Here are some exercises that will help you get a better grasp of using variables! (Try solving these by hand without a compiler!)
cups_of_tea
and assigns to it a value of 5.Answer:
int cups_of_tea = 5;
#include <stdio.h>
int main(void)
{
("The value of x is %d.\n", x);
printf
int x = 7;
return 0;
}
Answer: x
is declared after
the printf()
statement! This means that x
does
not yet exist at the time of the printf()
. Even if it did
somehow exist, it would not have a defined value.
To fix the issue, simply swap the lines with the
printf()
statement and the assignment to x
. A
revised version of the code might look like the following:
#include <stdio.h>
int main(void)
{
int x = 7;
("The value of x is %d.\n", x);
printf
return 0;
}
Answer:
__basic
apple#3
#
symbol is not allowed in a
variable.2023_year
INT
int
, this is an
allowed variable name.)orANGE
total students
982
float_
Answer:
int float = 34123.4123 * 4;
float
cannot be used as a variable name.char student_name = 'John Smith';
'
) can only
contain one character.int i = 0; i = i + 1;
4 = gpa;
gpa
, the order should be flipped to
gpa = 4
.#include <stdio.h>
int main(void)
{
= 16.0;
ounces_of_milk ("You have %lf ounces of milk.\n", ounces_of_milk);
printf
return 0;
}
Answer: ounces_of_milk
is assigned a
value without ever being declared first! You can’t use a variable and
assign it without first declaring it.
To fix this problem, you can place double
(notice the
%lf
hints at which type to use) before
ounces_of_milk
to make one line that both declares and
initializes the variable. A revised version of the code might look like
the following:
#include <stdio.h>
int main(void)
{
double ounces_of_milk = 16.0;
("You have %lf ounces of milk.\n", ounces_of_milk);
printf
return 0;
}
Alternatively, you could add a new line of code before
ounces_of_milk = 16.0;
that declares it:
#include <stdio.h>
int main(void)
{
double ounces_of_milk;
= 16.0;
ounces_of_milk ("You have %lf ounces of milk.\n", ounces_of_milk);
printf
return 0;
}
Author’s note: The second solution works, but is
unnecessarily verbose, declaring and assigning
ounces_of_milk
on two consecutive lines. Should there have
been other code between these lines, this decision may make more sense,
but the first solution is preferrable.
#include <stdio.h>
int main(void)
{
int apples = 16;
int oranges = 90;
= oranges;
apples = apples;
oranges
("You have %d apples and %d oranges.\n", apples, oranges);
printf
return 0;
}
Answer:
You have 90 apples and 90 oranges.