Question:
Programming question in c?
Teoh
2013-01-15 04:37:12 UTC
For questions (i) – (iii), using the declarations and initializations below, indicate whether each of statements from (i) – (iii) is valid or invalid. If the statement is valid, indicate what value is displayed or assigned. If the statement is invalid, explain why.
Given: float a[8]= {15.0, 11.0, 7.0, 3.5, 7.6, -3.5, 8.0, 9.9};
int b=4;
i. printf(“%.2f\n”, a[b * b]);
=invalid
ii. printf(“%.2f\n”, a[b]+b);
=valid
iii. a[2*b-3]=a[b/2];
=valid

help me check my answer.
can help me explain why invalid?
thank.
Three answers:
Runa
2013-01-15 04:57:51 UTC
b*b = 4* 4 = 16 which is out of range. Your index only goes up to 8.
?
2013-01-16 21:37:43 UTC
i.

Invalid since b*b = 4*4 = 16 and a[] has a size of 8 making a[16] (and anything else over a[7]) invalid.

Note that depending on the compiler and environment this may still build fine and give a run time error or it may even run but the output will be random gibberish.

c doesn't automatically prevent you from going outside of the valid range for an array, it's up to the programmer to ensure that it never happens.



ii.

valid, output of 11.60

a[b] = a[4] = the 5th element of a[] (the 1st is a[0]) = 7.6

so a[b] + b = 7.6+4 = 11.6

the printf formatting is %.2f meaning two digits after the decimal point so you get 11.60



ii.

Valid. no output.

a[2*b-3] = a[2*4-3] = a[5]

a[b/2] = a[4/2] = a[2]



So a[5] is now set to the value of a[2] or 7.0.
jplatt39
2013-01-15 12:59:37 UTC
4*4 is 16 and a has only 8 members. iii might be valid but I don't think it's true.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...