Unit 1
Unit 1
Unit 1
Introduction
Introduction to algorithms
• Algorithm is a systematic logical approach which is a well-
defined, step-by-step procedure that allows a computer to
solve a problem..
• Pseudo code is a simpler version of a programming code in
plain English which uses short phrases to write code for a
program before it is implemented in a specific
programming language.
• A flowchart is a schematic representation of an algorithm
or the diagrammatic representation of way to solve the
given problem.
Algorithm
• This is the first step to solve a mathematical or computer problem.
• Breaking down the task.
• “A sequence of activities to be processed for getting desired output from a
given input.”
• A computer program can be viewed as an elaborate algorithm.
• While writing algorithms we will use following symbol for different
operations:
Step 1: Start
Step 3: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Stop.
Example1: Pseudo code to add two numbers
Begin
Read: num1, num2;
Set sum = num1+num2;
Print sum;
End
Example1: Flowchart to add two numbers
Example2: Algorithm to find the sum of individual digits of a
given positive integer.
Step 1: start
Step 2: read a positive integer called num
Step 3: declare and initialize variables:
sum←0, dig←0
Step 4: repeat steps 4.1, 4.2, 4.3 until num greater than zero
4.1: dig ← num mod 10
4.2: sum ← sum + dig
4.3: num ← num/10
Step 5: write/ display sum
Step 6: stop
Example2: Pseudo code to find the sum of individual digits
of a given positive integer
Begin
Read num;
Set sum=0, dig=0;
While num>0 then
dig = num % 10
sum = sum + dig
num = num/10
End while
print sum
End
Example 2: Flow chart to find the sum of individual
digits of a given positive integer
Example 3 : Algorithm to find the largest among two
different numbers
Step 1: Start
Step 2: Declare variables a and b.
Step 3: Read values of a and b.
Step 4(a): If a greater than b then
Write/ Display a is the largest number.
Step 4(b): Else
Write/ Display b is the largest number.
Step 5: Stop
Example 3 : Pseudo Code to find the largest among two
different numbers
Begin
Read a and b
if a>b then
Print a is largest
else
Print b is largest
end if
End
Example 3: Flow chart to find the largest among two
different numbers
Example 4: Algorithm to convert temperature Fahrenheit to
Celsius
Algorithm:
Step 1: Start
Step 2:Read Temperature in Fahrenheit F
Step 3: convert temperature to celsius
C← 5/9*(F-32)
Step 4: Print Temperature in Celsius: C
Step 5: Stop
Example 4: Pseudo code to convert temperature Fahrenheit
to Celsius
Begin
Read Fahrenheit
set Celsius = 5/9*(Fahrenheit -32)
Print Celsius
End
Example4: Flow chart to convert temperature Fahrenheit to
Celsius
Introduction to C Language
History of C
• Developed by Dennis Ritchie in the early 1970’s at Bell
telephone laboratory.
• C is a general purpose, structured programming language.
• The first standard for C was published by ANSI (American
National Standards Institute).
C Programming Language
• Set of instructions is called as program.
• These instructions are formed using certain symbols
and words according to some rules known as syntax
rules.
• Purpose: C is used for systems programming (for
writing OS) as well as for application programming
(writing general purpose programs).
Features of C programming
• C has many built-in functions that can be used to write any
complex code or program.
• C has its own built-in library. User defined functions can be
added to extend library.
• C has many data types and operators that helps in fast
execution of program.
• A program can be separated in different modules. Modularity
makes a program easy to debug, test and maintain.
• C language is case sensitive.
Program development steps
(Creating, Compiling and running program)
• Source code is a file with instructions in high level language.
• A compiler translates the high level language into the machine
language.
• The Object code is the output of a compiler after it processes
source code.
• The Linker combines both the object code and specified header
file code and generates an Executable file.
• Loader is the program of the operating system which loads the
executable file from the disk into the primary memory(RAM) for
execution. It allocates the memory space to the executable
module in main memory and then transfers control to the
beginning instruction of the program
• CPU places the result on User window.
Structure Of A C-program
This section is used to provide small description of the program.
The comment lines are simply ignored by the compiler
/*comments or documentation*/
Preprocessing commands Preprocessing commands are used to include header files
or linking Section and to define constants, it instructs the compiler to do
required pre-processing before the actual compilation
Global declarations;
int main() Used to declare variables that are common
{ to multiple functions
local declarations;
Every C program must write this statement. This
executable statements; statement (main) specifies the starting point of the
. C program execution
.
return 0;
} The return value of the main function is considered
the "Exit Status" of the application.
On most operating systems returning 0 is a success
status like saying "The program worked fine".
A simple C program to Print Hello world
#include<stdio.h>
void main()
{
printf("Hello, World! \n");
}
Output:
Hello, World!
C Tokens
• In a C program the smallest individual units known as C tokens.
• C has 6 types of tokens namely:
1) Keywords
2) Identifiers
3)Constants
4)String literals
5)Operators.
6) White spaces.
C Tokens
• Keywords
– These are reserved words of the C language.
– There are 32 keywords in C, all the keywords are in small
case.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
• Identifiers
– An Identifier is a sequence of letters and digits, but must
start with a letter. Identifiers are case sensitive. Identifiers
specifies the names to the particular entity such as name
of variables, functions etc.
– Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If
– Invalid: 324, short, price$, My Name
• Variable
– Indicates the name of the data value.
• Constants: It refers to fixed values that do not change during
the execution of program.
– Numeric constants: integer and real(float)
– Character constants: single character and strings
• String Literals
– A sequence of characters enclosed in double quotes as
“…”. For example “13” is a string literal and not number 13.
‘a’ and “a” are different.
– Ex: “GfG”, “hello world” etc.,
• Operators
– Arithmetic operators like +, -, *, / ,% etc.
– Logical operators like ||, &&, ! etc.
• White Spaces
– Spaces, new lines, tabs. These are used to separate the
adjacent identifiers, keywords and constants.
Data types
• Data type determines the type of data a variable will hold.
• C language has some predefined set of data types to handle
various kinds of data that we can use in our program.
• Primary data types:
– void: Has no values and no operations.
– character(char): Used to store character value.
– integer(int): Used to store whole numbers.
– Floating point(float, double): Used to store real numbers.
Data type
Type Storage Value range Format
size specifier
unsigned 1 byte 0 to 255 %c
char
signed char 1 byte -128 to 127 %c
short int 2 bytes -32,768 to 32,767 %d
unsigned 2 bytes 0 to 65,535 %u
short int
long int 4 bytes -2,147,483,648 to 2,147,483,647 %ld
unsigned 4 bytes 0 to 4,294,967,295 %lu
long int
float 4 bytes 3.4*E-38 to 3.4*E+38 %f
double 8 bytes 1.7*E-308 to 1.7*E+308 %lf
long double 10 bytes 3.4*E-4932 to 1.1*E+4932 %Lf
Derived and User defined data types
• The addition operator can be used with numerical data types and
character data type.
‘c’ + ‘r’ = ‘cr’
• The remainder of division operator is used with integer data type
only.
Priority of operators:
Ex:-
3–5*7/8+6/2
3 – 35 / 8 + 6 / 2
3–4+6/2
3–4+3
-1 + 3
2
Convert arithmetic statements to C
• AxB–CxD
A*B–C*D
• (M+N)(P-Q)
(M+N)*(P-Q)
• 3x2 + 5x + 2
3*x*x* + 5*x + 2
• A+B+C
E+D
(A+B+C) / (D+E)
Assignment Operators
• Assign right hand side value (Rvalue) to the left hand side variable (Lvalue).
• The assignment operator is used in different variants along with arithmetic
operators.
simple assignment operators short hand assignment operators
a=a+1 a+=1
a=a-1 a-=1
a=a%b a%=b
a=a*b a*=b
a=a/b a/=b
Increment & Decrement Operators
• The increment and decrement operators are called as unary
operators.
• (++a): pre-increment
• (--a): pre-decrement
• (a--): post-decrement
• (a++): post-increment
Pre-Increment and Pre-Decrement
Example:
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf(“++i = %d, --j = %d",++i,--j);
}
Output:
++i = 6, --j = 4
Post-Increment or Post-Decrement
Example:
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf("i++ = %d, j-- = %d\n",i++,j--);
printf(“i = %d, j = %d\n” ,i,j);
}
Output:
i++ = 5, j-- = 5
i = 6, j = 4
Relational Operators
• They are used to compare or check the relationship between two values.
• Every relational operator has two results TRUE or FALSE.
• Relational operators are used to define conditions and take decisions in a
program.
Logical Operators
• The logical operators are used to combine multiple conditions into one
condition.
exp-1 exp-2 exp-1 && exp-2 exp-1 || exp-2
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0
exp-1 !exp-1
non-zero zero
zero non-zero
• Expression Types in C
– Infix Expression
– Postfix Expression
– Prefix Expression
Infix Expression
• The expression in which operator is used between operands is
called as infix expression.
• Structure of infix expression:
Example:
10 + 4 * 3 / 2
4 * 3 => 12
12 / 2 => 6
10 + 6 => 16
Postfix Expression
• The expression in which operator is used after operands
is called as postfix expression.
• Structure of postfix expression:
• Example:
4 5*8+
4*5 =>20
20+8 =>28
Prefix Expression
• The expression in which operator is used before
operands is called as prefix expression.
• The structure of prefix notation:
• Example:
+ * 2 3/ 10 2
2*3 => 6
10/2 =>5
6+5 =>11
Type conversion
• Type Conversion: Conversion from one data
type to another.
b=(float)a/3;
printf("8/3 = %.2f",b);
}
Decision making and branching
Introduction
• In c program, statements are executed sequentially, when no
options or repetitions are necessary.
• But the order of execution changes based on
– certain conditions
– repeats group of statements until certain condition is met
• This involves decision making to check whether a conditions has
occurred or not.
• Then direct the computer to execute some statements accordingly.
• Such decision making statements in C:
– if statement
– switch statement
– Conditional operator statement
– goto statement
if statement in c
• In c, if statement is used to make decisions based on a condition.
• The if statement verifies the given condition and decides whether a
block of statements are executed or not based on the condition
result.
• The if statement may be implemented in different forms depending
on the complexity of conditions to be tested. The different forms
are:
– Simple if statement
– if - else statement
– Nested if - else statement
– else if ladder(if-else-if statement )
Simple if statement
Syntax:
if (condition)
{
block of statement;
}
statement-x;
• In either case, either true block or false block will be executed, not both.
Example: c program to check whether given
number is even or odd
#include <stdio.h>
#include<conio.h>
void main()
{ Case 1:
int n ; Enter any integer: 100
100 is EVEN
printf("Enter any integer: ") ;
Case 2:
scanf("%d", &n) ; Enter any integer: 99
if ( n%2 == 0 ) 99 is ODD
printf("%d is EVEN\n", n) ;
else
printf("%d is ODD\n", n) ;
}
Nested if-else statement
• When a series of decisions are involved, we use more than one if-else
statement in nested form.
• The nested if-else statement can be defined using any combination of
simple if and if-else statements.
Syntax: else
if (condition-1) {
{ statements 3;
if (condition-2) }
{ statement x;
statements 1;
}
else
{
statements 2;
}
}
Example: c program to check whether given
number is even or odd if it is below 100.
#include <stdio.h>
void main(){
int n ;
printf("Enter any integer: ") ;
scanf("%d", &n) ;
if ( n < 100 ) {
printf(“%d is below 100\n", n) ; Case 1:
if( n%2 == 0) Enter any integer: 55
printf("And it is EVEN") ; 55 is below 100
And it is ODD
else
Case 2:
printf("And it is ODD") ; Enter any integer: 999
} 999 is not below 100
else
printf(“%d is not below 100" , n);
}
else if ladder(if-else-if statement )
• When multi path decisions are involved, we use a chain of ifs in
which the statement associated with each else is an if.
• Syntax:
if (condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else
statement 4;
statement x;
Example: C program to find the largest of three
numbers.
#include <stdio.h>
void main(){
int a, b, c ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}
Output:
Enter any three integer numbers: 55 60 20
60 is the largest number
• When we use conditional control statement like if statement, condition
might be an expression evaluated to a numerical value, a variable or a
direct numerical value.
• If the expression value or direct value is zero the condition becomes
FALSE otherwise becomes TRUE.
• Examples:
– if(10) - is TRUE
– if(x) - is FALSE if x value is zero otherwise TRUE
– if(a+b) - is FALSE if a+b value is zero otherwise TRUE
– if(a = 99) - is TRUE because a value is non-zero
– if(10, 5, 0) - is FALSE because it considers last value
– if(0) - is FALSE
– if (a=0, x=10) – is TRUE because it considers last value
– if(a=10, b=15, c=0) - is FALSE because last value is zero
switch statement in C
• When one of the many options is to be selected, we can use if
statement to control the selection.
• The complexity increase with increase in number of options.
• Program becomes difficult to read and flow.
• C has a built-in multi-way decision statement known as
switch.
• The switch statement tests the value of a given (or
expression) against a list of case values
• And when match is found, a block of statements associated
with that case is executed.
• expression can integer or character.
Syntax: • value1, value2 ... are constants (unique)
or constant expressions and are known as
switch (expression) case labels.
{ • block1, block2 ... are statement lists and
case value1: may contain zero or more statements.
block1
break; • No need of braces for blocks and case
case value2: labels end with colon (:).
block2 • If a case is found whose value matches
break; with the value of the expression, then the
......... block of statements that follows the case
......... are executed.
default: • The break statement signals the end of a
default block particular case and causes an exit from
break; switch.
} • The default is an optional case.
Statement-x;
Flow of execution
Example: c program to assign grades.
#include <stdio.h> case 4: printf("Third division") ;
void main(){ break ;
int n ; default: printf("Fail") ;
printf("Enter CGPA: ") ; }
scanf("%d", &n) ; }
index = n/10
switch( n ) { Case 1:
case 10: Enter marks: 85
case 9: Distinction
case 8: printf("Distinction") ; Case 2:
break ; Enter marks: 15
case 7: Fail
case 6: printf("First division") ;
break ;
case 5: printf("Second division") ;
break ;
The conditional operator
• Conditional operator is useful for making two-way decisions.
• This operator is a combination of ? and :, and takes 3 operands.
• Syntax:
conditional expression ? expression1 : expression2
• The conditional expression is evaluated first.
• If the result is non-zero, expression 1 is evaluated and its value is returned.
• Otherwise expression 2 is evaluated and its value is returned.
• For example:
if (x%2==0)
flag=1
else
flag=0
Can be written as
flag = (x%2==0) ? 1 : 0
• Using conditional operator is concise and efficient
• The conditional operator can be nested for evaluating more complex
assignment decisions.
• Example: consider the weekly salary of a sales girl who is selling some
domestic products. If x is the number of products sold in a week, her
weekly salary is given as:
4x +100 for x < 40
salary= 300 for x=40
4.5x+150 for x>40
• Using else-if ladder
if(x<40)
salary = 4*x + 100
else if (x>40)
salary = 4.5*x + 150
else
salary = 300
• This equation can be written as
salary = (x != 40) ? ((x<40) ? (4*x + 100) : (4.5*x + 150)) : 300
The goto statement
• In c, there are control statements which does not need any condition
to control the program execution flow.
• When we use goto statement in the program, the execution control
directly jumps to the line with specified label unconditionally..
• Using goto statement we can jump from top to bottom or bottom to
top.
• Syntax
goto label;
label:
Statement x; statetements;
------ -----------
label: -----------
goto label;
Statements 1;
Statements 2;
• The goto statement can be used with any statement like if, switch,
while, do-while and for etc,.
Example: forward jump
#include <stdio.h>
void main()
{
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last:
printf("We are at last printf statement!!!\n") ;
}
Output
We are at first printf statement!!!
We are at last printf statement!!!
Example: backward jump
#include<stdio.h> #include<stdio.h>
Void main()
Void main()
{
{ double x,y;
double x,y; read:
read: if ( x > 0)
scanf(“%f”, &x); {
scanf(“%f”, &x);
y = sqrt(x);
y = sqrt(x);
print(“%f %f\n”, x , y); print(“%f %f\n”, x , y);
goto read; goto read;
} }
}
Decision making and looping
The for statement
• The for loop is entry-controlled loop.
• It is concise control structure.
• General form of for:
Control variable is
Initialization of control variables incremented
#include <stdio.h>
int main()
if ( x == 5 )
continue; /* skip remaining code in loop only
if x == 5 */
}
printf("\nUsed continue to skip printing the value 5\n");
return 0;
}
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5 2000 Prentice H
Loops
• Loops are used to repeat a set of statements.
• In looping, a sequence of statements are repeatedly
executed until some end condition is met.
• A program loop has
Body of the loop.
Control statement.
• Depending on the position of the control statement in
the loop, control structure has
– Entry controlled loop.
– Exit controlled loop.
• Entry controlled and exit controlled loop
structure is shown below: