Your friend Raphael is an elementary school teacher. He has n students in his class, numbered 1,2,...,n. On a particularly chilly Wednesday, he decides to lure his students into attending his class by giving away candies to each of them. However, some children are mischievous and take more candies than allotted. The students who get lesser candies thus get sad, and need to be comforted. Therefore, Raphael wants your help in determining the index of the student who is the least happy.
Write a program in C++ that asks the user for an integer n, and then asks the user to input n different integers. Store these integers in an array. Print the index of the student who receives the minimum number of candies.
If more than one student gets the least number of candies, you can print any one of them.
Please enter the number of students (n): 5
Please enter the number of candies student 1 got: 3
Please enter the number of candies student 2 got: 4
Please enter the number of candies student 3 got: 2
Please enter the number of candies student 4 got: 1
Please enter the number of candies student 5 got: 3
4
You need to take as input, the entries of an array, let us call it candies
, and then find the position of the minimum element of it. This is possible by setting a variable current_min
to candies[0]
, and running through the entries of the array, comparing current_min
to candies[i]
, and updating current_min
if it is not the smallest entry. After the complete execution of this loop, you get the minimum of candies
in current_min
. However, in order to find the index/position of the minimum entry, you need to declare a new variable called min_index
, and update it to i
every time you update current_min
. Below is a CPP code that does this for you:
#include <iostream> using namespace std; int main() { int number_of_candies; cin>>number_of_candies; int* candies = new int [number_of_candies]; // Dynamic declaration of candies[] // Ask the user for the number of candies, and populate array candies[] for(int i = 0; i < number_of_candies; i++) { cout<<"Please enter the number of candies student"<<(i+1)<<" got: "; // Student 1's candies is stored in candies[0],...,Student n in candies[n-1]. cin>>candies[i]; } // Now we will find the minimum number of candies and the position of the minimum number of candies. int current_min = candies[0], min_index = 0; for(int i = 0; i < number_of_candies; i++) { if(current_min > candies[i]) // If the current_min is not the actual min, then update current_min and min_index to their correct values! { current_min = candies[i]; min_index = i; } } cout<<"The student with minimum number of candies is: "<<(min_index+1)<<endl; // min_index ranges in [0..n-1], student numbers are in [1..n] return 0; }