Lab Session - 3 [Loops]
Lab Session - 3 [Loops]
--------------------------------------------------
----
1. WAP to display first n natural numbers and their sum using for loop.
Take n from the user.
#include <stdio.h>
#include <conio.h>
void main()
{
int i, n, sum = 0;
clrscr();
printf("Up to which natural no. do you need the sum? : ");
scanf("%d", &n);
printf("\nThe first %d natural numbers are:\n", n);
for (i = 1; i <= n; i++)
{
printf("%d\n", i);
sum += i;
}
printf("\nThe Sum of natural numbers upto %d terms : %d \n", n,
sum);
getch();
}
#include<stdio.h>
#include<conio.h>
void main ()
{
int n, i;
clrscr();
printf("Enter a number to get its multiplication table: ");
scanf("%d",&n);
printf("\nMultilication table of %d: \n",n);
for (i=1;i<=10;i++)
{
printf("%d x %d = %d\n", n, i, n*i);
//If there is only a single statement inside the for loop, you can
omit the {} braces.
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main ()
{
int n, i=1;
system("cls");
printf("Enter a number up to which odd natural numbers are needed:
");
scanf("%d",&n);
printf("\nOdd natural numbers up to %d are:\n\n",n);
while (i<=n)
{
if (i%2!=0)
printf("%d\n",i);
i++;
}
getch();
}
4. WAP to print the square of only even nos. entered by user, and to
skip output for negative or odd nos.
#include <stdio.h>
#include <conio.h>
void main()
{
int i, n, a, sq;
clrscr();
printf("\nHow many numbers you want to enter: ");
scanf("%d", &n);
for (i=1;i<=n; i++)
{
printf("\nEnter number: ");
scanf("%d", &a);
if (a<0 || a%2!=0)
continue; //takes us back to beginning of for loop
sq = a * a;
printf("\nSquare = %d\n", sq);
}
getch();
}
6. WAP to take multiple numbers from user and to print the largest among
them using Do-While loop.
#include<stdio.h>
#include<conio.h>
void main ()
{
int num=-1, largest=0;
clrscr();
do
{
printf("Enter a number (enter 0 to stop): ");
scanf("%d",&num);
if(num>largest)
largest = num;
}
while (num!=0);//note that ; must be used with the while statement
here.
printf("Largest number is %d",largest);
getch();
}
A better alternative:
#include<stdio.h>
#include<conio.h>
void main()
{
int x=0,y=1,z,n;
clrscr();
printf("Enter no. of terms for fibonacci series: ");
scanf("%d",&n);
n-=2; //same as writing n=n-2
if (n==-1)
printf("%d\t",x);
else if (n==0)
printf("%d\t%d\t",x,y);
else
{
printf("%d\t%d\t",x,y);
do
{
printf("%d\t",z=x+y);
x=y;
y=z;
--n;
}
while (n>0);
}
getch();
}
----------------------------------X----------------------------------