Commit 6ee03480 authored by Dominik Widhalm's avatar Dominik Widhalm
Browse files

Extended example solutions for chapter 7

parent 71158b1c
......@@ -17,6 +17,7 @@ int check = 0;
void check_input (int value, int guess) {
int check = value == guess ? 1 : 0; // declaration of local variable check shadows global variable
// Additionally for such a long expression brackets are advisable
return;
}
......@@ -26,7 +27,7 @@ int main (int argc, char** argv) {
do {
printf("Guess a number: ");
scanf("d",&input);
scanf("d",&input); // % is missing in format string
check_input(number,input);
} while(check = 0); // second = is missing (for comparison)
......
......@@ -22,7 +22,8 @@ int main (int argc, char** argv) {
printf("Do you want information on the character [y/n]: ");
scanf("%s",info); // %s is used for strings, for single characters use %c (requires to pass the address of the variable with '&')
if (info == "y") // Better use brackets for if statements ...
if (info == "y") // Use of '' for single characters ("" is used for strings)
// Better use brackets for if statements ...
if ((input >= 'a') && (input <= 'z'))
printf("You entered a small letter!\n");
else if ((input >= 'A') && (input <= 'Z'))
......
......@@ -18,7 +18,8 @@ int main (int argc, char** argv) {
char* string1 = "Testikus";
char string2[8] = "Testikus"; // array is too small, since it has to hold 8 characters + '\0' (=9)
if (strcmp(string1,string2) == 1) // opening bracket { is missing // strcmp returns 0 in case of match
if (strcmp(string1,string2) == 1) // strcmp returns 0 in case of match
// opening bracket { is missing
printf("Match!\n");
}
......
......@@ -18,7 +18,8 @@ int main (int argc, char** argv) {
printf("How many numbers to you want to sum up: ");
scanf("%d",&count);
printf("Enter %d numbers now:\n",count);
while (--count > 0) // missing brackets for loop body ...
while (--count > 0) // Off-by-one error since first decremented and then compared with greater than
// missing brackets for loop body ...
scanf("%d",&input); // ... therefore only this statement will be looped ...
sum += input; // ... while this statement is only executed once after leaving the loop
printf("The sum of all numbers equals %d\n",sum);
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment