C Programming

MAKING DECISIONS

Answers: Practise Exercise 5: while loops and if else

1. Use a while loop to print the integer values 1 to 10 on the screen

	12345678910


	#include <stdio.h>

	main()
	{
		int loop;
		loop = 1;
		while( loop <= 10 ) {
			printf("%d", loop);
			loop++;
		}
		printf("\n");
	}

2. Use a nested while loop to reproduce the following output

	1
	22
	333
	4444
	55555


	#include <stdio.h>

	main()
	{
		int loop;
		int count;
		loop = 1;
		while( loop <= 5 ) {
			count = 1;
			while( count <= loop ) {
				printf("%d", count);
				count++;
			}
			loop++;
		}
		printf("\n");
	}

3. Use an if statement to compare the value of an integer called sum against the value 65, and if it is less, print the text string "Sorry, try again".


	if( sum < 65 )
		printf("Sorry, try again.\n");

4. If total is equal to the variable good_guess, print the value of total, else print the value of good_guess.


	if( total == good_guess )
		printf("%d\n", total );
	else
		printf("%d\n", good_guess );


ęCopyright B Brown. 1984-1999. All rights reserved.