Embedded Loops The objective of this assignment is to give the student more prac
ID: 3818029 • Letter: E
Question
Embedded Loops
The objective of this assignment is to give the student more practice in using loops, especially embedding one loop inside the other. These are called “nested loops”. The assignment also provides the opportunity to work with random number generators. The assignment is composed of two parts for the benefit of student comprehension. However, only one program that does both parts a) and b) should be turned in by the student.
The two parts are:
a) Write a program in C that determines how many calls to a random number generator it takes to match a number between 0 and 99 that is entered by a user. Use a seeded random number generation function; otherwise all iterations of the outer loop (part b below) will be the same.
b) Embed the above program in a second loop that makes this computation 50 times and prints out the average number of times that the program took to find a match for the number entered.
Musts:
1) You must use at least two nested (embedded) loops.
2) You must use a seeded random number generator.
3) The output average of times the inner loop ran must be a floating point number.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
//i controls the for loop, n saves the user input, comparisions saves the number of comparisions per search
// and totalComparision saves the total number of comparisions
int i, n, comparisions, totalComparision = 0;
//avg saves the average number of comparisions in 50 turns
float avg = 0.0f;
//time constant
time_t t;
//A seeded random function generator
srand((unsigned) time(&t));
//taking input from the user
printf("Enter the number from 0 and 99 to search: ");
//saving the value in n
scanf("%d",&n);
//outer loop
for (i = 0; i < 50; i++) { //loop that makes comparisions 50 times the inner loop
comparisions = 0;
//inner loop
while (rand()%100 != n) { //if the value is found terminate else increase count of comparisions
comparisions++;
}
totalComparision += comparisions;
}
avg = (float)totalComparision/50; //convert the integers into floating point and calculate average
printf("The average times taken is:%f ",avg);//display average
return(0);
}
FEEL FREE TO COMMENT AND RATE.
HOPE THIS HELPS.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.