In this article, we will delve into the practical aspect of programming in C language, particularly focusing on a fundamental operation – addition of two numbers. Although it seems basic, it serves as a cornerstone for understanding larger, more complex programs.
Adding Two Numbers in C
Adding two numbers in the C language is a straightforward task and is usually the first step for beginners to understand the syntax and structure of the language.
Below is the simple program to add two numbers:
Let’s break down this code to understand each component:
: This is a preprocessor command that includes the standard input-output library functions. The printf and scanf functions used in this program are part of this library.
- int main(): This is the main function where the program execution begins. The int keyword before main signifies that the main function will return an integer value.
- int num1, num2, sum;: These are integer variable declarations. num1 and num2 are the numbers to be added and sum will hold the result of the addition.
- printf(“Enter first number: “);: This function is used to print the string inside the double quotation marks onto the console.
- scanf(“%d”, &num1);: The scanf function is used to receive the user’s input. The %d format specifier is used to scan an integer number. The & symbol is the address operator and is used here to provide the memory location for storing the input value.
- sum = num1 + num2;: This is the arithmetic operation where the numbers num1 and num2 are added and the result is assigned to the sum variable.
- printf(“Sum of the entered numbers: %d”, sum);: This function is used to print the result onto the console. The %d is a placeholder for the integer that will be replaced by the value of the sum variable.
- return 0;: This statement signifies the successful termination of the program. It returns the control from the main function back to the operating system.
The ability to add two numbers may seem trivial, but understanding the syntax, variable declaration, user input, and console output in C is fundamental for developing more complex applications. As you progress in your programming journey, these principles will form the foundation of your knowledge and enable you to tackle more complex problems.