New guy here, and feeling like a bit of a dumbass, to be honest.
Basically, I am at university and one of my modules is Introduction to Programming (learning C). I really enjoy learning the programming and really want to take that further; however, I am really struggling with the math/logic. For example, each week we get these small tests which I have been doing OK on - unless they involve (what seems to me complicated but to many of you quite easy, I am sure) mathematical lines of code.
Here is one of the questions:
Which of the following is output when the following code is run:
#include<stdio.h>
void main()
{
int a = 300, b = 100, c = 100;
if(a >= 400)
b = 300;
c = 200;
printf("%d, %d, %d\n", a, b, c);
}
So I basically answered 300,100,100 (in the multiple choice answers), but the answer was 300,100,200. And (if I am being totally honest with you) if the option to choose 300,300,200 was there in the multiple choice I would have chosen that. I cant seem to understand why - in the result - only the value of c was changed?
Honestly, where this part of programming is concerned I am really struggling. I am determined to keep working hard on it though.
Any tips, or advice you guys have will be greatly appreciated.
Kind regards.
If you look at the code, b and c have values assigned since their initialization.
But b is changed if the condition a >= 400 is true i.e. b is set to 200 if 300 >= 400 is true. Is that true? No. So, b is left unchanged.
200 is assigned to c regardless anything else in your code.
In summary, since the declarations of a (=300), b(=100), and c(=100):
a isn't changed at all.
b is changed on a condition. But since that condition is false, it's not changed either.
c is always changed (200 is assigned).
So, you can now work out why the answer is so?
Execution proceeds line by line, and control branches as required.
Initially, the line with the initializations runs:
int a = 300, b = 100, c = 100;
At this point, the values are a = 300, b = 100 and c = 100.
if(a >= 400)
b = 300;
The if statement works as follows:
if(condition)
then-statement;
If the condition is true, then the then-statement is executed. Otherwise, we skip it. In your example, we are testing to see if a >= 400, since a is 300 so far, 300 >= 400 is not true, so we skip the statement b = 300.
At this point, the values are still a = 300, b = 100 and c = 100 (since we did not change anything).
Finally, you have the line:
c = 200;
This statement is not guarded by an if, so it will always be executed. So, we update the value of c and set it to 200.
At this point, the values are a = 300, b = 100 and c = 200.
So, when we get to the print statement, these are precisely the values that are printed out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With