Wednesday, 26 June 2013

C Programming Language Tutorial X- Nested for loop

Nested for loop

Note: Before beginning with this lesson you should study the previous lessons of C Programming Language Tutorial VIII and should read beginning part of C Programming Language Tutorial IX. This is mandatory to understand the concept of nested for loop.

Let us perform some programs of nested for loop:
You can write first program as you had done in nested while loop in which you had printing value of i and j.


//By nested for loop program to print Asteriks Graph
#include<stdio.h>
#include<conio.h>

void main()
{
 int r,c;
 clrscr();

 for(r=1;r<=5;r++)    //rows start from one till 5
 {
  for(c=1;c<=r;c++)  //columns start from one till current value of r
  {
     printf("* ");
  }
    printf("\n");        //after finishing inner loop used ‘\n’ for a new line
 }
 getch();
}
o/p:
*
* *
* * *
* * * *
* * * * *
//Asterik's graph
#include<stdio.h>
#include<conio.h>

main()
{
  int r,c,n;
  clrscr();

  printf("\nEnter number of rows");  
  scanf("%d",&n);

  for(r=1;r<=n;r++)    //n is used instead of fixed value 5
  {
    for(c=1;c<=r;c++)
    {
      printf("* ");
    }
    printf("\n");
  }
  getch();
} 
Enter number of rows: 7
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *


What should do if you want a opposite pattern i.e. first 5 rows then 4..3..2..1. for this program you have to change inner loop to for(c=n;c>=r;c- -). After this change you will get following output

* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*


//Asterik's graph in triangle shape
#include<stdio.h>
#include<conio.h>

main()
{
  int r,c,n,sp;
  clrscr();

  printf("\n Enter number of rows:  ");
  scanf("%d",&n);

  for(r=1;r<=n;r++)
  {
    for(sp=1;sp<=r;sp++)   //space is used for getting triangle pattern. Space starts from 1 till current value of row i.e. in 1st row one space, in 2nd row two spaces like this spaces will print.
    {
      printf(" ");   //put a single space in printf
    }
    for(c=n;c>=r;c--)
    {
      printf("* ");
    }
    printf("\n");
  }
  getch();
}
o/p:
Enter no. of rows?
10
 * * * * * * * * * *
  * * * * * * * * *
   * * * * * * * *
    * * * * * * *
     * * * * * *
      * * * * *
       * * * *
        * * *
         * *
          *

Now you can try following output
       *
      * *
     * * *
    * * * *
   * * * * *
  * * * * * *
 * * * * * * *
* * * * * * *
  * * * * * *
    * * * * *
      * * * *
        * * *
           * *
             *

Let us use values instead of ‘*’

//By nested for loop program to print Asteriks Graph
#include<stdio.h>
#include<conio.h>

void main()
{
 int r,c;
 clrscr();

 for(r=1;r<=5;r++)    //rows start from one till 5
 {
  for(c=1;c<=r;c++)  //columns start from one till current value of r
  {
     printf("%d ",c);   //current value of column 
  }
    printf("\n");        //after finishing inner loop used ‘\n’ for a new line
 }
 getch();
}
o/p:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Assignments
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
1
2 3
4 5 6
7 8 9 10
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1


Let us use only 0 and 1 instead of values

//By nested for loop program to print Asteriks Graph
#include<stdio.h>
#include<conio.h>

void main()
{
 int r,c;
 clrscr();

 for(r=1;r<=5;r++)    //rows start from one till 5
 {
  for(c=1;c<=r;c++)  //columns start from one till current value of r
  {
    If((c+1)%2==0) //if if is true then it will print 1 else 0
        printf("1 ");  
    else
        printf("0 ");  
  }
    printf("\n");        //after finishing inner loop used ‘\n’ for a new line
 }
 getch();
}
o/p:
1
1 0
1 0 1
1 0 1 0
1 0 1 0 1

Assignments

1
0 0
1 1 1
0 0 0 0
1 1 1 1 1
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
0
1 1
0 0 0
1 1 1 1
0 0 0 0 0

Monday, 24 June 2013

C Programming Language Tutorial IX- Nested while loop

Nested while loop

Note: Before beginning with this lesson you should see the previous lessons of C Programming Language Tutorial VII. This is helping you to understand the concept of nested loop.

Nested Loop:
In case of nested loop, you have more than one loop. The structure of nested loop is loop within loop. If for loop is within while loop or for loop within for loop or while loop within for loop and vice versa known as nested loop.
In this case first outer condition is evaluated and then first inner loop gets execute till the inner condition is true. After termination of inner loop, outer loop gets executed and inner loop get reset this whole cycle is going on till the outer condition is true. Let us clear this concept by following syntax:

Nested while loop

            while(outer condition)
             {
                while(inner condition)
                {
                    -------
                   -------
                    -------
                }
             }



While creating program of nested loop you must be think of each and every step.
e.g. – what is outer condition?
          What is inner condition?
           How to reset inner loop?            
Let us see in details, generally outer condition is useful only to jump value step by step. i.e. if num=1 then it will 2,3,4……. till given range. Use inner condition same as you had used in case of while loop. Reset loop means to set any variable of inner loop at previous initialized value.


You have to study following program to grip concept of working of nested loop –

//nested while loop
#include<stdio.h>
#include<conio.h>

void main()
{
  int i=1,j=1;        //declaration and initialization of variables
  clrscr();

   while(i<=5)     //outer condition
   {
     while(j<=3)   //inner condition
     {
        printf("\ni = %d \t j = %d",i,j);    //simply print value of i and j
        j++;           //increment to j for getting termination of inner loop
      }
       printf("\n------------------------------------");
       j = 1;          //reset inner loop
       i++;           // increment to i for getting termination of outer loop
    }
     getch();
}         
o/p:
i = 1         j = 1
i = 1         j = 2
i = 1         j = 3
i = 2         j = 1
i = 2         j = 2
i = 2         j = 3
i = 3         j = 1
i = 3         j = 2
i = 3         j = 3
i = 4         j = 1
i = 4         j = 2
i = 4         j = 3
i = 5         j = 1
i = 5         j = 2
i = 5         j = 3



You have created program to print multiplication table of given number. But if you have a set or range of numbers and want to print multiplication table of each value then you can simply apply nested loop.
Let us see:

//multiplication table
#include<stdio.h>
#include<conio.h>

void main()
{
  int num=1,cnt=1,ans,range;
  clrscr();

  printf("\nEnter any range for table: "); 
  scanf("%d",&range);

 while(num<=range)  //outer loop is used to jump one by one number till range
 {
   printf("\nMultiplication Table of %d : \n",num);
//you can find that inner loop is same as you have used while printing multiplication table of single number         
  while(cnt<=10)           
   {
      ans = num * cnt;        //process 
      printf("\n%d * %-2d = %d",num,cnt,ans);  //It will print following mentioned output
      cnt++;
   }
   cnt=1;   //after printing table for one time you must need to reset counter for next set of numbers
   num++; //it will give you next number
}
   getch();
}
o/p:
Enter any range for table: 3

Multiplication Table of 1 :

1 * 1  = 1
1 * 2  = 2
1 * 3  = 3
1 * 4  = 4
1 * 5  = 5
1 * 6  = 6
1 * 7  = 7
1 * 8  = 8
1 * 9  = 9
1 * 10 = 10

Multiplication Table of 2 :

2 * 1  = 2
2 * 2  = 4
2 * 3  = 6
2 * 4  = 8
2 * 5  = 10
2 * 6  = 12
2 * 7  = 14
2 * 8  = 16
2 * 9  = 18
2 * 10 = 20

Multiplication Table of 3 :

3 * 1  = 3
3 * 2  = 6
3 * 3  = 9
3 * 4  = 12
3 * 5  = 15
3 * 6  = 18
3 * 7  = 21
3 * 8  = 24
3 * 9  = 27
3 * 10 = 30

Assignment: From above program you can be modify program of factorial by using range and print sum of all factorial.

In previous lesson you know that how to check whether given number is palindrome or not palindrome. Now you can apply range to find all palindrome numbers from given range.
Let us see the program –

//program to print all palindrome numbers from given range
#include<stdio.h>
#include<conio.h>

void main()
{
 int no=100,rem,rev=0,temp,range;      //number starts from zero
 clrscr();

 printf("\nEnter any range: ");
 scanf("%d",&range);              //range must be greater than 100

while(no<=range)                   //number goes from 100 till given range
{
 temp=no;      //assigns value of number to temp

 while(temp>0)   //temp is used here because you will need current value of number in outer loop
 {
  rem = temp % 10;
  temp = temp / 10;
  rev = rem + rev * 10;
 }

 if(no == rev)   //check whether the value of no is equal to rev
  printf("\nPalindrome number = %d",no);

rev=0;  //for each number rev=0 again
no++;  //increment to get next number
}
 getch();
}
o/p:

Enter any range: 200

Palindrome number = 101
Palindrome number = 111
Palindrome number = 121
Palindrome number = 131
Palindrome number = 141
Palindrome number = 151
Palindrome number = 161
Palindrome number = 171
Palindrome number = 181
Palindrome number = 191


Assignment : Create a program to print all prime numbers by setting start range and end range. 

Wednesday, 19 June 2013

C Programming Language Tutorial VIII- for loop, do while loop


for Loop
For loop is most popular and concise loop. It is also simplified version of loop. It takes care of initialization of loop control, evaluating the loop condition and proper increment or decrement.

 for(initialization;condition;increment/decrement)
{
    Loop body;
}


The programs done in previous lesson (while loop) are easily converted to for loop. E.g. take a previously done program of factorial.

/* PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER */
#include<stdio.h>
#include<conio.h>

void main()
{
int n,c;
long fact; //fact = 1 because this value use for multiplication and update during program ans c is used to count from 1 to number
 clrscr();

printf(“\n Enter number to find factorial: “);
scanf(“%d”,&n);

 for(c=1;c<=n;c++)  //initialization, condition and increment section is combined. It is starting from initialization and after checking condition increment section gets executed. Later during the program initialization is not perform again where as only increment section continue till the condition is true.
 {
   fact=fact*c;  //main process for calculating fact
   c++;              //for proper execution the value of c should be increment
  }
  printf("\nFactorial of number = %ld",fact);
  getch();
  }
o/p:
Enter number to find factorial: 5
Factorial of number = 120

In for loop section break is done by semicolon (;) and only two semicolons are allowed. If you have more than one initialization, condition and increment or decrement then also you have to break section by semicolon and partition of section is done by coma (,).
Have a look at following program:

//prog to print number in ascending and descending order by for loop
#include<stdio.h>
#include<conio.h>

void main()
{
   int a,b;
   clrscr();

  for(a=1,b=10;a<=10,b>=1;a++,b--)  //for has more than one variable. Separation done by coma and for section break semicolon is used
  {
     printf(“\n a = %d \t b = %d”,a,b);
  }
  getch();
}
o/p:
a = 1         b= 10
a = 2         b= 9
a = 3         b= 8
a = 4         b= 7
a = 5         b= 6
a = 6         b= 5
a = 7         b= 4
a = 8         b= 3
a = 9         b= 2
a = 10       b= 1

This is only introduction of for loop we will see detail programming of it in the lesson of nested loop. For loop mostly use while creating set (array, matrix, structure) programs.

do while Loop
The loop statements discussed previously, must evaluate condition at first and then body of loop gets executed. But in some cases, it may be necessary to execute the body of loop before the condition evaluated. In such situation you can use do while loop.
do while loop executes the body of loop at least once before evaluating condition.

do
{
 Body of loop;
}
while(condition);



Let us check the following program that accept single alphabet from user and continue the execution if user entered ‘y’ else execution will over.

//program to check working of do-while
#include<stdio.h>
#include<conio.h>

void main()
{
 char ans;    //variable for accepting single character as input (single alphabet)
 clrscr();

 do
 {
   printf("Do you want to print message?\n");
   flushall();  //it is mostly use while accepting single character from user to clean buffer(temporary memory storage)
   scanf("%c",&ans);

   printf("Welcome\n");

 }
 while(ans=='y');  //post condition checked
 getch();
}
o/p:
Do you want to print message?
y
Welcome
Do you want to print message?
n
Welcome

If you execute the above program then you will find that it first execute do part and then continue process by evaluating while condition every time. The program execution will terminate when user entered other than ‘y’ alphabet.


//program to print Fibonaci's series up to n steps
#include<stdio.h>
#include<conio.h>

void main()
{
 int f0=0,f1=1,f2,c=1,steps;
 clrscr();

 printf("\nEnter steps for series: ");
 scanf("%d",&steps);

 printf("\nFibonaci's series up to %d steps\n",steps);
 printf("%d\t%d\t",f0,f1);

 do
 {
  f2 = f0 + f1;    //simple formula for calculating Fibonaci’s series
  printf("%d\t",f2);    
  f0=f1;            //swap the value of f1 to f0 and f2 to f1
  f1=f2;
  c++;             //counts the steps
 }
 while(c<=steps-2);   //we have performed two steps before beginning loop
 getch();
}
o/p:
Enter steps for series: 7
Fibonaci's series up to 7 steps
0   1   1   2   3   5   8

Do while loop useful in case of switch (menu driven programming) where we were used goto in C Programming Language Tutorial VI. Let us do it.

//program using switch statement
#include<stdio.h>
#include<conio.h>

void main()
{
 int no1,no2,choice;
 clrscr();

 printf("\nEnter two numbers: ");
 scanf("%d%d",&no1,&no2);

// program will repeat from this point
 do
 {
 printf("\n==================================");  //menu list
 printf("\n1 . Addition");
 printf("\n2 . Subtraction");
 printf("\n3 . Multiplication");
 printf("\n4 . Division");
 printf("\n5 . Exit");
 printf("\n===================================");

 printf("\nEnter your choice: "); //accepts choice from user
 scanf("%d",&choice);

 switch(choice)  //switch starts working by checking value of choice
 {
   case 1:
              printf("\nAddition = %d", no1+no2);
              break;
   case 2:
               printf("\nSubtraction = %d",no1-no2);
               break;
   case 3:
               printf("\nMultiplication = %d",(no1+no2)/2);
               break;
   case 4:
               printf("\nDivision = %d",no1/no2);
               break;
   case 5:
               exit(0);  //library function for exiting program
   default :
              printf("\nWrong Entry");
 }
 While(choice<=5);  //continue execution till you select exit case
 getch();
}


In next some topics we will use do-while as per requirement. This loop is rarely use in programming. 

Popular Posts