Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C - Loops

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

08

Repetition Control Structure


C - Loops
You may encounter situations, when a block of code needs to be executed several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
Or Loops are used to repeat a block of code.
Given below is the general form of a loop statement in most of the programming languages −

Types of loops
1. for
2. while
3. do while

1. for loop
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

for ( init; condition; increment )


{
statement(s);
}
Here is the flow of control in a 'for' loop −
 The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and the flow of control jumps to the next statement just after
the 'for' loop.
 After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition becomes
false, the 'for' loop terminates.

Flow Chart
Example
#include <stdio.h>
int main ()
{
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}

Output
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

while loop in C
A while loop in C programming repeatedly executes a target statement as long as a given
condition is true.

Syntax
while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any


expression, and true is any nonzero value. The loop iterates while the condition is true. When the
condition becomes false, the program control passes to the line immediately following the loop.
Flow Diagram

Here, the key point to note is that a while loop might not execute at all. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.

Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}

Output
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

More about loops


Based on the nature of the control variables and the kind of value assigned to, the loops may be
classified into following two general categories;

a) Counter controlled loop


b) Sentinel Value controlled loop

a) Counter controlled loops: 


The type of loops, where the number of the execution is known in advance are termed by the
counter controlled loop. That means, in this case, the value of the variable which controls the
execution of the loop is previously known. The control variable is known as counter. A counter
controlled loop is also called definite repetition loop.

Example : A while loop is an example of counter controlled loop.


sum = 0;
  n = 1;
   while (n <= 10)
    {
     sum = sum + n*n;
      n = n+ 1;
     }
Here, the loop will be executed exactly 10 times for n = 1,2,3,......,10.

b) Sentinel Value controlled loop : 


The type of loop where the number of execution of the loop is unknown, is termed by sentinel
controlled loop. In this case, the value of the control variable differs within a limitation and the
execution can be terminated at any moment as the value of the variable is not controlled by the
loop. The control variable in this case is termed by sentinel variable.                 
Example : The following do....while loop is an example of sentinel controlled loop.
                        do
                                      {
                                       printf(“Input a number.\n”);
                                      scanf("%d", &num);
                                      }
                              while(num>0);
                             
In the above example, the loop will be executed till the entered value of the variable num is not 0
or less then 0. This is a sentinel controlled loop and here the variable num is a sentinel variable.

goto statement in C
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement in the same function.
Syntax
goto label;
..
.
label: statement;

Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}
while( a < 20 );
return 0;
}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
LECTURE 09

C tokens:

C tokens are the basic buildings blocks in C language which are constructed together to write a C
program. Each and every smallest individual units in a C program are known as C tokens.

Types of C tokens

C tokens are of six types. They are,

1. Keywords               (eg: int, while),


2. Identifiers               (eg: main, total),
3. Constants              (eg: 10, 20),
4. Strings                    (eg: “total”, “hello”),
5. Special symbols  (eg: (), {}),
6. Operators              (eg: +, /,-,*)

C tokens example program:


int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (“Total = %d \n”, total);
}                                                                                        
.

where,

 main – identifier
 {,}, (,) – delimiter
 int – keyword
 x, y, total – identifier
 main, {, }, (, ), int, x, y, total – tokens
Constant

Constant in C means the content whose value does not change at the time of execution of a program.
In the C programming languages, const is a type qualifier: a keyword applied to a data type that
indicates that the data is constant (does not vary). You can use const prefix to declare constants
with a specific type as follows –

const type variable = value;

e.g

const int LENGTH = 10;

const int WIDTH = 5;

const char NEWLINE = 'M';

Note that it is a good programming practice to define constants in CAPITALS.

Types of Constants

1. Integer Number Constant [ e.g int, unsigned int, long int, long long int]
2. Single Character Constant [ e.g ‘A’   ,   ‘B’,     ‘C’]
3. String Constant [“Khalid”   ,   “Lahore”]
4. Float Constant [float, doule]

Rules for constructing C constant:

 An integer constant must have at least one digit.


 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.
 A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single quotes.
 The maximum length of a character constant is 1 character.
 String constants are enclosed within double quotes.

Example

#include<stdio.h>
#include<conio.h>
void main()
{
const int std_reg_no;
const char std_gener;
std_reg_no = 5;
printf(“Value of you have stored is= %d”, std_reg_no);
std_reg_no = 7; .
}

Output
Error: Cannot modify a const object
C – Literals

Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.

Example

#include<stdio.h>
#include<conio.h>
void main()
{
const int std_reg_no;
const char std_gener;
std_reg_no = 5;
printf(“Value of you have stored is= %d”, std_reg_no);
}

Here are “ 5 ”is example of literals.


C – String

C Strings are array of characters ended with null character (‘\0’). This null character indicates the end of the
string. Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.

Example for C string:


 char string[20] = { ‘P’ , ’a’ , ‘k’ , ‘i’ , ‘s’ , ‘t’ , ‘a’ , ‘n’, ‘\0’}; (or)
 char string[20] = “Pakistan”; (or)
 char string []    = “Pakistan”;
 Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of
memory space is allocated for holding the string value.
 When we declare char as “string[]”, memory space will be allocated as per the requirement during
execution of the program.

Example program for C string:


#include <stdio.h>
int main ()
{
char string[20] = " Pakistan ";
printf("The string is : %s \n", string );
return 0;
}
Output:
The string is : Pakistan
getch() and getche()

All of these functions read a character as input and return an integer value.

getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS
compilers like Turbo C. It reads a single character from keyboard. But it does not use any buffer, so the
entered character is immediately returned without waiting for the enter key.
Syntax:
int getch();

Example:
#include <stdio.h>
#include <conio.h>
int main()
{
char a;
a= getch();
printf("%c",a);  
}
Output
Input: g (Without enter key)

Output: Program terminates immediately.

getche()
Like getch(), this is also a non-standard function present in conio.h. It reads a single character from the
keyboard and displays immediately on output screen without waiting for enter key.
Syntax:
int getche(void);

Example:
#include <stdio.h>
#include <conio.h>
int main()
{
  printf("%c", getche());
  return 0;
}
Output
Input: g(without enter key as it is not buffered)

Output: Program terminates immediately.

But when you use DOS shell in Turbo C,

double g, i.e., 'gg'


Program Documentation

In computer hardware and software product development, documentation is the information that
describes the product to its users. It gives a comprehensive procedural description of a program. It
shows as to how software is written. Program documentation includes hard-copy or electronic
manuals that enable users, program developers, and operators to interact successful with a
program. It consists of the

 product technical manuals and/or


 online information (including online versions of the technical manuals and help facility
descriptions).

The term is also sometimes used to mean the source information about the product contained in
design documents, detailed code comments, white papers, and blackboard session notes.

. Program documentation even has the capability to sustain any later maintenance or development
of the program. The program documentation describes what exactly a program does by mentioning
about the requirements of the input data.

You might also like