Practice Exercise (Loops)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Task 1

Objective: implement nested loops


Problem Statement: (Triangle Printing Program) Write a program that prints the following
patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*)
should be printed by a single printf statement of the form printf( "*" ); (this causes the asterisks
to print side by side).
[Hint: The last two patterns require that each line begin with an appropriate number of blanks,
i.e. 2 inner loops in the outer loop.]

Task 2.
Objective: implement input-validation loop for different data types
Problem Statement:
(a) Write a program to input an employee’s grade, age and experience from the user. All the
input values should be validated according to the following rules.
User input Valid values
Grade ‘w’, ‘x’, ‘y’, ‘z’
Age Age should be positive integer between 18
and 150.
Experience Experience should be positive integers less
than 30.
Once the valid values are available, simply display all the read input values.
(Hint: use do-while loop with the general format for input validation loop as discussed in theory
lecture)
(b) Define 3 separate functions for validating the 3 inputs, as discussed in lab demo. Convert
the above program, so that it now calls these functions to validate the inputs. Rest of the
program is the same as part (a).
Task 3.
Objective: Using nested loops with mixed types of inner loops
Program Name: Repeated multiplication tables
Problem Statement: In this lab task, you have to displays multiplication table of N integers one-
by-one, where N is a positive integer input by the user. Use a nested loop, where outer loop runs
for N times, and inputs a number T for which the multiplication table should be printed. While
the inner loop prints table of T upto 5 terms. A couple of sample outputs of the program is as
below.
Sample output 1 Sample output 2

Note: Perform input validation for both N and T, where N is a positive integer, and T is a
positive integer greater than and including 2.
Hint: This program first validates input N. Then, uses a nested loop, where outer-loop is
counter-controlled. Two inner loops are included inside this outer loop. First, input validation
loop for T, second, counter-controlled loop for printing multiplication table.
Task 4.
Program Objective: Using sentinel-controlled loop
Program name. Updated multiplication table program
Problem Statement.
We have discussed in class, that a sentinel-controlled loop depends on user input and continues
until the user input a particular (sentinel) value. We have also discussed that a do-while loop can
be used to validate user input.
In this lab task, you have to modify the multiplication table program Task 3 so that it first
validates the input number, for which multiplication table is printed. The valid values are in the
range 2-20 only. The program then prints multiplication table upto 5 terms, but does not exit.
Rather, it asks the user if he wants to continue the table upto 5 more terms. If the user responds
with ‘y’, then the next 5 terms are displayed. This process continues until the user inputs some
other value than ‘y’.
(Hint: you will have to nest the counter-controlled loop for printing the multiplication table
inside the sentinel-controlled loop, which inputs user choice.)
Task 5.
Program Objective: Using endfile-controlled loop
Program name. Average student score (batch mode)
Problem Statement.
Write a looping code segment that takes as input up to 20 integer scores from file indata, and
outputs their average. If the file contains fewer than 20 scores, the segment should still output the
correct average. If the file contains more than 20 scores, the additional numbers should be
ignored. Be sure to consider what happens if the file is empty.

Task 6.
Program Objective: Using general-conditional loop
Program name. Pair of divisible integers
Problem Statement.
Design an interactive input loop that scans pairs of integers until it reaches a pair in which the
first integer evenly divides the second.
(Hint: This is an example of a general-conditional loop, so identify the loop termination
condition first.)

Task 7.

Program Objective: Using endfile-conditional loop


Program name. Named students score percentage (batch mode)
Problem Statement.
Write a C program that computes student grades for an assignment as a percentage given each
student’s score and the total points. The final score should be rounded up to the nearest whole
value using the ceil function in the <cmath> header file. You should also display the floating-
point result up to 5 decimal places. The input to the program must come from a file containing
multiple lines with the student’s last name, score, and total separated by a space. In addition, you
should print to the console “Excellent” if the grade is
greater than 90, “Well Done” if the grade is greater than 80, “Good” if the grade is greater than
70, “Need Improvement” if the grade is greater than or equal to 60, and “Fail” if the grade is less
than 50. Here is an example of what the input file might look like:
Weems 50 60
Dale 51 60
Richards 57 60
Smith 36 60
Tomlin 44 60
Bird 45 60

Hint: Use endfile-controlled loop to read each line of data from file. In each line, the 2 numbers
are read as integer variables, while, the name is read character-by-character using sentinel-
controlled loop, where the sentinel-value is the space character ‘ ‘.

The output of your program should look like this:


Weems 83% .83333 Well Done
Dale 85% .85000 Well Done
Richards 95% .95000 Excellent
Smith 60% .60000 Need Improvement
Tomlin 73% .73333 Good
Bird 75% .75000 Good

Task 8.
Program Objective:
• Develop input validation loop
• Develop sentinel-controlled loop
• Program separate functions for different sub-problems
Program name. Named students score percentage (batch mode)
Problem Statement. Write a program that inputs 2 numbers (n and r). Both inputs should be
validated using a function int validateInput();, where valid values are positive integers. The
function keeps on scanning a single integer value until a valid value is available. The function
should then return this valid value. (Hint: use input-validation do-while loop format for this and
develop the input validation function as done in online lab 2.)
After validating the inputs, the program shows the following input menu to the user. (Hint: you
may use a separate void function for displaying these instructions only.)
Press 1 for multiplying numbers.
Press 2 for finding nCr.
Press 3 for finding nPr.
Press -1 for Exit.

The program should then perform the appropriate task according to the choice input by the user.
Ignore validation of the choice input. (Hint: Use a sentinel-controlled loop format for this, where
sentinel value is -1.)
(Hint: Formulae for computing combination and permutation:
• Comb = n!/(r!*(n-r)!)
• Perm = n!/((n-r)!)
Use a counter-controlled loop for computing factorial of n (n!). This is a running product pattern
very similar to running sum, as discussed in lecture 1 on while loop.)
Task 9.

Design an interactive input loop that scans an integer until it reaches a successive input in which
the previous integer evenly divides the second.
(Hint: you have to keep track of the value entered in previous iteration during the loop. See “3:
Keeping track of previous value”.)
Task 10.

Write a code segment that outputs the Fibonacci numbers that are less than 30,000. Each Fibonacci
number is the sum of its two predecessors (Hint: you have to use current and previous value in the
series to determine next number in series). The first two Fibonacci numbers are 1 and 1. Thus, the
sequence begins with
1, 1, 2, 3, 5, 8, 13, 21, 34, …
Output each number on a separate line.
Task 11.
The GCD of numbers n1 and n2 is the largest possible number, which divides both n1 and n2. E.g.
GCD of 27 and 30 is 3; GCD of 45 and 70 is 5. Write a program to compute the GCD of 2 input
numbers. If both numbers are prime (e.g. 7 and 17), then display message that GCD does not exist.
(Hint: find the smaller number out of n1 and n2. Loop from 2 to this smaller number and use a
flag-controlled loop, where flag gcdFound is turned on, if the counter divides both n1 and n2. )
Task 12.
a. Write a program, which runs in batch mode and finds the Largest and smallest numbers
from the list of numbers in an input file named numbers.txt. In the end, the program should
display these values as well as the average of numbers read from the file.
b. Write a program, which runs in batch mode and finds the Largest and second-largest
numbers from the list of numbers in an input file named numbers.txt.
(Hint: This program combines the 2 loop operations discussed we discussed in lecture i.e.
Keeping track of previous value” and Finding the Smallest/Largest values in a list”.)

You might also like