Computer Programming - I (MCT-143) Lab Session 8: Task 1
Computer Programming - I (MCT-143) Lab Session 8: Task 1
Lab Session 8
The main purpose of this Lab Session is to recheck your concepts of for loop and Nested for loop. You must
realize that you cannot proceed further in programming without having perfect concept of loops (for loop
and some others to be covered in next lab sessions).
So just re-do the tasks of the last lab session and make clear any tiny doubt you have regarding for loop.
Note: No repetition of any of the Lab Session will happen in future.
After getting clear to the last lab session, try the following task:
Task 1:
Write a program that that will take all entries of a 3x3 matrix and will display the sum and product of all of
its entries. Sample output is:
Note: You have to use cin instruction only once to take all nine inputs.
How to do it:
Apparently it is very simple problem where you have to take 9 inputs and display their sum and product.
Yes you can do it using a for loop as you did in task of calculating average of five subjects.
But how can you display a11 to a33?
What if instead of a11 to a33 you are asked to display a1 to a9? You should figure out its way. It’s pretty
simple; you can use the loop variable e.g. i. Every time i is incremented the display will change from a1 to
a9.
Now think about displaying a11 to a33. Here you have two numeric values linked with a, both changing
from 1 to 3. So you can do it using nested for loop with two variables (definitely!) e.g. i and j. Use them to
display a11 to a33.
Note: You must think at this point that you are taking 9 inputs from the user but none is being saved
except one. What if you want to apply some Matrix operation on input matrix and you need values of all
entries? There are ways to do it which you will learn later on.
Practice Problems:
I STRONGLY recommend trying these problems at home before coming to next Lab on Wednesday.
Task 1:
Write a program to take an integer from user and display corresponding triangle as shown in sample
output.
1
22
333
4444
Task 2:
Modify above task to get the output as shown below:
Sample output is:
Enter an integer: 4
1
333
55555
7777777
Task 3:
Write a program to take an integer from user and display corresponding triangle as shown in sample
output.
How to do it:
It is not an easy task. You will be using nested for loop as in above tasks but see carefully that in first line of
triangle there is not just one * but four spaces as well. So the outer loop will be from 1 to entered number,
but the in the inner loop you will use two loops, one for spaces and one for * with spaces decreasing in
each iteration and * increasing.
Hint: Start with some fixed number e.g. 5 and then make it general to user’s input.