Look at below an example of C syntax with a simple program that adds two numbers.
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("The sum of %d and %d is %d", num1, num2, sum);
return 0;
}
In this program, we're using several elements of C syntax:
#include <stdio.h>
: This is a preprocessor directive that tells the compiler to include the standard input/output library, which provides functions likeprintf
andscanf
.int main()
: This is the main function of our program, which is where the program starts executing.int
specifies the return type of the function, and()
indicates that the function takes no arguments.int num1, num2, sum;
: These are variable declarations. We're declaring three variables of typeint
:num1
,num2
, andsum
.printf("Enter two numbers: ");
: This is a function call that prints the specified string to the console.scanf("%d %d", &num1, &num2);
: This is a function call that reads two integers from the console and stores them in the variablesnum1
andnum2
. The&
symbol before each variable name is the address-of operator, which gives the memory address of the variable.sum = num1 + num2;
: This is an assignment statement that calculates the sum ofnum1
andnum2
and stores the result in the variablesum
.printf("The sum of %d and %d is %d", num1, num2, sum);
: This is a function call that prints a formatted string to the console. The%d
placeholders are replaced with the values ofnum1
,num2
, andsum
.return 0;
: This statement terminates themain
function and returns the value0
to the operating system, indicating that the program completed successfully.
Comments