Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 77

CPPS - Unit 1

1
Algorithms and Flowcharts
What is an Algorithm?
• In simple terms, a set of steps to solve a given problem
• We saw the example of adding the first ‘n’ numbers in the initial
introductory class – a good example of an algorithm
• Programming is all about implementing the algorithm in a given
language along with a good way of storing the required data.
• The topic of Data Structures is all about learning different ways of storing data
for ease of manipulation
• Algorithm + Data Structures = Programs
Flowchart
• Flowcharts are pictorial representations of algorithms which are easy
to study and understand
• There are several basic symbols used in a flowchart:
• Terminator
• Process
• Decision
• Data
• Document
• On-page and Off-page references
• Delay/Bottleneck
• Flow
A sample flowchart
Start

Read X

Read Y

Calculate X * Y

Print Product

End
Another flowchart with decision
Start

Read X

Read Y

YES NO
Is X > Y

Print X > Y Print X == Y Print X < Y

End
Algorithm Features - Sequence
• Sequence is nothing but a series of simple steps
• Most algorithms will have a sequence that describes the steps to be
done in the required order
• The order of actions is important to do any task, and to solve any
problem and Sequence describes the same for successfully solving the
given problem or performing a given task
Algorithm Feature - Decision
• For solving most of the problems, other than the most trivial ones, we
need to take some decisions
• True in real life activities as well..
• A decision is a point in the algorithm where certain values are compared or
checks for certain conditions are done, and the sequence of steps post that
depends on the outcome of the decision.
• Refer to the flowchart that compares 2 values X and Y
• The Decision box (Diamond shape) is the point in the algorithm where the two
values are compared to print the appropriate message.
• Most programming languages support some constructs to check some conditions
and take different actions based on the outcome
• Typical examples are the ‘if’, ‘if-else’, ‘switch’ statements in different programming languages
Algorithm Feature - Repetition
• There are several situations where we do repeated operations on a variety of
data items.
• Simple example of adding first ‘n’ numbers also has a repeated addition in the algorithm
• Such repeated actions can be neatly structured by having a set of
steps(sequence) being repeated for ‘n’ number of times.
• Typically, there is a check if the sequence needs to be repeated by checking some
condition – say a counter that keeps track of how many numbers out of ‘n’ have been
added.
• Check can be either at the end or beginning
• The repetition continues as long as the condition holds true
• Commonly called as ‘loops’ in programming languages
• ‘while’ loop, ‘for’ loop etc.
A typical repetition example
• Problem is to add ‘n’ numbers
• Let’s say we have a value ‘m’ initialized to 1 – pointing to the first number
• We will save the partial sum in ‘s’, initialize it to 0.

LOOP: read number pointed to by ‘m’


add the number to value in ‘s’ and store result in ‘s’
increment ‘m’
if (m <= n) then
goto LOOP
else
print value in ‘s’
end program
Background of C Language
• Originally designed and implemented on the UNIX Operating System
on a DEC PDP-11 computer by Dennis Ritchie
• Relatively low level language – Easy to write system software
components like Operating system, device drivers in C
• A large number of applications and systems have been developed in C
over the last 4 decades
• Supports a variety of data types – ‘weakly’ typed language
• Good set of development tools for a variety of platforms (Operating
Systems)
Basic Structure of a C Program
#include <stdio.h>
#include ….

<Global variables declaration>

main(int argc,char *argv[]) { /* main() is the function where program execution starts */
<Local variables declaration>
printf(“Hello Class\n”);
}
Func1(int a, char b) {
<Local variables declaration>
<Code>
{
Func2(char c, int x) {
……..
}
..
A simple code snippet
{
int a, b; /* variable declaration–‘int’ is a keyword */

a = 2; /* assignment statement, a is a variable, ‘2’ is a constant*/

b = a + 1; /* assignment with a small arithmetic expression to add */

if (b > 5) {
/* Decision statement – ‘if’ is a keyword, ‘>’ is for greater than */

printf(“b is bigger than 5\n”);

}
}
Keywords – what are they
• In any programming language, there are certain words which are
reserved by the language for an explicit purpose
• These cannot be used for other purposes like variable names etc.
• Some of the common keywords in the C language are:
• If, else, for, while, do, switch, case, default, goto, short, int, long, float, double,
char, signed, unsigned, void, struct, union…
• We will learn about these as we go along in the course
Identifiers
• Identifiers are nothing but the names given to variables, functions that we
define/use in our program
• Example:
int xy, ab;

Func1() {

}

char mystr[10];

‘xy’ and ‘ab’ are variables of type ‘int’ – integer


‘Func1’ is a function – which is a unit of code that gets executed when the function is called
‘mystr’ is an array variable that stores 10 characters
Rules for naming identifiers
• Names can contain alphabets and numbers. The only special character that was allowed in the older
standard is the underscore character ‘_’.
• Some modern compilers allow a few other special characters, but best to avoid using those characters for
portability
• Name cannot start with a number
• Names can start with alphabet or ‘_’.
• Starting with ‘_’ is not recommended as many common libraries use names that start with ‘_’ and it is better to avoid naming our
identifiers starting with ‘_’ to avoid name clashes.
• Names cannot be any of the reserved keywords
• Names are case-sensitive
• i.e ‘Count’ and ‘count’ are 2 different identifiers
• Older standard/compilers were having some limits on the length like 31 that is considered significant
– Modern compilers generally have much higher limits
• Good Programming Practice – Name the identifiers meaningfully and use reasonable length names
• Generally, single alphabet names like ‘i’, ‘j’ etc. are commonly used for loop indices – keeps code readable
Examples..
• Counter, r_index, headptr, s1, s2 – All are valid identifier names
• 1count, 2_count – Not valid as it is starting with a number
• _rcount – Valid, but not recommended to be used to avoid potential
name clash with libraries which tend to use identifiers starting with
‘_’.
• Good practice is to use names which can convey their use/meaning in
the program
Data Types
• Data type specifies the type of data that is stored and the range of values that
can be stored in that.
• In C, we must explicitly declare the data type of any variable that we want to
use.
• Examples:
• int – Specifies that a variable name that follows this keyword ‘int’ is capable of storing an integer
quantity
• float – Specifies that the variable can store a single precision floating point value
• …
• Typically, each data type has a fixed amount of memory and representation
format associated with it.
• For example, a ‘float’ variable occupies 4 bytes of memory and the storage follows a
standard.
Basic Data Types in C
Data Type Typical Size in Bytes Range of Values
(64 bit Machine)
char 1 -128 to 127 ( -2^7 to 2^7-1 )
unsigned char 1 0 to 255
short 2 -32768 to +32767 (-2^15 to 2^15-1)
unsigned short 2 0 to 65535 ( 0 to 2^16 – 1)
int 4 -2147483648 to +2147483647 ( -2^31 to
2^31 – 1)
unsigned int 4 0 to 4294967295 (0 to 2^32 – 1)
long 8 -2^63 to (2^63 – 1)
unsigned long 8 0 to (2^64 – 1)
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
Variables
• Variables are nothing but names for the locations where we can store some data and
use/manipulate them later
• In C, we first have to declare the variables and specify the type of data (integer, floating point
etc.) they are going to store before using them
• Variables are ‘identifiers’ and so the rules for naming them follows the same rules we saw
earlier.
• Examples:
• int x, y; /* x and y are variables that can store an signed
integer */
• float f1, f2; /* f1 and f2 are variables that can store a floating
point value */
• char mybuff[26]; /* mybuff is the name for a block of memory that can
store 26 characters */
Using variables
• We can use the name of the variable to get the value stored there.
• For example:
{
int x, y; /* Declare 2 integer variables x, y*/
x = 5; /* Store the value 5 in variable x */
y = x; /* This reads the value in x and stores
it in variable y*/
}
• We can also initialize variables when we declare them:
{
unsigned int x=2, y=6;
float m = 3.14f;
}
Constants
• Integer Constants – Nothing but integers that can be used in a
program
int x = 213; /* 213 is a integer constant */
Long y = 1235464646L; /* 1235464646L is a long
constant – ends with L or l */
int mx = 037; /* 037 is a integer constant written as
a Octal number – starts
with a 0 – it is decimal 31 */
int zx = 0x15; /* 0x15 is a integer constant written
as a Hexadecimal number – starts
with 0x – it is also decimal 31 */
Constants..
• Floating point constants
float f1 = 122.55f; /* 122.55f is a float constant –
ends with F or f, assigned to variable f1*/
double d1 = 113434.23 /* 113434.23 is a double constant
– no suffix */
• Character constant
• It is nothing but a small integer, written as one character with single quotes
char c1 = ‘a’; /* ‘a’ represents the ASCII value of
the alphabet a, which is stored in c1 */
char c2 = ‘\013’ ; c2 stores the ASCII Vertical tab
character which has value
represented by Octal 013 */
Constants..
• #define MAXLEN 101
• This defines a constant identifier MAXLEN which has the value 101
• #define is called a Preprocessor directive which is processed by the C Pre-processor –
this is a process that runs before the C program is compiled and all instances of the
string MAXLEN will be replaced with 101 in the file.
• #defines are also used to define MACROS which will be discussed later
• Constant identifiers like MAXLEN are by convention in full upper case.
• String Constant
• In C, a string is nothing but a sequence of characters which has the null character ‘\0’ at
the end to indicate end of the string.
“Hello World” is a string constant or string literal in C
char mymsg[] = “Hello World”; /* initializes an array
with this string contents */
Constants..
• Enumerations – enum
• Enumeration is a list of constant integer values and is specified like:
enum boolean {NO, YES};
/* Declares an enumeration ‘boolean’ which can take 2 values represented symbolically by
NO and YES. The first name in the enum ‘NO’ gets the value 0 and the next 1 and so on..*/
• We can also specify specific values to be assigned to the names as needed and
subsequent names will get sequentially higher values
enum myrange { ALPHA, GAMMA=3, ZETA };
/* Hear ALPHA gets the value 0, GAMMA gets 3, and ZETA will be assigned 4 */
• Names in different enumerations must be distinct
• Like #defines, these names are also by convention in upper case.
const keyword
• In C, any variable can be declared to have a constant value by
prefixing it with the keyword ‘const’
const float pi = 3.1415f;
/* Declares ‘pi’ to be a float type, and it’s value
cannot be changed elsewhere */

const char msg[] = “my message”;


/* The const keyword indicates that the elements of
the array msg[] cannot be altered */
Printing data, messages
int printf(char *format, arg1, arg2, …)
• printf() is the library function used to print formatted data
• ‘format’ points to a string (a set of characters, null terminated).
• The format string contains 2 types of objects
• Ordinary characters are copied to the output as is
• Conversion specifiers, each of which is used to cause conversion and printing of the next
successive argument in the list of arguments, viz. arg1, arg2…
• The first conversion specifier applies to arg1, second to arg2 and so on..
• Conversion specifier beings with a ‘%’ character and ends with a conversion character which is
used to process the argument appropriately for printing
printf() – conversion character table
Character Argument Type: Printed As
d, i int : Decimal number
o int : unsigned octal number without a leading zero
x, X int : unsigned hexadecimal number
u int : unsigned decimal number
c int : single character
s char *: print characters from the string until a null character ‘\0’ is encountered or limited by
the precision specifier
f double : [-]m.dddddd – number of d’s is given by precision specifier, default is 6
e, E double : [-]m.dddddd e +-x or [-]m.dddddd E +-x
% No argument is converted, used to print a % on the output
Some simple examples
int x = 31;
printf(“%d”,x); /* prints the value in x as a Decimal number */
printf(“%x”,x); /* prints the value in x as hexadecimal number
– will print 15 on the screen */

char c1 = ‘M’;
printf(“%c”, c1); /* character M is printed on the screen */

char mymsg[] = “Hello Students”;


printf(“%s”,mymsg); /* The string Hello Students is printed */
Reading Data
• scanf(“control string”, arg1, arg2,….) can be used to read formatted input
• Control string has similar semantics to the printf format string
• Point to note is that arg1, arg2 should be addresses where we want the
values that are read to be stored
• Since C uses call by value for function parameters, arg1, arg2 need to be pointers
to the variables that we want to use to store the read values
• More on pointers in later classes..
int x;
scanf(“%d”,&x); /* reads an integer and stores it
in variable x */
Operators - Arithmetic
• Arithmetic Operators are the following:
Operator Function
+ Addition
- Subtraction
* Multiplication
/ Division (Integer division truncates any fractional part)
% Modulo operator – x%y produces the remainder when x is divided by
y – Only for integers

• + and – have same precedence, it is lower than precedence of *, / and %.


• Unary + or – have the highest precedence
• Associativity is from left to right
Operators – Relational
• Relational Operators are listed below:
Operator Function
> Greater than
< Lesser than
>= Greater than or equal to
<= Lesser than or equal to
== Equality
!= Inequality

• >, >=, <, <= all have same precedence


• == and != have lower precedence than >, >=….
• Relational operators all have lower precedence than arithmetic operators
Operators – Relational
• Result of a relational operator is a TRUE or FALSE value. In C, TRUE is
typically the value ‘1’, and FALSE is the value ‘0’.
• In general any non-zero value is considered to be TRUE.
{
int x=4, y=2;

int z;
z = (x > y); /* z will get the value 1,
indicating that x>y is TRUE */
z = (x < y); /* z will get the value 0,
indicating that x<y is FALSE */
}
Operators – Logical
• Logical operators are listed below:
Operator Function
&& Logical AND
|| Logical OR
! Logical NOT

• Expressions connected by &&, || are evaluated left to right and


evaluation stops as soon as the truth or falsehood of the result is
known
• (expression1) && (expression2) – The result is TRUE only if both
expression1 and expression2 are TRUE(non-zero), else result is FALSE
• (expression1) || (expression2) – The result is TRUE if any of
expression1 or expression2 is TRUE(non-zero), else result is FALSE
Operators – Logical and Relational
together
{
int x = 4, y = 2, z = 10;
int res;

res = (x > y) && (z > y); /* res will get the value 1,
indicating that the expression
is TRUE, i.e x>y and also z>y */

res = (x < y) && (z > y); /* res will get the value 0,
as x < y is FALSE and so
the entire expression will evaluate to FALSE */

res = (x < y) || (z > y); /* res will get the value 1,


as one of the 2 sub-expressions,
in this case (z>y) is TRUE */
}
Operators – Increment and Decrement
• Logical operators are listed below:
Operator Function
++ Adds 1 to it’s operand
-- Subtracts 1 from it’s operand

• Two forms
• Prefix – Increment happens before value is taken
int x=5, y; /* x, y are int variables. x is assigned value 5 */
++x; /* value of x is incremented – contains 6 now */
y = ++x; /* Prefix form, so x is first incremented, becomes 7. y is
assigned value 7 */
• Postfix – Existing value is taken, then increment happens
int x=5, y; /* x, y are int variables, x is assigned
value 5 */
x++; /* value of x is incremented – contains 6
now */
y = x++; /* Postfix form, value of x which is 6 is
assigned to y, then x is incremented to 7 */
Ternary Operator
• C provides an operator which can be used to write a single statement
that can check a condition and assign different value to a variable (or
in general take different actions by calling different functions)
• Syntax
expr1? expr2 : expr3
• expr1 is first evaluated
• If expr1 is TRUE, then expr2 is evaluated, and the result of this entire expression is the result
of expr2
• If expr1 is FALSE, then expr3 is evaluated and the result of this entire expressions is the result
of expr3
Ternary Operator - Example
{
int a = 2, b = 5;
int min;

min = (a < b)? a:b;


/* The variable ‘min’ gets the minimum of the 2
variables ‘a’ and ‘b’.
First (a < b) is evaluated. If this is TRUE,
then a is less than b, and so assign ‘a’ to ‘min’. Else,
‘b’ is the smaller (or equal number) and assign that to
‘min’ */
}
Bitwise Operators
• C has a unique set of operators that can be used to modify values at
the bit level
• Quite useful in many system programming tasks where we often have to write
certain bits in some hardware registers.
• Operators &, |, ^ and ~ follow the standard Boolean logic operations of AND,
OR, XOR and NOT at a bit level as shown below
• Individual bit of each operand are taken and the following truth table is
applied
AND - & OR - | XOR - ^ NOT - ~
A ~A
A B A&B A B A|B A B A^B
0 1
0 0 0 0 0 0 0 0 0 1 0
0 1 0 0 1 1 0 1 1
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0
Bitwise Operators - Examples
{
unsigned short x = 0x5555; /* 01010101 01010101 in Binary */
unsigned short y = 0xA5A5; /* 10100101 10100101 in Binary */
unsigned short z;
z = x & y; /* z will have 00000101 00000101 i.e 0x0505 */
z = x | y; /* z will have 11110101 11110101 i.e 0xF5F5 */
z = x ^ y; /* z will have 11110000 11110000 i.e 0xF0F0 */
z = ~x; /* z will have 10101010 10101010 i.e 0xAAAA */
}
Bitwise Shift Operators
• The shift operators are >> and <<.
• >> is the right shift operator
• << is the left shift operator
• Typical Usage: (expr) << num_bits or (expr) >> num_bits
• expr should be a integer data type
• num_bits specify the number of bits to shift left or right
• Example
{
unsigned short x = 0xAAAA; /* 10101010 10101010 in Binary
*/
unsigned short y;
y = x << 1; /* y will have 01010101 01010100 – 0x5554 */
}
Bitwise Shift Operators…..
{
unsigned short x = 0xAAAA; /* 10101010 10101010 in Binary */
unsigned short y;
y = x >> 1; /* y will have 01010101 01010101 – 0x5555/
}

{
short x = 0xAAAA; /* 10101010 10101010 in Binary */
short y;
y = x >> 1; /* y will have 11010101 01010101 – 0xD555/
}
(Note the difference in result when we use signed quantities, i.e short
instead of unsigned short – This is called arithmetic right shift)
Assignment Operator
• Apart from the simple assignment using ‘=‘, C supports an additional construct that is
called ‘assignment operator’
• Syntax:
• expr1 op= (expr2
• This is equivalent to expr1 = (expr1) op (expr2), and is a shorthand notation used commonly
• ‘op’ can be any of +, -, *, /, %, <<, >>, &, ^, |
• Example
{
int x=2, y;
x += 4; /* This is nothing but x = x + 4, and x will get the value 6 */
y = x; /* y will get the value 6 */
}
Operator Precedence, Associativity
Operators Associativity Precedence
() [] -> . Left to right Highest
! ~ ++ -- + - * & (type) sizeof Right to left
* / % Left to right
+ - Left to right
<< >> Left to right
< <= > >= Left to right
== != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Right to left
= += -= *= /= %= &= ^= |= <<= >>= Right to left
, Left to right Lowest
Comma operator
• Not used very often
• A pair of expressions separated by a ‘,’ is evaluated left to right and
the type and value of the result are the type and value of the right
operand
• For example,
{
int x, y, z;
x = (y=2,z=5);
printf(“%d\n”,x); /* Will print 5 */
}
‘sizeof’ Operator
• It is a compile-time unary operator that can be used to compute the size of a given variable
• Returns the size of the object in bytes
• Usage:
sizeof <variable>
sizeof (<type name>)
• Example:
{
long y;
int x;
x = sizeof(y);
printf (“%d\n”,x); /* will print the number of bytes
occupied by variable y */
}
Type Conversions
• When we have an operator that has operands of different types, they
are converted to a common type according to a small set of rules
• In general, ‘narrower’ operands are converted to the ‘wider one’ without
losing information.
• Like converting an integer to float, or an int to long.
• Assignment expressions that try to assign a ‘larger’ type to a ‘smaller’
type might lose information.
• For example assigning a ‘long’ variable to a ‘int’ variable
• Compiler may generate a warning, but it is not legal
• General philosophy in the C language design is that the programmer
knows what he is doing
Type casting
• Implicit conversions based on the standard set of rules occurs in expressions, assignments where multiple
types are involved.
• This is needed in scenarios, especially when we want to pass some values to functions expecting a parameter
of a particular type
• The explicit casting ensures that the data is converted and passed in the right format that the called function
can understand.
• Syntax
• (type-name) expression
• For example
{
int n;
double x;
x = sqrt((double) n); /* sqrt() function expects a double as a
parameter, hence need to explicitly convert ‘n’
which is int type to a double for the
function sqrt() to get the proper value */
}
Control Flow Statements
What are control-flow statements
• These statements specify the order in which computations re performed.
• Basic statement
• Any expression, becomes a statement when it is followed by a semicolon
{
x = 0; /* Each of these lines are statements */
x++;
printf(“….”);
}
• The braces { and } are used to group declarations and
statements together – This is called a block or compound
statement
• Program execution is nothing but execution of each of
these statements in sequence.
If-else statement
• When we develop programs, we often need to take decisions, based
on some data point, and take different actions based on the decision.
• The ‘if-else’ statement is used to express decisions
• Syntax:
if (expression)
statement1
else
statement2
If-else statement…
• statement1 and statement2 can be simple basic statements, or
compound statements (block)
• The ‘else’ part is optional
• The ‘expression’ is evaluated, if it is TRUE (i.e non-zero value),
statement1 is executed. If it is FALSE (zero value), and if there is an
‘else’ part, statement2 is executed.
• There can be nested if-else statements. Since, ‘else’ part is optional,
any ambiguity is resolved by associating the ‘else’ with the closest
previous ‘else-less’ if.
If-else statement…
{
int x=2, y=5, z=10;
if( x > y)
printf(“x is greater than y\n”);
else
printf(“y is greater than x\n”);
}
If-else statement…
{
/* Code snippet assigns z to the larger of x or y after comparing them */
int x=2, y=5, z=10;
if( x > y) { /* Use of a compound statement */
printf(“x is greater than y\n”);
z = x;
}
else {
printf(“y is greater than x\n”);
z = y;
}
}
Else-if statement…
• More general form of using the if-else construct as below:
if (expression1)
statement1
else if (expression2)
statement2
else if (expression3)
statement3
….
….
else
statement-default
Else-if statement…
• In the above sequence, expression1 is first evaluated, statement1 is
executed and this terminates the chain.
• Else, if goes to the next if condition, expression2, evaluates it and
executes statement2 and terminates the chain.
• This continues, and if none of the ‘if’ clauses evaluates to TRUE, the
final ‘else’ clause ‘statement-default’ gets executed.
Else-if statement…
{
int x = 2, y = 2;
if ( x > y) {
printf(“x is greater than y\n”);
}
else if (y > x) {
printf(“y is greater than x\n”);
}
else {
printf(“x is equal to y\n”); /* statement-default */
}
}
switch statement
• A easy to use multi-way decision construct
• Tests if an expression matches one of a number of constant integer values,
which are called ‘cases’, and branches accordingly
• Syntax:
switch(expression) {
case const-expr1: statements
case const-expr2: statements

default: statements
}
switch statement
• First the ‘expression’ is evaluated and it needs to generate a integer
value
• Then the first constant expression const-expr1 is compared with the
‘expression’ value.
• If it matches, the set of statements associated with this is executed
• Execution continues after that, i.e falls through.
• An explicit ‘break’ statement is needed to exit the switch case if that is the
desired behaviour (usually)
• If const-expr1 does not match, the next one const-expr2 is compared
with ‘expression’ value and same logic continues..
switch statement
{
int x = 2;
switch(x) {
case 0:
case 1:
case 2:
case 3:
printf(“x is less than or equal to 3\n”); /* should get printed for x=2 */
break; /* Try removing this break and observe behavior */
case 4:
case 5:
printf(“x is either 4 or 5\n”);
break;
default:
printf(“x is greater than 5\n”);
break;
}
}
Iterations - Loops
What are Iterations/loops?
• We often have scenarios that require repeated execution of the same
set of tasks.
• A simple example could be converting all the letters in a string into upper
case.
• Here we need to operate one character at a time and convert it to the
appropriate upper case value.
• This basic operation has to be repeated (iterated) for all the characters in the
string.
• A programming construct that allows one to repeat the same operations for
every element of the string with appropriate checks to decide when to end
the iteration is called a basic ‘loop’ construct
while loop
• The basic syntax for while loop is:
while (expression)
statement
• The ‘statement’ above can be a single basic statement or a compound basic
statement or block i.e
while (expression) {
statement;
statement;
….
}
while loop
{
int i=0;
char c = ‘a’;
while(i < 26) { /* loop body executes till
i becomes 26 */
printf(“%c “,c);
i++;
c = c + 1; /* Increment ASCII value
of c by 1 – code point
for next alphabet */
}
}
for loop
• The basic syntax of the ‘for’ loop is follows:
for(expr1; expr2; expr3)
statement
• It is equivalent to:
expr1;
while(expr2) {
statement;
expr3;
}
for loop…
• Typically, expr1 and expr3 are assignments or function calls.
• expr2 is a relational expression, that evaluates to either TRUE or
FALSE
• The for loop body is executed as long as expr2 evaluates to TRUE
• expr1 is typically used to setup the initial conditions before the
iteration starts
• expr3 is typically used to modify some of the variables that are used
in the iteration to refer to consecutive elements for example..
for loop…
{
/* The earlier while loop implementation converted as a for loop */
int i;
char c;
for(i=0, c=‘a’; i < 26; i++, c++) {
printf(“%c “,c);
}
}
A nested for loop…
{ /* This code snippet prints a pattern of
asterisk on the screen */
for(i = 1; i <= 10; i++) {
printf(“\n”);
for(j = 0; j < i; j++) {
printf(“*”);
} /* end of inner for loop */
} /* end of outer for loop */
}
do-while loop
• Both the ‘while’ loop and ‘for’ loop test the termination condition at the top,
before entering the body
• Sometimes it is useful to have the test after making one pass of the loop
body. In this case, the loop body is executed at least once
• Syntax:
do
statement
while (expression);
• As usual, the statement can be a simple basic statement or a compound statement
• Statement is executed once, and then expression is evaluated.
• If expression is TRUE, the statement is executed again, else the loop terminates.
do-while loop
{
/* this code snippet prints numbers 0 to 9 */
int i=0;
do {
printf(“%d “,i);
i++;
} while (i < 10);
}
break statement
• We saw the use of the ‘break’ statement in the ‘switch’ statement
discussion
• Used to exit out of the switch statement
• In iterations, sometimes it is convenient to be able to exit the loop
other than by the tests at the top or bottom of the loop.
• The ‘break’ statement can be used to exit the loop.
• If it is a nested loop construct, the break causes the innermost enclosing loop
or switch to be exited immediately
break statement..
{
char mymsg[] = “Hello World”;
int i;
for(i = 0; i < strlen(mymsg); i++) {
if (mymsg[i] == ‘ ‘) {
printf(“Blank space found at index %d\n”,i);
break; /* Loop exits when a blank
space character is found */
}
}
}
continue statement
• The ‘continue’ statement is related to ‘break’, but the effect is
different
• It causes the next iteration of the enclosing ‘for’, ‘while’, or ‘do-while’ loop to
begin
• In the while and do loops, this forces the test part to be executed immediately.
• In the ‘for’ loop, control passes to the increment step.
• ‘continue’ is only for loops, and it does not apply to the ‘switch’ statement.
• Usage is in general less common than the ‘break’ statement, but
useful in some scenarios
continue statement
{
char mystr[]=“pack my box”;
int i;
for(i = 0; i < strlen(mystr); i++) {
if (mystr[i] == ‘ ‘)
continue;
mystr[i] = toupper(mystr[i]);
}
printf(“%s\n”,mystr);
}
goto statement and labels
• The ‘goto’ statement is used to transfer control directly to a given
label
• A ‘label’ is nothing but an identifier that is used to mark a particular
point in the C program. It is an identifier that is written with a ‘:’
character after the name at a point in the program.
• ‘goto’ statements should be used sparingly and it is not considered a
good programming practice.
• Formally, a ‘goto’ statement is not needed, but in some rare cases like error
handling it is easier to use.
goto statement and labels
{
for(….) {
for(….) {


if(disaster)
goto error_handler; /* The keyword ‘goto’ should be followed
by
the label – the point where execution
should jump */
}
}

error_handler: /* This is a label, nothing but a name for a location in the code */
<code to handle the error is placed here>
}
End of Unit-1

You might also like