Answer Exercises Fundamnetal C Programming
Answer Exercises Fundamnetal C Programming
1. Write a single C statement to accomplish each of the following: printf( "Count is greater than 10.\n" );
a) z = x++ + y;
b) product *= 2;
a) x = 1;
2. Find the error in each of the following code segments and
while ( x <= 10 )
explain how to correct it.
{
x++;
a) x = 1;
}
while ( x <= 10 );
x++;
b) for ( y = 1; y != 1.0; y += 1 )
}
printf( "%f\n", y );
b) for ( y = .1; y != 1.0; y += .1 )
c) switch ( n ) {
printf( "%f\n", y );
case 1:
printf( "The number is 1\n" );
c) switch ( n ) {
break;
case 1:
case 2:
printf( "The number is 1\n" );
printf( "The number is 2\n" );
case 2:
break;
printf( "The number is 2\n" );
default:
break;
printf( "The number is not 1 or 2\n" );
default:
printf( "The number is not 1 or 2\n" );
}
break;
}
d) The following code should print the values 1 to 10.
n = 1;
d) The following code should print the values 1 to 10.
while ( n < = 10 )
n = 1;
printf( "%d ", n++ );
while ( n < 10 )
printf( "%d ", ++n );
should keep telling the player Too high or Too low to help
3. the player “zero in” on the correct answer.
a) Write a pseudocode the game of “guess the number” as
follows: b) Draw the flowchart based on pseudocode in (a).
c) Write the C program based on algorithm in (a) and (b).
Your program chooses the number to be guessed by
selecting an integer at random in the range 1 to 10. The 1. Start
program then types: 2. Declare target, guess
3. target = rand() % 10 + 1
I have a number between 1 and 10. 4. Start loop
Can you guess my number? 4.1 Enter guess
Please type your first guess. 4.2 If target == guess, print "Congratulations! You guessed
the correct number."
The player then types a first guess. The program responds 4.3 Else if target > guess,print "Too high! Try again."
with one of the following: 4.4 Else, print "Too low! Try again."
5. End
If the player’s guess is incorrect, your program should loop int main() {
until the player finally gets the number right. Your program int target, guess;
// Generate random number between 1 and 10
target = rand() % 10 + 1;
do {
printf("Enter your guess: ");
scanf("%d", &guess);
if (guess == target)
printf("Congratulations! You guessed the correct
number.\n");
else if (guess > target)
printf("Too high! Try again.\n");
else
printf("Too low! Try again.\n");
} while (guess != target);
return 0;
}