beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

C Program to Add two numbers

By Chaitanya Singh | Filed Under: C Programs

We will write two programs to find the sum of two integer numbers entered by user. In the first program, the user is asked to enter two integer numbers and then program displays the sum of these numbers. In the second C program we are doing the same thing using user defined function.

Example 1: Program to add two integer numbers

To read the input numbers we are using scanf() function and then we are using printf() function to display the sum of these numbers. The %d used in scanf() and printf() functions is the format specifier which is used for int data types in C programming.

#include <stdio.h>
int main()
{
   int num1, num2, sum;
   printf("Enter first number: ");
   scanf("%d", &num1);
   printf("Enter second number: ");
   scanf("%d", &num2);

   sum = num1 + num2;
   printf("Sum of the entered numbers: %d", sum);
   return 0;
}

Output:

Enter first number: 20
Enter second number: 19
Sum of the entered numbers: 39

Example 2: Program to add two integers using function

In this program, we are writing the addition logic in the user defined function sum() and we are calling this function from the main function. To read about function, refer this guide: C Functions with example

#include <stdio.h>
/* User defined function sum that has two int
 * parameters. The function adds these numbers and
 * return the result of addition.
 */
int sum(int a, int b){
   return a+b;
}
int main()
{
   int num1, num2, num3;
   printf("Enter first number: ");
   scanf("%d", &num1);
   printf("Enter second number: ");
   scanf("%d", &num2);

   //Calling the function
   num3 = sum(num1, num2);
   printf("Sum of the entered numbers: %d", num3);
   return 0;
}

Output:

Enter first number: 22
Enter second number: 7
Sum of the entered numbers: 29

Check out these related C examples:

  1. C Program to check if number is even or odd
  2. C Program to find factorial of number
  3. C Program to check if number is Palindrome or not
  4. C Program to find the sum of array elements

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap