Sample Codes for Looping Structures in C


Loop Sample: Using for loop with an input of rows and display a half flip triangle.
#include <stdio.h>
int main()
{
    int i,j,rows,a;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    for(i=rows;i>=1;--i)
    {  
        for(j=1;j<=i;++j)
        {
    printf("*");
        }
printf("\n");
}
    return 0;
}
OUTPUT


Loop Sample: Using for loop with a display of an arrow compose of asterisk characters.
#include<stdio.h>
int main()
{
    int  i, k, l, j;
    for ( i = 0 ; i <= 5 ; i++)
    {
            for(k=1; k<=5-i; k++)
            {
                    printf(" ");
            }
            for(j=0; j<i; j++)
            {
                    printf("*");
            }
            printf("\n");
    }
int rows = 5;

    for (i=rows-1; i>=0; i--)
    {
        for(l=(rows-2)-i; l>=0; l--)
        {
             printf(" ");
        }
        for (k=i; k>=0; k--)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}
OUTPUT


Loop Sample: Using for loop with a display starting from 6 to descending repeated numbers.
#include <stdio.h>
int main()
{
    int i,j,rows;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    for(i=1;i<=rows;++i)
    {
        for(j=rows;j>=i;--j)
        {
           printf("%d ",j);
        }
        printf("\n");
    }
    return 0;
}
OUTPUT


Loop Sample: Using for loop with a display from 1 to 10 repeated numbers.
#include<stdio.h>
int main()
{
 int num,r,c;
 printf("Enter loop repeat number(rows): ");
 scanf("%d",&num);
 for(r=1; num>=r; r++)
 {
  for(c=1; c<=num; c++)
  {
     printf("%d",c);
  }
  printf("\n");
 }
 return 0;
}

OUTPUT


Loop Sample: Using do while loop with a display from 0 to 10 numbers.
#include <stdio.h>
int main()
{
int i;

do {
printf("%d\n", i);
i++;

}while (i<=10);

system("pause");
return 0;
}
OUTPUT


Loop Sample: Using for loop with a form of triangle compose of numbers.
#include<stdio.h>
int main()
{
    int rows,i,j,k=0;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=1;i<=rows;i++)
    {
        for(j=1;j<=i;++j)
          printf("%d ",k+j);
        ++k;
        printf("\n");
    }
return 0;
}

OUTPUT


Loop Sample: Using arrays and for loop then get the sum of arrays.
#include <stdio.h>
int main()
{
     int marks[10],i,n,sum=0;
     printf("Enter number of students: ");
     scanf("%d",&n);
     for(i=0;i<n;++i)
{
          printf("Enter marks of student%d: ",i+1);
          scanf("%d",&marks[i]);
          sum+=marks[i];
     }
     printf("Sum= %d",sum);
return 0;
}

OUTPUT

Sample Codes for Looping Structures in C Sample Codes for Looping Structures in C Reviewed by code-dev on 12:30 AM Rating: 5

No comments:

Powered by Blogger.