2(b) Write a Program which Generates One Hundred Random Integers in the Range of 1 To 100, store them in an array and then prints the average. Write three versions of the program using Different Loop Constructs.
Algorithm
Average of 100 random numbers
1. Start
2. Set sum:=0, i:=1
3. Repeat step 4 to step 7 until i > 100,go to step 8
4. Set n:=random(100)
5. Sum=sum+n
6. Write n
7. Set i:=i+1
8. Set avg:=sum/100
9. Write avg
10. Stop
Flowchart:
Program:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[150],sum=0,avg,i=1;
randomize();
printf(“\nAverage of 100 random numbers ”);
while(i<100)
{
a[i]=random(100);
sum=sum+a[i];
printf(“%d\t”,a[i]);
i=i+1;
}
avg=sum/100;
printf(“\nAverage of 100 random numbers is %d”,avg);
}
Linux Version
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
int i,arr[100],sum=0,Avg;
unsigned int iseed = (unsigned int)time(NULL);
srand(iseed);
for(i=0;i<100;i++)
{
arr[i]=rand()%100;
sum=sum+arr[i];
printf("%d\t",arr[i]);
}
Avg=(float)sum/100;
printf("\nAverage is :%d",Avg);
}
Algorithm
Average of 100 random numbers
1. Start
2. Set sum:=0, i:=1
3. Repeat step 4 to step 7 until i > 100,go to step 8
4. Set n:=random(100)
5. Sum=sum+n
6. Write n
7. Set i:=i+1
8. Set avg:=sum/100
9. Write avg
10. Stop
Flowchart:
Program:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[150],sum=0,avg,i=1;
randomize();
printf(“\nAverage of 100 random numbers ”);
while(i<100)
{
a[i]=random(100);
sum=sum+a[i];
printf(“%d\t”,a[i]);
i=i+1;
}
avg=sum/100;
printf(“\nAverage of 100 random numbers is %d”,avg);
}
Linux Version
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
int i,arr[100],sum=0,Avg;
unsigned int iseed = (unsigned int)time(NULL);
srand(iseed);
for(i=0;i<100;i++)
{
arr[i]=rand()%100;
sum=sum+arr[i];
printf("%d\t",arr[i]);
}
Avg=(float)sum/100;
printf("\nAverage is :%d",Avg);
}

Comments
Post a Comment