Objectives:
-to Learn the use of for loop
-to Learn to get data using for loop
-to Learn to show data using for loop
The program given below is to learn the uses of for loop. We will input specific number of data from keyboard and we will keep them into the array. Later we will show them using for loop again.
#include<stdio.h>
void main()
{
int a[3],i,n;
printf("Enter the Number of Data: ");
scanf("%d",&n);
if(n>3)
{
printf("You can keep only 3 data\nDon't use more than 3 data");
}
for(i=0; i<n; i++)
{
printf("Enter the Data: ");
scanf("%d",&a[i]);
}
for(i=0; i<n; i++)
{
printf("\nData of Array: %d",a[i]);
}
}
Description of the Above Program
Line 04: int a[3],i,n;
In this line I have declared two integer type variables and an array. We will use the array a[3] to keep three data in it. If we use a[10] then we will be able to keep up to 10 data in it.
Line 05: printf("Enter the Number of Data: ");
The fifth line of the program we need to use to show the line Enter the Number of Data: only.
Line 06: scanf("%d",&n);
We have to use this number to keep the number of data we will use. We can keep up to 3 data into the array. That's why should not use more than 3 as the value of n. N.B. if you want to use 5 data, then you have to use a[5] instead of a[3]. Similarly you have use a[10], if you want to use 10 data.
Line 07: if(n>3)
This is the seventh line of the program. I have used to show an error message if anyone provide the value of n more than 3. The line printf("You can keep only 3 data\nDon't use more than 3 data"); will print the error message if anyone provide more than three as the value of n.
Line 11: for(i=0; i<n; i++)
This is the eleventh line we have to use for the for loop. This condition will initialize the value of i is zero(0) and will check if the value of i is less than i. If i<n condition is true then this line will increase the value 1 of i. And the lines printf("Enter the Data: "); and scanf("%d",&a[i]); will be executed continuously till i<n.
The next for loop will do the same and the rest of the programs are described in the previous posts. Read them for better understanding.
No comments:
Post a Comment