Arrays question. please write a c++ program that will ask the user to enter a ce
ID: 3805525 • Letter: A
Question
Arrays question.
please write a c++ program that will ask the user to enter a certain number of grades (for example) , and will then ask the user for the target grade.
the target grade is the grade whose indices of occurences we need.
it should have two functions :
1) A function designed to partially fill an array
A function to search for ALL occurrences of a given grade. please note that i need the indices of those reoccuring grades be stored to a results array which will then be printed out in main.
Explanation / Answer
// C++ code
#include <iostream>
using namespace std;
void fillArray(int grades[], int size)
{
for (int i = 0; i < size; ++i)
{
cout << "Enter grade " << (i+1) << ": ";
cin >> grades[i];
}
}
int* search(int grades[], int size, int target)
{
int count = 0;
for (int i = 0; i < size; ++i)
{
if(grades[i] == target)
count++;
}
int *indexArray = new int[count];
int j = 0;
for (int i = 0; i < size; ++i)
{
if(grades[i] == target)
{
indexArray[j] = i;
j++;
}
}
return indexArray;
}
int main()
{
int size = 5;
int grades[size];
int target;
fillArray(grades, size);
cout << "Enter target: ";
cin >> target;
int *indexArray = search(grades,size,target);
cout << "Index of target in scores: ";
int l = sizeof(indexArray)/sizeof(indexArray[0]);
for (int i = 0; i < l; ++i)
{
cout << indexArray[i] <<" ";
}
cout << endl;
return 0;
}
/*
output:
Enter grade 1: 2
Enter grade 2: 2
Enter grade 3: 3
Enter grade 4: 4
Enter grade 5: 1
Enter target: 2
Index of target in scores: 0 1
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.