C Programming
Structure of a C Program
Preprocessor directives
Main function()
{
Local declarations; Body of main function
Statements;
}
User-defined functions
Function 1
Function 2 option to user
Function 3
#include <stdio.h>
#include <conio.h>
int main()
{
printf("Hello World!");
return 0;
}
General Syntax of printf:
printf(control string, list of arguments);
// Ask the user to type a number
printf("Type a number: \n");
// Output the number the user typed
printf("Your number is: %d", myNum);
// Output the float value with 2 digits after decimal e.g. 56.21 or 423.00
printf("Product: %.2f\n", product);
General Syntax of scanf:
scanf(“format specifiers”, list of variables);
// Get and save the number the user types
scanf("%d", &myNum);
scanf("%d,%d", &x,&y);
Conditional Control Structures if, if else, else-if, switch
General Syntax of if:
Example:
if(condition) if (20 > 18)
{
{
Block of statements; printf("20 is greater than 18");
} }
General Syntax of if else: Example:
int time = 20;
if(condition)
if (time < 18)
{
{
Block of statements; printf("Good day.");
} }
else else {
{ printf("Good evening."); Example:
Block of statements;
} }
General Syntax of else-if:
if(condition-1)
{ Example:
Block of statements;
int myNum = 10; // Is this a positive or
}
negative number?
else if(condition-2) if (myNum > 0)
{ {
Block of statements; printf("The value is a positive number.");
}
}
else if (myNum < 0)
else if(condition-3) {
{ printf("The value is a negative number.");
Block of statements; }
else
}
{
. printf("The value is 0.");
. }
.
else
{
Block of statements;
}
General Syntax of switch: Example:
switch(expression) int day = 0;
{
printf("Enter weekday number between 1-7 to
case const-1: calculate the weekday name: ");
Statements; scanf("%d", &day);
break; switch (day)
case const-2:
{
Statements; case 1:
break; printf("\n Monday");
case const-3: break;
Statements; case 2:
break; printf("\n Tuesday");
. break;
. case 3:
. printf("\n Wednesday");
default: break;
Statements; case 4:
}
printf("\n Thursday");
break;
case 5:
printf("\n Friday");
break;
case 6:
printf("\n Saturday");
break;
case 7:
printf("\n Sunday");
break;
default:
printf("Enter number between 1-7");
}
Loop Control Structures (for loop)
General Syntax of for:
for (initialization; condition; increment/decrement)
{
Block of statements
}
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. int main()
4. {
5. int i=0;
for(i=1; i<=10; i++)
{
printf("%d \n",i);
}
6. return 0;
7. }
Example:
(while loop) #include<stdio.h>
#include<conio.h>
General Syntax of while: int main()
{
while (Test condition)
int i=1;
{ while(i<=10)
Block of statements {
} printf("%d \n",i);
i++;
}
return 0;
Example:
(do-while loop)
#include<stdio.h>
#include<conio.h>
General Syntax of do-while:
int main()
{
do{
Block of statements int i=1;
do{
} while(Test condition);
printf("%d \n",i);
i++;
} while(i<=10);
return 0;
}