Program 1 #include <iostream> #include <string> using namespace std; int main()
ID: 3858206 • Letter: P
Question
Program 1
#include <iostream>
#include <string>
using namespace std;
int main()
{
int size;
//Section 1 - Array Definitions
int readings[-1];
float measurements[4.5];
string names[size];
//Section 2
const int SIZE = 100;
int numbers[SIZE];
for (int i = 1; i <= SIZE; i++)
numbers[i] = i;
}
Questions:
1) In the lines under the comment labeled Section 1, what is incorrect about these variable declarations? Rewrite the lines so that they are valid C++ statements that will compile.
2) Under Section 2, is there a problem with these lines of code? If so, how do you fix them?
Explanation / Answer
1)
int size; // The declaration is correct
//Section 1 - Array Definitions
int readings[-1]; // The declaration is wrong because size of the array cannot be negative
float measurements[4.5]; // size of the array must be integer
string names[size]; // Size of the array must be a constant
Correct Code :
//Section 1 - Array Definitions
int readings[4];
float measurements[4];
string names[5];
2)
const int SIZE = 100;
int numbers[SIZE];
for (int i = 1; i <= SIZE; i++)
{
numbers[i] = i;
}
The above code is correct.
Correct program :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int size;
//Section 1 - Array Definitions
int readings[4];
float measurements[4];
string names[5];
//Section 2
const int SIZE = 100;
int numbers[SIZE];
for (int i = 1; i <= SIZE; i++)
{
numbers[i] = i;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.