When you find yourself copy/pasting blocks of code, then that code is a good candidate for a function. The only challenge you may face, if you're still very new, is how to get two values (e.g. "first" and "second") from a function, when a function can only return one value. The solution is to pass pointers to the variables of interest, so their values can be updated in the called function.
For example:
Code:
#include <stdio.h>
void get_two_numbers( int *n1, int *n2 ); // expects two pointers to int
int main(void)
{
int x1, x2;
get_two_numbers(&x1, &x2); // pass addresses of x1 and x2
printf("\nx1 is %d\nx2 is %d\n", x1, x2);
return 0;
}
void get_two_numbers( int *n1, int *n2 )
{
int num1, num2;
puts("Enter 1st number:");
scanf("%d", &num1); // error checking omitted
puts("Enter 2nd number:");
scanf("%d", &num2); // error checking omitted
*n1 = num1; // dereference "n1" and store the value of "num1"
*n2 = num2; // dereference "n2" and store the value of "num2"
}
In "get_two_numbers()", you wouldn't even need local variables. Note the slightly difference scanf() calls, since "n1" and "n2" are already pointers:
Code:
void get_two_numbers( int *n1, int *n2 )
{
puts("Enter 1st number:");
scanf("%d", n1); // error checking omitted; no '&' operator since n1 already a pointer
puts("Enter 2nd number:");
scanf("%d", n2); // error checking omitted; no '&' operator since n2 already a pointer
}
If this seems over your head at this time, an easier solution would be to pass a char that indicates the operation you wish to perform. Then your function can read two values, perform the indicated operation, and simply return an answer.