Tuesday, November 27, 2012

Looping Cont.


Last Session Practice :

write a program that takes two number from user and print the odd numbers in between.


input:

1 10

output:

1 3 5 7 9
#include<stdio.h>
int main()
{
   int i,end,start;
   
   printf("please enter two number\n");
   scanf("%d%d",&start,&end);
   for(i=start;i<end+1;i++)  
   {
             if(i%2!=0)  
                  printf("%d\n",i);  
   }
  return 0;
}
Session Agenda:
  1. While Loop
  2. Practice
While Loop

let's us see another form of looping called "While".
doing the same as for loop  "doing some code many times" but it has different syntax.

 while(condition  is true)

{
   //while my condition is true do this code.
   
   //some code

}



Example:
try to make the previous program using while loop.

#include<stdio.h>
int main()
{
   int i,end,start;
   
   printf("please enter two number\n");
   scanf("%d%d",&start,&end);
   i=start;

while(i<end+1) 
   {
             if(i%2!=0)  
                  printf("%d\n",i);
             i++;
   }
  return 0;
}

Finally , you can use whatever form you wish nothing recommended as you saw they are similar in Task & different in syntax.

Practice 

1- Write a program that print a square of asterisks after taking the number of lines from the user.


input
3  
output
***
***
***


input
5  
output
*****
*****
*****
*****
*****


2- modify the last program to print a rectangle instead of a square.


input
4  3

output
***
***
***
***

input
3  5

output
*****
*****
*****

3- write a program that print a triangle of asterisks after taking the number of lines.

input
4

output
*
**
***
****

4- modify the previous program to print a triangle of asterisks but upside down.



input

4

output
****
***
**
*

5- what about this triangle can you code this one ?


input
4

output
****
 ***
  **
   *

try to think about these practice problems to be sure that you can use loops very well in your code.

solutions will be posted later :). 



No comments:

Post a Comment