Find the error(s) in the following code fragments and explain how to correct it
ID: 3764888 • Letter: F
Question
Find the error(s) in the following code fragments and explain how to correct it (them). Int g() {cout "Inside function g" endl; int h() {cout "Inside h" endl;}} int sum (int x, int y) { int result; result = x + y;} void product { int a, b, c, result; cout "Enter three integers: "; cin a b c; result = a*b*c; cout "Result is " result; return result; } double square (double n) {double n; return n*n;} float cube (float); // function prototype double cube (float number) // function definition{ return number*number*number; } const int N = 10; int a[N]; for(int i = l; iExplanation / Answer
a.
error:function-definition is not allowed inside a function, before'{' token
int h() {cout << "Inside h" << endl;}}
Correction:
int g() {cout << "Inside function g" << endl;}
int h() {cout << "Inside h" << endl;}
Note: These functions should not be placed inside main()
b.
error:function-definition is not allowed inside main(), before'{' token
int sum (int x, int y) {int result; result = x + y;}
Note:
This error arises if the code fragment is inside the main()
Otherwise there is no error if it is written as the function outside(before) main()
Correction:
Place the code fragment as the function outside(before) main()
c.
error: return-statement with a value, in function returning 'void'
return result;}
Correction:
int product ()
d.
error: declaration of 'double n' shadows a parameter
{double n; return n*n;}
Correction:
double square(double n)
{return n*n;}
e.
error: ambiguating new declaration of 'double cube(float)'
double cube (float number)
^
Correction:
double cube (float); //function prototype
f.
const int N=10;int a[N];for(int i=1;i<=10; i++) {cin>>a[i];}
error: as per the code you have to access a[10]
but as per array definition, a[10] => a[0] to a[9] are allowed.
Correction:
const int N=10;int a[N];for(int i=0;i<10; i++) {cin>>a[i];}
g.
const int N=2; int a[N]={2,3},b[N]={3,4},c[N]; c=a+b;
error: invalid operands of types 'int [2]' and 'int [2]' to binary 'operator+'
const int N=2; int a[N]={2,3},b[N]={3,4},c[N]; c=a+b;
^
Correction:
const int N=2; int a[N]={2,3},b[N]={3,4},c[N]; for(int i=0;i<N;i++){ c[i]=a[i]+b[i];}
Note: c[N]=a[N]+b[N];
works, syntax wise but does not give intended result.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.