C program to add two numbers. There are three program examples – 1) Simple, 2) by user input, and 3) using a function.
Simple C program to add two numbers
Lets declare two int variables a and b with value 10 and 20. Declare one more variable sum of it type that will store the sum result. Using + operator, add two variables a and b. so, sum = a+b.
Print the result sum using printf function.
/*
* C program to add two numbers
*/
#include <stdio.h>
int main(){
//declare two numbers
int a =10;
int b = 20;
int sum =0;
//add variables
sum = a+b;
//print the sum
printf("sum = %d",sum);
return 0;
}
Output:
sum = 30
C program to add two numbers from user input.
You can prompt user to enter two numbers and sum them as above program. Use printf function to prompt user to enter the number and read it with scanf function.
/*
* C program to add two numbers from user input
*/
#include <stdio.h>
int main(){
int a,b;
int sum =0;
//Prompt user to enter two numbers
printf("Enter 1st number ");
scanf("%d",&a);
printf("Enter 2nd number ");
scanf("%d",&b);
//add variables
sum = a+b;
//print the sum
printf("sum = %d",sum);
return 0;
}
C program to add two numbers using functions
Create a user defined function add with two arguments and return the sum. Call sum function in main() with both arguments. sum function will return the sum.
/*
* C program to add two numbers using functions
*/
#include <stdio.h>
int add(int a, int b){
//return sum
return a + b;
}
int main(){
int a,b;
int sum =0;
//Prompt user to enter two numbers
printf("Enter 1st number ");
scanf("%d",&a);
printf("Enter 2nd number ");
scanf("%d",&b);
//call function with supplying
//both arguments a and b
sum =add(a,b);
//print the sum
printf("sum = %d",sum);
return 0;
}
Output:
Enter 1st number 5
Enter 2nd number 6
sum = 11