Here’s a simple example demonstrating the basic syntax and structure of a C program. This program takes two integers from the user, adds them, and displays the result:
#include <stdio.h> // Include standard input/output library
int main() { // Main function: entry point of the program
int num1, num2; // Declare two integer variables
int sum; // Declare an integer to hold the result
// Prompt the user to enter two integers
printf("Enter first integer: ");
scanf("%d", &num1); // Read first integer from user and store in num1
printf("Enter second integer: ");
scanf("%d", &num2); // Read second integer from user and store in num2
sum = num1 + num2; // Add the two numbers and store the result in sum
// Display the result
printf("The sum of %d and %d is: %d\n", num1, num2, sum);
return 0; // Return 0 to indicate successful execution
}
Explanation of Code Structure and Syntax
1. Preprocessor Directive (#include <stdio.h>)
#include <stdio.h>is a preprocessor directive that includes the standard input/output library, which provides functions likeprintfandscanffor displaying text and receiving input from the user.- Directives starting with # are processed before compilation begins, allowing for library and macro inclusion.
2. Main Function (int main())
- The
mainfunction is the entry point for every C program. The execution of a program starts from this function. - It returns an integer value (
int) to the operating system, which traditionally indicates success or failure.return 0; at the end signals that the program ran successfully.
3. Variable Declarations
int num1, num2;declares two integer variables,num1andnum2, which will hold the input values.int sum;declares another integer variable,sum, to store the result of the addition.
4. Input and Output
printf("Enter first integer: ");prints a message prompting the user to input a value.scanf("%d", &num1);reads an integer from user input and stores it innum1. The%dformat specifier tellsscanfto expect an integer, and&num1is the address of the variable where the input is stored.- The same steps are repeated for
num2.
5. Computation
- s
um = num1 + num2;performs the addition ofnum1andnum2and stores the result in thesumvariable.
6. Displaying Results
printf("The sum of %d and %d is: %d\n", num1, num2, sum);outputs the result.- The format specifier
%dis used to insert the values ofnum1,num2, andsuminto the string, replacing each%dwith the corresponding value. \nis a newline character, which moves the cursor to a new line after printing.
7. Return Statement
return 0; ends the program, signaling that it finished successfully.
