This C program to add two numbers takes two numbers as input from user and add them using '+' arithmetic operator and prints the sum on screen. Addition operator in C correspond literally to their respective mathematical operators. If user enters 2 and 3 as input numbers then 5(2 + 3) will be printed as sum on screen.
C program to add two numbers using '+' operator
In this program, we first take two numbers as input from user using scanf function and stores them in integer variable firstNumber and secondNumber. Then we add firstNumber and secondNumber using '+' operator and stores the result in variable 'sum'. Finally, we print the sum on screen using printf function.
#include <stdio.h> int main(){ /* Integer variable declation */ int firstNumber, secondNumber, sum; printf("Enter First Number: "); scanf("%d", &firstNumber); printf("Enter Second Number: "); scanf("%d", &secondNumber); sum = firstNumber + secondNumber; printf("Sum of %d and %d is %d", firstNumber, secondNumber, sum); return 0; }Output
Enter First Number: 2 Enter Second Number: 4 Sum of 2 and 4 is 6
C program to add two numbers using function
This program takes two numbers as input from user and pass it to a user defined function 'getSum'. Function 'getSum' takes two numbers as input parameter and returns sum of the input arguments.
#include <stdio.h> int getSum(int num1, int num2); int main(){ int firstNumber, secondNumber, sum; printf("Enter First Number: "); scanf("%d", &firstNumber); printf("Enter Second Number: "); scanf("%d", &secondNumber); sum = getSum(firstNumber, secondNumber); printf("Sum of %d and %d is %d", firstNumber, secondNumber, sum); return 0; } int getSum(int num1, int num2){ int sum; sum = num1 + num2; return sum; }Output
Enter First Number: 4 Enter Second Number: 5 Sum of 2 and 4 is 9
C Program to add two numbers using pointers
This program uses two integer pointer to store the memory address of two operands. It first takes two integers as input from user using scanf function and stores them in firstNumber and secondNumber integer variable. Next step is to assign the addresses of these two input variables to integer pointers. Then value of operator is used to access the data stored in the memory location pointed by these pointer to find the sum.
#include <stdio.h> int main(){ int firstNumber, secondNumber, sum; /* Pointers declaration */ int *firstNumberPointer, *secondNumberPointer; printf("Enter two numbers \n"); scanf("%d %d", &firstNumber, &secondNumber); /* Pointer assignment*/ firstNumberPointer = &firstNumber; secondNumberPointer = &secondNumber; sum = *firstNumberPointer + *secondNumberPointer; printf("SUM = %d", sum); return 0; }Output
Enter two numbers 3 8 SUM = 11
Related Topics