Wednesday 22 January 2014

Constructs:


There are two types of constructs in C programming language.

1. Conditional Constructs.
2. Loop Constructs.

Conditional Constructs are two types.    A) If … else statements.    B) Switch case.


Loop Constructs are three types.     A) For loop.  B) While loop.  C) Do … while loop.


If else :

#include<stdio.h>
void main()
{
int x;
printf("Enter a number :\n");
scanf("%d",&x);
if(x%2==0)
{
printf("It's a EVEN number \n");
}
else
{
printf("It's a ODD number \n");
}
}



Switch case :

#include<stdio.h>
void main()
{
printf("1. Sum\n");
printf("2. Substract\n");
printf("3. Multi\n");
printf("4. Div\n");
printf("Enter your choice :\n");
int x;
scanf("%d",&x);
switch(x)
{
int a,b,c;
case 1:
printf(":::  Sum  :::\n");
printf("Enter two numbers :\n");
scanf("%d%d",&a,&b);
c=a+b;
printf("Sum of two numbers is %d\n",c);
break;
case 2:
printf(":::  Substract  :::\n");
printf("Enter two numbers :\n");
scanf("%d%d",&a,&b);
c=a-b;
printf("Substract of two numbers is %d\n",c);
break;
case 3:
printf(":::  Multi  :::\n");
printf("Enter two numbers :\n");
scanf("%d%d",&a,&b);
c=a*b;
printf("Multi of two numbers is %d\n",c);
break;
case 4:
printf(":::  Div  :::\n");
printf("Enter two numbers :\n");
scanf("%d%d",&a,&b);
c=a/b;
printf("Division of two numbers is %d\n",c);
break;
default:
printf(" Invalid Choice. \n");
}
}



LOOP :-

For loop :

#include<stdio.h>
void main()
{
int x,sum,cnt;
printf(":::  Sum of 5 numbers  :::\n\n");
printf("Enter 5 numbers :\n");
for(cnt=sum=0;cnt<5;cnt++)
{
scanf("%d",&x);
sum=sum+x;
}
printf("The result is :%d\n",sum);
}


While loop : 

#include<stdio.h>
void main()
{
int x,sum,cnt;
cnt=sum=0;
printf(":::  Sum of 5 numbers  :::\n\n");
printf("Enter 5 numbers :\n");
while(cnt<5)
{
scanf("%d",&x);
sum=sum+x;
cnt++;
}
printf("The result is :%d\n",sum);
}


Do ... while loop :

#include<stdio.h>
void main()
{
int x,sum,cnt;
cnt=sum=0;
printf(":::  Sum of 5 numbers  :::\n\n");
printf("Enter 5 numbers :\n");
do
{
scanf("%d",&x);
sum=sum+x;
cnt++;
}while(cnt<5);
printf("The result is :%d\n",sum);
}

The preceding snippet is output of the above loop programs...





No comments:

Post a Comment

Thanks For Giving Comment In Our Blog.