Wednesday, 8 January 2014

C Programming Language Tutorial VII- while loop

Introduction
While creating program we may have need to repeat some statement for appropriate output of program. But if we will do this task by creating repeated statement it may cause a very vast processing and ridiculous task. So to avoid such things we should be use loop.
Loop
The process of repeatedly executing a block of statement is known as looping. If the process of repeated execution takes for specified number of times it is called finite loop. If the process of repeated execution continues forever then it is known as infinite looping.
Loop enables programmer to developed programs containing repetitive processes.
In looping a sequence of statements executing repeatedly until some condition for termination of loop is satisfied.
For successful looping you have to check following four terms:
§  Initialization of variable to be use within loop
§  Execution of statements with in body of loop
§  Increment or decrement variable
§  Evaluate loop condition
C supports three types of loops
- while loop
- for loop
- do-while loop
While Loop
The condition is evaluated first, if it is true, the statements in the body will get executed. After execution of body of loop, it again evaluates condition and process is going on as long as the condition returns true. If the condition returns false the body of loop gets terminated.
while(condition)
{
  Body of loop;
}
Let us take a simple example to print “HELLO!” five times.
First let us discuss about program, here you want to print 5 times therefore you should have one counter that counts from 1 to 5. Then as per rule of loop you should have condition that is initially true and during execution at one stage it will get false. As you know that programming is not a magic hence you should give increment to counter for executing one by one step.
//prog to print "Hello" message 5 times
#include<stdio.h>
#include<conio.h>
void main()
{
 int cnt=1;            //initialization
 clrscr();
 while(cnt<=5)     //condition
 {
  printf("\nHello");
  cnt++;               //increment
  }
 getch();
}
o/p:
Hello
Hello
Hello
Hello
Hello
Modify above program and instead of 5 times you can enter number of times as a user input. It is too easy just try it.
You should make a program to print 1 to 10 numbers.
We will make a program to print sum of 1 to 10 numbers. For this program you simply require counter and sum variable.
e.g. 1+2+3+4+5+6+7+8+9+10 = 55
//prog to print sum of 1 to 10 numbers
#include<stdio.h>
#include<conio.h>
void main()
{
 int cnt=1,sum=0; //sum will use both side of = operator hence it is necessary to assign zero to sum to avoid garbage value
 clrscr();
 while(cnt<=10)     //condition
 {
    sum = sum + cnt; //sum appears as lvalue(left side value) as well as rvalue (right side value)*
    cnt++;               //increment
  }
  Printf(“\nSum of 1-10 numbers = %d”,sum);
 getch();
}
o/p:
Sum of 1-10 numbers = 55
*when any variable needs to use as lvalue and rvalue then it is necessary to assign some value to it.
You can be modifying above program by calculating average.
Let us take an example to print multiplication table. E.g. see the following table of number 5 is –
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10= 50

Think of how to create program and how many variables are require? Let us think step by step, as you have seen in above table you will need total three variables, one for number, second for counter and third for answer. Now you are ready to create program
//multiplication table
#include<stdio.h>
#include<conio.h>
void main()
{
  int num,cnt=1,ans;
  clrscr();
  printf("\nEnter any number for table: "); 
  scanf("%d",&num);
  printf("\nMultiplication Table: ");
  while(cnt<=10)            //condition         
   {
      ans = num * c;        //process 
      printf("\n%d * %-2d = %d",num,cnt,ans);  //It will print above mentioned output
      cnt++;
   }
   getch();
}
o/p:
Enter any number for table: 12
12
24
36
48
60
72
84
96
108
120
Be continuing with other programs.
Now let us simply create a program to calculate factorial of given number
Factorial of 5 is 5 x 4 x 3 x 2 x 1=120
In this case you should have variable that has initially some value and update during program execution.
/* PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER */
#include<stdio.h>
#include<conio.h>
void main()
{
long int n,fact=1; //fact = 1 because this value use for multiplication and update during program execution
 clrscr();
printf("\nEnter number for factorial: ");
scanf("%d",*n);

 while(n>0)  //process is going on till n is greater than zero
 {
   fact=fact*n;  //main process for calculating fact
   n--;              //for proper execution the value of n should be decrement
  }
  printf("\nFactorial of number = %ld",fact);
  getch();
  }
o/p:
Enter number to find factorial: 5
Factorial of number = 120
In above program long int is used because range of integer is not sufficient.
Crate a program to print reverse and sum of given number. For this program we have variables rev(reverse), sum and rem(remainder) and num(number).
//program to find reverse & sum of all digit of number
#include<stdio.h>
#include<conio.h>
void main()
{                                                    
 int num,rem,rev=0;
 clrscr();
 printf("\nEnter any number: ");
 scanf("%d",&num);
 while(num>0)
 {
  rem = num % 10;    //rem is found by modulus (%) operator if the number is 123 then rem is 3, 2 and 1 respectively. You can try it by manual
  num = num / 10;    
  rev = rem + rev * 10;   //initially rev=0 and sum=0, then it is change during each step of loop
  sum = sum + rem;
 }
 printf("\nReverse of given number = %d",rev);
 printf("\nSum of all digit of given number = %d",sum);
 getch();
}
o/p:
Enter any number: 572
Reverse of given number = 275
Sum of all digit of given number = 14
Modify above program and check whether number is palindrome or not.
The palindrome number is finding by checking equality to its reverse. If reverse of number is same as number then only it is palindrome number.
e.g. – 1221, 6336, 929, 717 etc.
In above program, after finding reverse, check this rev with given number. If the condition is true then print number is palindrome else not palindrome.
//program to check whether given number is palindrome or not palindrome
#include<stdio.h>
#include<conio.h>
void main()
{
 int no,rem,rev=0,temp;  ;   
 clrscr();
 printf("\nEnter any number: ");
 scanf("%d",&no);
 temp=no;   ;    //assigns value of number to temp variable because after successful termination of while loop value of number is zero.
 while(no>0)
 {
  rem = no % 10;
  no = no / 10;
  rev = rem + rev * 10;
 }
 if(temp == rev)   //check whether the value of temp (copy of no) is equal to rev
  printf("\n%d is palindrome number",temp);
 else
  printf("\n%d is not palindrome number",temp);
 getch();
}
o/p:
Enter any number: 575
575 is palindrome number.
Assignments:
  1. Write a program to calculate power by given base value and exponent. e.g. if base is 2 and exponent is 3 then power is 8 (2x2x2=8). For this program see the logic of factorial.
  1. Write a program to check whether given number is Armstrong or not. (Armstrong number is a sum of cube of all digit)
e.g. number = 153
                    = (1x1x1) + (5x5x5) + (3x3x3)
                    = 1+120+27
                    =153
You need to first find remainder and calculate cube of it for calculating sum. Then after executing loop check whether the sum and number is same.
Let us create a simple program to check whether given number is prime or not. Prime is a number that is divisible by 1 and itself only.
For this program the variables are, no for number, one counter (cnt)  that starts from 1 till num, and one more counter (k) to count how many times num is divisible i.e. how many times remainder is zero.

//prog to check prime number
#include<stdio.h>
#include<conio.h>
void main()
{
 int no,cnt=1,k=0;
 clrscr();
 printf("\nEnter any number: ");
 scanf("%d",&no);
 while(cnt<=no)  //cnt goes till number
 {
   if(no%cnt==0)  //check whether it is divisible
  {
   k++;
  }
  cnt++;
 }
 if(k==2)
  printf("\n%d is prime number",no);
 else
  printf("\n%d is not prime number",no);
  getch();
 }
o/p:
Enter any number: 7
7 is prime number

No comments:

Post a Comment