Professional Documents
Culture Documents
Presentation 11677 Content Document 20231014034322PM
Presentation 11677 Content Document 20231014034322PM
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
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.
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 */
if (b > 5) {
/* Decision statement – ‘if’ is a keyword, ‘>’ is for greater than */
}
}
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];
char c1 = ‘M’;
printf(“%c”, c1); /* character M is printed on the screen */
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
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 */
• 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;
{
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