Department of Computing: Lab Topic: For Loop
Department of Computing: Lab Topic: For Loop
Department of Computing: Lab Topic: For Loop
Introduction
The purpose of this lab is to get familiar with usage of for loop in C programming.
Objectives
The objective of this lab is to design solution using while loop.
Tools/Software Requirement
MS Visual Studio
Description
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is –
Example
#include <stdio.h>
int main () {
int a;
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Lab Tasks:
Using for loops, unless specified otherwise, perform the following tasks.
1. (Printing the Decimal Equivalent of a Binary Number) Input an integer containing only0s and 1s
(i.e., a “binary” integer) and print its decimal equivalent. [Hint: Use the remainder and division
operators to pick off the “binary” number’s digits one at a time from right to left. Just as in the
decimal number system, in which the rightmost digit has a positional value of 1, and the next
digit left has a positional value of 10, then 100, then 1000, and so on, in the binary number
system the rightmost digit has a positional value of 1, the next digit left has a positional value of
2, then 4, then 8, and so on. Thus the decimal number 234 can be described as 4 * 1 + 3 * 10 + 2
* 100.The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8 or 13.]
2. (How Fast is Your Computer?) How can you determine how fast your own computer really
operates? Write a program with a for loop that counts from 1 to 300,000,000 by 1s. Every
time the count reaches a multiple of 100,000,000, print that number on the screen. Use your
watch to time how long each 100 million repetitions of the loop takes .
4. Write a program that prints the following patterns separately one below the other. All asterisks
(*) should be printed by a single printf statement of the form printf( "*" ).[Hint: The
last two patterns require that each line begin with an appropriate number of blanks.]
Output:
Method 2
}
printf("Multiple is 1\n");//when count is 100000000 then it prints given statement
for (; count <= 200000000; count++)//count to 200000000
{
}
printf("Multiple is 2\n");//when count is 200000000 then it prints given statement
for (count = 1; count <= 300000000; count++)//count to 300000000
{
}
printf("Multiple is 3\n");//when count is 300000000 then it prints given statement
return 0;
}
Output:
Task # 4(Code):
Task # 3(Code):
//Hamid Muzaffar Khan
//BS-CS 10-B
Output: