logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jun08/min.c

/* 

finds the min of two numbers using a function

refer to C Lesson 4 on the class website and the link to 
Chapter 13: Functions on Tutorialspoint for more info

*/
#include <stdio.h>




int min(int a1, int a2); //function declaration
/*

	a function declaration tells the compiler about a function name and how to 
	call the function. We can define the function below the main function.

	to write a function declaration, you need to write it in the following manner

	return_type function_name(arguments);

	the return type is int, meaning that it returns an integer

	the function name is min

	the arguments are that this function takes two integers, and within this function
	we are naming them a1 and a2

	Note: you can omit the function declaration statement if you define your function 
		  above the main function instead of below the main function as i've done here. 
*/

int main(){

	int num1, num2; 
	printf("Enter two numbers: ");
	scanf("%d %d", &num1, &num2);

	//we call our function min below, giving it num1 and num2
	int answer = min(num1, num2); 

	printf("%d is smaller\n", answer);

	return 0;

}



//here, we define the function min
int min(int a1, int a2){ 

	int result; //declaring a variable for result
				//result can only be used inside this function

	//we get our values for a1 and a2 from when we passed in num1 and num2
	//when we called the function in main

	//for the purposes of this function, if the two numbers are equal, just return 
	//either a1 or a2, this is closest to how an actual program would handle this situation
	if(a1 <= a2)  
		result = a1;
	else if (a2 < a1)
		result = a2;


	return result; //this ends the function and sends  whatever is in result
				   //to the variable "answer" back in the main function.

}