Showing posts sorted by relevance for query loop. Sort by date Show all posts
Showing posts sorted by relevance for query loop. Sort by date Show all posts

Sunday, 3 October 2010

17. Use The For Loop

The for loop is one of C's three statements. It allows one or more statements to be repeated. The for  loop is considered by many C programmers to be its mast flexible loop. The for loop is used to repeat a statement or block of statements a specified number of tims. It's general form repeating a single statement is shown here.



for(initialization;conditionl-test;increnent or descrement)
statement;



The initialization scction is used to give an initial value to the variable that controls the loop. This varible is usually referred to as the loop-control. The initialization section is executed only before the loop be gins. Then execute the conditional-test. If the condition true then the program execute the statement. When the statement is end then the program come back in the increment statement. After increment test the condition if the condition is true then the program executed the statement. It will be continue. When the condition will be wrong the for loop is end.



Example:
As a simple first example. This program use a for loop to print the numbers 1 through 10 on the screen.

#include<stdio.h>
void main()
{
int num;
for(num=1; num<11; num=num+1)
printf("%d",num);
printf("terminating");
getch();
}

This program produces the following output:
1 2 3 4 5 6 7 8 9 10 treminating.
The program works works like this :
First, the loop control variable num is initialixed to 1. Next, the cxpession num<11 is evaluated. Since it is true, the for loop begins running, After the number is printed, num is incremented by one and the conditional test is evaluated again. This provcess continues until num equals 11. When this happens the for loop stops, and terminating is displayed, keep is mind that the initialixation portion of the for loop is only excecuted once, when the loop is first entered.
Post by Anrob. 


Tuesday, 5 October 2010

22. Infinite loop

If you want to create an infinite loop you can use for and while loop easily. For create an infinite loop by using for loop, you can not give any initialization, increment and condition into for loop. For example:

for ( ; ; )
{
Printf (“finite loop”);
}

When you run this program you can not exit this for loop normally. For exit this program uses ctrl+Break.

For create an infinite loop by using while loop you can use this formula,

While(1)
{
Printf(“finite loop”);
}

When you run this program you can not exit this for loop normally. For exit this program uses ctrl+Break.

Written by arnob.


  

Sunday, 19 September 2010

15. Use break to exit a loop

The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. If you use a break statement under a loop and when the program read the break statement then the loop is immediately stopped, and program control resumes at the next statement following the loop. For example, this loop prints only the numbers 1 to 10.


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i;
  for (i=1;i<100;i++)
  {
  printf("%d",i);
  if(i==10);
  break;                    /* exit the loop */
  }
}


The break statement can be used with all three of C'a loops.
   You can have as many break statements within a loops as you desire. However, since too many exit points from a loop tend to destructure your code, it is generally best to use the break for special purposes, not as your normal loop exit.


Here a another example for using break.


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,x=0;
for(i=0;i<5;++i)
  {
  x+=(i+j-1);
  printf("%d",x);
  break;
  }
printf("\nx=%d",x);
}


(post by arnob)

Thursday, 7 October 2010

25. DO.....WHILE LOOP

Do....while loop is similar to the while loop. While loop checks the condition first then the statements are executed but the do…..while loop checks the conditions after the statement are executed. This means that do…while loop executes the statements at least once, while the while loop might not execute the statements at all based on its condition.

The expression must have arithmetic or pointer type. Execution proceeds as follows:
1.   The statement body is executed.
2.   Next, expression is evaluated. If expression is false, the do-while statement terminates and control passes to the next statement in the program. If expression is true , the process is repeated, beginning with step 1.

Example of the do-while statement:
do
{
    y = f( x );
    x--;
} while ( x > 0 );

In this program, the two statements y = f( x ); and x--; are executed, regardless of the initial value of x. Then check the condition (x>0). If the condition is true then the statement body is executed again and x > 0 is reevaluated. The statement body is executed repeatedly as long as the condition is true. When the condition is false then do…..while loop is stop.
 post by Arnob

Sunday, 19 September 2010

16. Know when to use the continue statement


The continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. For example, this program never display any output: 

#include<stdio.h>
#include<conio.h>
void main()
{
int x;
  for(x=0;x<100;++x)
  {
  continue;
  printf("%d",x);    /* this is never executed */
  }
}

In this program when the continue statement is reached, it causes the loop to repeat, skipping the printf() statement. In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process. In the case of for, the increment part of the loop is performed,the conditional test is executed, and the loop continues.
   Frankly, continue is seldom used, not because it is poor practice to use it, but simply because good applications for it are not common.

(post by arnob)

Tuesday, 5 October 2010

18. Create Nested Loops

When the body of one loop contains another, the second is said to be nested inside the first. Any of C’s loops may be nested within any other loop. The ANSL C standard specifies that loops may be nested at least 15 levels deep. However, most compilers allow nesting to virtually any level. As a simple example of nested for, this fragment prints the numbers 1 to 10 on the screen ten times,

for (i=0;i<10;i++)
{
  for (j=1;j<11;j++)  /* nested loop */
  printf(“%d”,j);
  printf(“\n”);
}

Examples:

** This program used three for loops to print the alphabet three times, each time printing each latter twice;

#include<stdio.h>
int main(void)
{
  int I,j,k;
  for(i=0;i<3;i++)
    for(j=0;j<26;j++)
      for(k=0;k<2;k++)
      printf(“%c”,’A’+j);
return 0;
}

The statement
Printf(“%c”,’A’+j);
Works because ASCII codes for the letters of the alphabet are strictly ascending-each one is greater than the letter that precedes it.

(Taken from “Teach yourself C”)

19. Some program using for loop

Here i give some program by using for loop.
Q1. Useing for loop printf 10 star.

/* Program 1 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=0;i<10;i++)
printf("* ");
getch();
}

Explanation:
When the program is execute initialization scction i=0, then it execute the condition (i<10). First time when i=0 then the condition is true so it execute the printf function and pint a star. After execute the printf function it will go back in the increment section and increment the value of i, then i=1. Then again execute the condition and work again and again. When i=10 the condition is false and it can not exicute the printf function. So that the output is :

* * * * * * * * * *

/* Program 2 */

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,n;
printf("Enter the value : ");
scanf("%d",&n);
for(i=1;i<=n;i+=4)
{
for(i=1;i<=n;i+=4)
printf(" %d",i);
}
getch();
}
if n=10
Output:
1 5 9

/* Program 3 */

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,n;
printf("Enter the value : ");
scanf("%d",&n);
for(i=0;n>=i;n-=4)
{
printf(" %d",n);
}
getch();
}
if n=20
Output is:
20 16 12 8 4 0
Post by Arnob



Sunday, 7 November 2010

42. Dynamic Memory Allocation

In this tutorial you will learn about C Programming - Dynamic Memory Allocation. Suppose we have a program which can store 100 student’s marks. If you need to store 75 students’ marks in this program you can, but some memory are not uses. But if you need store 110 students’ marks in this program you can not do it. You need increase array size. So it is big problem when any body use this program because he or she can not increase the array size. If we have a way that when the program runs in that time we give the array size, then that problem can not come. Yes we have a way that when we run the program we give the student number then the program make array size in its own. The way is dynamic memory allocation. In this system we can use two functions they are malloc and calloc. They both do the same work. They are often known as “Dynamic memory allocation functions”. Let us now see a program, which uses the concept of dynamic memory allocation.

/*Program for dynamic memory allocation */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,avg,I,*p,sum=0;

printf(“\n Enter the number of student: ”);
scanf(“%d”,&n);

p=(int*) malloc (n*2)
if(p==NULL)
{
printf(“\n Memory allocation unsuccessful”);
exit();
}
for(i=0;i<n;i++)
scanf(“%d”,(p+i));

for(i=0;i<n;i++)
sum=sum+*(p+i);

avg=sum /n;
printf(“Average marks=%d”,avg);
getch();
}
Note: here (n*2) means that the number of (student * 2). We want to convert the student number in byte. The number of student is integer so we multiply with 2(integer =2 byte). If it is float then we multiply with 4(float=4 byte).

Here, we have first asked for the number of students whose marks are to be entered and then allocated only as much memory as is really required to store these marks. Not a byte more, not a byte less. The allocation job is done using the standard library function malloc( ). malloc( ) returns a NULL if memory allocation is unsuccessful. If successful it returns the address of the memory chunk that is allocated. We have collected this address in an integer pointer p since malloc( ) returns a void pointer we have telecasted it into an integer pointer. IN the first for loop using simple pointer arithmetic we have stored the marks entered from keyboard into the memory that has been allocated. In the second for loop we have accessed the same values to find the average marks.

The calloc( ) functions works exactly similar to malloc( ) except for the fact that is needs tow arguments. For example,
Int *p
P=(int*) calloc (10,2);

Here 10 mean the number of student. And 2 indicates that we wish to allocate memory for storing integers.


Written by Arnob.
Reference: “Understanding Pointers In C”

Monday, 11 October 2010

27. Create a number pyramid.

 I have written this article to demonstrate how you can print a number pyramids using for loop and if condition. Building a pyramid in c programming is quite easy, but you must have the understanding of how for loop works.

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int i,j,n,k;
printf("Enter a value : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
 {
  for(j=1;j<=n-i;j++)
   printf(" ");
  {
   for(j=1;j<=i;j++)
   printf("%d",j);
   j=1;
   for(j=i;i>=j;j--)
   if(j==0)
   break;
   else
   {
   k=j-1;
   if(k==0)
   break;
   else
   printf("%d",k);
   }
   printf("\n");
   }
   }
 getch();
}

post by Arnob

Tuesday, 5 October 2010

23. While statement

While is one kind of loop. The process to write down while statement is

While (condition)
{
Statement;
Increment or decrement;
}

Condition means a right expression and we normally use relational expression. While statement first of all check the condition if the condition is true then the program execute the while statement but if the condition false the wile statement can not execute.
Look at this program,

#include<stdito.h>
void main ()
{
int i=1;
while(i<=5)        
{
Printf(“i”);           /* statement */
i++;                      /* increment */
}
getch();
}

Output: 1 2 3 4 5

Explain: First of all I is initialize in i=1; . Then check the condition while (i<=5) so the condition is true because i=1. Then print the value of i by using printf statement (printf(“i”); ). Then the value of i is increment in (i++). Again check the while condition  and printf the value of i and increment i. whine i=6 the while condition is false so the loop is stop.

Written by arnob.

Monday, 18 October 2010

35. Introduction to Pointer and Arrays

Pointer and arrays:
1. Array elements are always stored in contiguous memory location.
2. A pointer when incremental always pointer to an immediately next location of its type.
Suppose we have an array,
int mamun[ ]={3,4,5,6};
Suppose the elements are located in memory as
Elements:               3        4           5           6
Memory location: 1000   1002      1004      1005
Here is program that prints out the memory location in which the elements of this array are stored.

main( )
{
   int mamun[ ]={3,4,5,6};
   int i=0,*p;
   p=mamun;   /*Because the array name is a base address of first elemnt of the array. We cam also write it p=mamunb[0]*/
     while (i<=4)
 {
    printf(" \n Address = %u",&mamun[i]);
    printf("\n Element = %d", *p);
    i++;
    p++;
 }
}
output:
address             elements
1000                  3
1002                  4
1004                  5
1006                  6

in this program, to begin with  we have collected the base address of the array(address of 0th  element) in the variable p using the statement,
p=mamun; /*assigns address 1000to p*/.
When we are inside the loop for the first time p contains the address 1000,and the value at this address is 24.
These continue till the last element of the array has bee n printed.

A word of caution! D o not attempt the following operations on pointer ... they would never work out.
1. Addition of two pointers.
2. Multiplying a pointer with a number.
3. Dividing a pointer with a number. 

written by mamun

Friday, 3 December 2010

46. Find the even number from a array by using RECURSION

Question: Get input a array frmon user and find the hight number. You can only use one array and can not use any globel variable.

Ans: If you can use more then one array then you can easyle find the hight number by only using for loop. But you can not use more then one array. So you can solve this problem by using recursion.

/*program for find the even number */

#include<stdio.h>
#include<conio.h>

int main()
{
clrscr();
int a[100];n,i;
printf("How many number you want to input: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d number: ");
scanf("%d",&a[i]);
}
void chk_evn(int,int,int*,int*)
chk_evn(0,0,&n,a);
for(i=0;i<n;i++)
printf("%d",a[i]);
return 0;
}

void chk_evn (int i,int j,int *n,int *a)
{
if(i==n){*n=j;return n;}
if(a[i]%2==0)
a[j++]=a[i];
chk_evn(i+1;j,n,a);
}

program written by arnob

Thursday, 14 October 2010

29. How to print prime number.

Print Prime Numbers(using for loop):

#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
clrscr();
int i,j,n;
printf("Enter a value : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
 {
 for(j=2;j<=sqrt(i);j++)
   {
   if(i%j==0)
     break;
     if(j>sqrt(i))
     printf("%d  ",i);
   }
 }
getch();
}
post by Arnob.

Monday, 11 October 2010

26. How to creat a pyramid in C


Hello friends, today I want to write about Pyramid. How can you create a pyramid in C. It is very easy to make a pyramid in C. For create a pyramid in C, you must have the understanding of how for loop works.
                                                             when input is 4.

 If you want to create this type of pyramid you can follow the program.


#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int i,j,n,k;
printf("Enter a value : ");
scanf("%d",&n);
  for(i=1;i<=n;i++)
  {
    for(j=1;j<=n-i;j++)
     printf(" ");
    {
      for(j=1;j<=i;j++)
      printf("*");
       j=1;
      for(j=i;i>=j;j--)
      if(j==0)
      break;
      else
      {
        k=j-1;
        if(k==0)
        break;
        else
        printf("*");
        }
      printf("\n");
      }
    }
getch();
}
post by Arnob

Thursday, 11 November 2010

45. Passing 2-D Array to a Function by using pointer

There are two ways in which er can pass a 2-D array to a function by using pointer. These are illustrated in the following program.

/*Two ways of accessing a 2-D array*/
#include<alloc.h>
void main()
{
int a [3][4]={
               1,2,3,4,
               5,6,7,8,
               9,0,1,6
             };
clrscr();
display(a,3,4);
show(a,3,4);
}

display(int *q,int row, int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%d",*(q+i*col+j));
printf("\n");
}
printf("\n");
}

show(int (*q)[4],int row, int clo)
{
int i,j;
int *p;

for(i=0;i<row;i++)
{
p=q+i;
for(j=0;j<col;j++)
printf("%d",*(p+j));
printf("\n");
}
printf("\n");
}

And here is the output...

1234
5678
9016

1234
5678
9016

In the display() finction we have collected the base address of the 2-D array being passed to it in an ordinary int pointer. Thenthrough the two for loops using the ex[ression *(q+i*col+j) we have reached the appropriate element in the array. Suppose i is equal to 2 and j is equal to 3, then we wish to reach the element give this element or not. The exprewssion *(q+i*col+j) becomes *(4001+2*4+3). This turns out to be *(4001+11). Since 4001 is address of an integer, *(4001+11) turns out to be *(4023). Value at this address is +. This is indeed same as a[2][3]. A more general formula for accessing each array element would be:

*(base address + row *no of columns +column no)

In the show( ) function we have defined q to be a pointer to an array of 4 integers through the declaration
int (*q)[4];

To begin with, q hods the base address of the xeroth 1-D array, i.e 4001. This address is then assigned to p, an int pointer, and then using this pointer all elements of the xeroth 1-D array are accessed. Next thime through the loop when i takes a value 1, the expression q+i fetches the address of the first 1-D arry. This is because, q is a pointer to zeroth 1-D array and adding 1 to it would given us the address of the next 1-D array. This address is once again assigned to p, and using it all elements of the next 1-D arraY are accessed. 

Arnob