Analyze the following C++ programming snippet #include using namespace std; int
ID: 3839454 • Letter: A
Question
Analyze the following C++ programming snippet
#include
using namespace std;
int main()
{
unsigned int vals[10];
size_t which;
unsigned int square;
for (size_t i = 0; i < 10; i++ )
vals[i] = (i+1)*(i+1);
cout << "Please type a number: ";
cin >> which;
square = vals[which-1];
cout << "The square of " << which << " is " << square << endl;
return 0;
}
• Are there instances were input is requested from an end user? Provide an explanation to justify your answer.
• Evaluate the code and identify possible flaws with the code in the context of accepting input from users.
Explanation / Answer
This code results in giving us the square of a number from 1 to 10
0 th index will give us square of 1 and 9th index will five us square of 10 i.e 100
• Are there instances were input is requested from an end user? Provide an explanation to justify your answer.
Yes, If we see below two lines of code
cout << "Please type a number: ";
cin >> which;
This ask the user to input a number
• Evaluate the code and identify possible flaws with the code in the context of accepting input from users.
Flaw 1 :
If the user enters which is 0 then we will access 0-1 = -1
-1 index of aray which does not exists
Flaw 2 : What if the user enters a number greater than 10, Suppose 100, Then we will be accessing 100-1 = 99
99th index of array which does not exists..Hence these are the flows in input..Insetead of that we need to correct that and prompt the user to enter values between 1 and 10 inclusive.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.