0% found this document useful (0 votes)
26 views109 pages

Session 1 - 2

Uploaded by

Rahul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views109 pages

Session 1 - 2

Uploaded by

Rahul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 109

Divide and Conquer Strategy

Counting basket of Coins


• Divide them into small buckets and
give them to individuals to count 
• Once individual things are done, then
simply sum all of the counts by
individuals to get total in the basket
Activity
• Count the number of tables in the lab
• Some of the students may be chosen and asked
to count number of rows in a particular are
• Then the answers may be combined
• Complexity of problem gets reduced when
problem is divided
Divide And Conquer
• Divide – break the problem into several
subproblems that are similar to the original
problem but smaller in size
• Conquer – solve the subproblems recursively.

• Base case: If the subproblem size is small enough


(i.e., the base case has been reached) then solve
the subproblem with or without more recursion
Divide And Conquer
• Top-down technique for designing
algorithms that consists of dividing the
problem into smaller subproblems
• Partial solutions are combined into the
solution of the original problem
Divide And Conquer
Isogram problem
• Given ‘n’ letters find how many isogram words
can be formed?
• A word is said to be isogram if it is formed
without repeating a letter. For example, the word
‘isogram’ itself has the property and ‘Apple’ do
not have the property as ‘p’ is repeated in the
word
Technique to solve
• Length of the word can only be maximum of ‘n’
• First letter can be any of the ‘n’ letters
• Second letter will be any of the remaining ‘n-1’
• Third letter will be any of the remaining ‘n-2’
• ...
• nth letter can be the only one left
• Therefore total number of isogram words that
shall be formed is
• n*(n-1)*(n-2)*...*1
Isogram problem

Input Output Alternate Ways


for Solution
Number of n! - Factorial of Iterative way
letters (n) n Or
Recursive
Tower of Hanoi
• Mathematical puzzle invented by a French
Mathematician Edouard Lucas in 1883
• The game consists of three pegs named as
source, destination and auxiliary
• Starts by having few discs stacked in increasing
order of size in the source peg
• Objective – All discs must be moved from source
peg to destination peg
Rules of the Puzzle
• Move only one disc at a time
• A larger disc may not be placed on top of a
smaller disk
• Each move consists of taking the upper disc from
one of the rods and sliding it onto another rod
ToH problem

Input Output Alternate Ways


for Solution
Number of disc Description of Iterative way
in source pole movements Or
(n) Recursive
Or
bitwise
algorithm
Initial Configuration
Final Configuration

Suggestion: Play the youtube video


https://www.youtube.com/watch?v=5Wn4EboLrMM
Recursive Algorithm to Solve Tower of Hanoi
• When the number of discs is 1
• Directly move from source to destination
• Otherwise
• Move n-1 discs from source to auxiliary peg by using
destination peg as intermediate
• Move nth disc from source to destination peg

• Move n-1 disc from auxiliary peg to destination peg


by using source peg as intermediate
Pseudocode for Tower of Hanoi
Solve (N, from, inter, to)
If N is 0
Exit
Else solve (N-1, from, to, inter)
Move from Src to Dst
Solve(N -1 , Aux, Src, Dst)
Pseudocode for Tower of Hanoi
• For each call of the function the from, to and inter
poles are changed
• When n = 4, the function is called for n = 3
• When n = 3, the function is called for n =2
• When n = 2, the function is called for n = 1
• When n=1, base case is reached move disc from ‘from’
pole to ‘to’ pole
Steps of Executing Pseudocode of ToH when
n=4
Change of from, to and inter pegs in call
of first solve in pseudocode when n = 4,
Value of ‘n’ From To Inter
4 Source Destn Auxiliary
3 Source Auxiliary Destn
2 Source Destn Auxiliary
1 Source Auxiliary Destn
0 Source Destn Auxiliary
Disc movements
Steps in Learning a Natural Language

Learning a Programming Language


Solve Isogram Problem using Computer
• We want to solve the problem in C
• Value of ‘n’, the number of letters has to be stored in
memory
• So we need to store data in memory
• So we need to name the location in memory - variable
• A group of characters represent a variable name
• There are different types of variable based on values that
can be stored in the memory
• The value of ‘n’ has to be got from the user – scanf in C
Solve it using Computer
• Then we have to find n! which is equal to n x (n-1)!
• Here n x (n-1) ! is an expression - how expressions are
defined in C
• Then we have to find (n-1)!  Which is (n-1) * (n-2) and so
on
• An arithmetic expression may have many operators and
order of execution is defined by precedence of operators
Solve it using Computer
• After computation, we need to show the output in the
screen – printf in C
• scanf and printf cant' work alone - we need main()

Layout of a C program
pre-processor directives – Preceded by a ‘#’
global declarations – Optional and not a good
programming practice
int main() - standard start for all C programs 
{
local variables to function main ; - all variables used in the
function must be declared in the beginning
statements associated with function main ;
}
void f1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
Components of a C program

A C program consists of the following parts:


• Comments
• Variables
• Preprocessor Commands
• Functions
•Statements & Expressions
Partial C code for Isogram Problem
/* Code to get the number of letters from user and print it*/
#include<stdio.h>
int main()
{
// Declaration of variable to store number of letters and
number // of isogram words
// Get the value of number of letters from user
//If num_Of_Letters in less than or equal to zero then error
// multiply all numbers from n to 1 to find number of
// isogram words that can be formed
// print the number of isogram words can be formed
}
Comments in C

Two types of comments


Single line and multi line comment
Single Line Comment is double forward slash
‘//’ and can be Placed Anywhere
Multiline Comments in C

• Multi line comment can be placed anywhere


• Multi line comment starts with /*
• Multi line comment ends with */
• Any symbols written between '/*’ and '*/‘
are ignored by Compiler
Character set of C
Constants, Variables and Keywords
• alphabets, numbers and special symbols when
properly combined form constants, variables and
keywords
• Constant - entity that doesn’t change
• Variable - entity that may change
• Keyword – reserved in programming language
(Equivalent to words in natural language with
predefined meaning)
Types of C Constants

Now Restrict Discussion to Primary Constants


Rules for Constructing Integer Constants
• Must have at least one digit
•Must not have a decimal point
•Can be either positive or negative
• If no sign precedes then it is assumed to be +ve
• No commas or blanks are allowed
• GCC is a 32-bit compiler therefore 4 bytes are allocated
• Range of values -2,147,483,648 to 2,147,483,647
What will be the Output of code?
#include<stdio.h>
void main()
{
printf("%d",2147483649);
//printf("%ld",sizeof(int));
}
gcc first.c
./a.out
Output
warning: format ‘%d’ expects argument of type
‘int’, but argument 2 has type ‘long int’ [-Wformat]

-2147483648
Real Constants
• Two forms
• Fractional Form
• Exponential Form
Rules for Fractional Form Real Constants
• Must have at least one digit
• Must have a decimal point
• Could be either positive or negative
• Default sign is positive
• No commas or blanks are allowed within a real
constant
• Eg: +325.34, 426.0 , -32.76, -48.5792
Exponential Form of Real Constants

• Represented as two parts separated by a ‘e’


• Part appearing before ‘e’ is called mantissa,
whereas the part following ‘e’ is called exponent
Rules for Exponential Form Real Constants
• Both parts should have atleast one digit
• Mantissa can be a real constant in fractional form
• Exponent can only be integers
• Both parts may have a positive or negative sign
• Default sign of both parts is positive
• Range of real constants expressed in exponential
form is -3.4e38 to 3.4e38
• Eg: +3.2e-5 4.1e8 -0.2e+3 -3.2e-5
Rules for Constructing Character Constants

• A character constant is a single alphabet, a single


digit or a single special symbol enclosed within
single inverted commas
• Maximum length of a character constant can be 1
character
• Eg: 'A' 'I' '5' '='
Types of C Variables
• Variable names - Names given to locations in memory
• Locations can contain integer, real or character
constants
• In any language, types of variables supported depend
on the types of constants that it can handle
• Because a particular type of variable can hold only
same type of constant
• Integer variable - integer constant, real variable - real
Rules for Constructing Variable Names
• Rules for constructing variable names of all types are
same
• Combination of 1 to 31 alphabets, digits or underscores
• Some compilers allow up to 247 characters but safer to
31 characters
• First character must be an alphabet or underscore
• No commas or blanks are allowed
• No special symbol other than an underscore
• Eg: si_int m_hra pop_e_89
Data types in C
Basic Arithmetic types - further classified into: (a)
integer types and (b) floating-point types

Enumerated types - arithmetic types that are used


to define variables that can be assigned only certain
discrete integer values throughout the program

Type void - indicates that no value is available

Derived types - They include (a) Pointer types, (b)


Array types, (c) Structure types, (d) Union types and
(e) Function types
Integer Types
Floating Point Types
Keywords
• 32 keywords available in C

Compiler vendors (like Microsoft, Borland, etc.)


provide their own keywords
Discuss Valid and Invalid variable names
• BASICSALARY
•_basic
• basic-hra
• #MEAN
• group.
• 422
• population in 2006
• FLOAT
• hELLO
I/O in C
• Basic operation in any language
• Input is got through a function scanf which is
equivalent to input or raw_input in Python
• Syntax of scanf
• int scanf(const char *format, ...) 
• Basically two or more arguments
• First format string, followed by address of variables
that are going to hold values entered by user
I/O in C
• int printf(const char *format, ...)
• contains one or more arguments
• first argument is the format string
printf and scanf format codes
code type format
d int decimal (base ten) number
o int octal number (no leading '0'
supplied in printf)
hexadecimal number (no leading '0x'
supplied in printf; accepted if
x or X int present in scanf) (for printf, 'X'
makes it use upper case for the
digits ABCDEF)
decimal number ('l' can also be
ld long applied to any of the above to
change the type from 'int' to 'long')
printf and scanf format codes
code type format
u Unsigned int decimal number
lu unsigned long decimal number
c char [footnote] single character
s char pointer string
number with six digits
f float [footnote]
of precision

lf double [footnote] number with six digits


of precision
Address of a variable
• Address of a variable can be obtained by putting a
‘&’ before the variable name
Arithmetic instructions in C
• To perform arithmetic operations between constants
and variables
• Operands shall be either constant or variables
• Variables can be of any type of integer or floating point
value or character except for modulus operator
• Modulus operator cannot be applied for floating point
values but can be applied for integer and character types
Example 1
#include<stdio.h>
void main()
{
int a = 27;
int b = 25;
int c = a -b;
printf("%d",c);
}
Output 1
2
Example 2
#include<stdio.h>
void main()
{
char a = 273;
char b = 25;
int c = a%b;
printf("%d",c);

}
Output 2
warning: overflow in implicit constant conversion [-
Woverflow]

17

Character – range is 0 to 255

256 is 0
257 is 1 and so on
Example 3
#include<stdio.h>
void main()
{
char a = 27;
char b = 25;
char c = a -b;
printf("%c",c);

}
Output 3
A special character
Arithmetic Operators in C
Operator Description
+ Adds two operands
− Subtracts second operand from the first.
∗ Multiplies both operands
∕ Divides numerator by denominator
% Modulus Operator and remainder of after
an integer division.
++ Increment operator increases the integer
value by one
-- Decrement operator decreases the integer
value by one
Precedence of Operators in C
++, -- Post increment Operators
++, -- Pre increment Operators

Parenthesis can be used to override default precedence


Example 4
#include<stdio.h>
main()
{
int a, b,c;
a = 4;
b = 2;

c = -a+--b;

printf ( "c = %d", c) ;


}
Output 4
c = -3
Example 5
#include<stdio.h>
main()
{
int a, b,c;
a = 4;
b = 2;

c = -a+ b--;

printf ( "c = %d", c) ;


printf ( "b = %d", b) ;
}
Output 5
c = -2
b=1
Example 6
#include<stdio.h>
main()
{
int a, b,c;
a = 4;

c = ++a + a++;

printf ( "c = %d", c) ;

printf ( "a = %d", a) ;

}
Output 6
c = 10 a = 6
Example 7
#include<stdio.h>
main()
{
int a, b,c;
a = 4;

c = ++a + ++a;

printf ( "c = %d", c) ;

printf ( "a = %d", a) ;

}
Output 7
c = 12 a = 6
Example 8
#include<stdio.h>
main()
{
int a, b,c;
a = 4;

c = a++ + ++a;

printf ( "c = %d", c) ;

printf ( "a = %d", a) ;

}
Output 8
c = 10 a = 6
Associativity of Operators in C
When precedence of two operators are same then
associativity of operator is considered for evaluation
Partial C code for Isogram Problem
/* Code to get the number of letters from user and print it*/
#include<stdio.h>
int main()
{
int num_Of_Letters; // Declaration of variable is mandatory in C
int num_Of_Words ; // Memory is allocated but not initialized
scanf(“%d”,&num_Of_Letters);
//If num_Of_Letters in less than or equal to zero then error
printf(“Number of letters is %d”,num_Of_Letters);
// multiply all numbers from n to 1 to find number of
// number of isogram words that can be formed
Compile and Run

• Compile and run the program named as isogram.c


• gcc isogram.c – to compile
• ./a.out – to run
Automatic Type Conversion in C
Convert a variable from one data type to another data
type
When the type conversion is performed automatically by
the compiler without programmers intervention, such
type of conversion is known as implicit type
conversion or type promotion.

The compiler converts all operands into the data type of


the largest operand.
Rules for Implicit Type Conversion in C
• Sequence of rules that are applied while
evaluating expressions are given below:
• All short and char are automatically converted to
int, then,
• If either of the operand is of type long double,
then others will be converted to long double and
result will be long double.
• Else, if either of the operand is double, then
others are converted to double.
• Else, if either of the operand is float, then others
are converted to float.
Rules for Type Conversion in C
• Else, if either of the operand is unsigned long int, then
others will be converted to unsigned long int.
• Else, if one of the operand is long int, and the other is
unsigned int, then
• if a long int can represent all values of an unsigned int,
the unsigned int is converted to long int.
• otherwise, both operands are converted to unsigned
long int.
• Else, if either operand is long int then other will be
converted to long int.
• Else, if either operand is unsigned int then others will be
converted to unsigned int.
Example 9
#include<stdio.h>
void main()
{
char a = 65;
char b = 100;
int c = a%b;
printf("%c",c);

}
Output 9
A
Example 10
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
int c = a/b;
printf("%d",c);

}
Output 10
1
Example 11
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
float c = a/b;
printf("%f",c);

}
Output 11
- 1.000000
Example 12
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
float c = a/b;
printf("%f",c);

}
Output 12
- 1.000000
Example 13
#include<stdio.h>
void main()
{
int a = 165;
float b = 100;
float c = a/b;
printf("%f",c);

}
Output 13
- 1.650000
Explicit Type Conversion
Type conversion performed by the programmer is known
as explicit type conversion
Explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type)expression;
where, data_type is any valid c data type,
and expression may be constant, variable or an expression
For example, x=(int)a+b*d;
Explicit Type Conversion
The following rules have to be followed while converting
the expression from one type to another to avoid the loss
of information:
• All integer types to be converted to float.
• All float types to be converted to double.
• All character types to be converted to integer.
Example 14
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
float c = (float)(a/b);
printf("%f",c);

}
Output 14
1.000000
Example 15
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
float c = (float) a/b;
printf("%f",c);

}
Output 15
1.650000
Assignment
• Students have to check all operators for all types of
operands, also work on to understand precedence of
operators
Scope and Lifetime of a Variable in C Language

Scope of a variable - Area of our program where we can


actually access the variable.

Life Time of a variable - Time for which the particular


variable outlives in memory during execution of program.
Global vs Local Scope

Global scope :
When variable is defined outside all functions.
It is then available to all the functions of the program and
all the blocks program contains.
Local scope :
When variable is defined inside a function or a block, then
it is locally accessible within the block and hence it is a
local variable.
Global vs Local Scope
int global = 100;          // global variable declared
void main()
{
   int local = 10;         // local variable declared
   printf("Global variable is %d",global);
   printf("Local variable is %d",local); 
func1();
}
void func1()
{
   printf("Global inside func1 is %d",global);  
Storage Classes in C
Four Storage Classes, classified based on life and scope of access:

Storage Life Scope


Class
Auto Created when a function is Can be accessed
called and destroyed  only within the
automatically when function function where
exits it is declared
Default – int n;

Register Similar to Auto but stored in Similar to Auto


register, a faster memory.
Number of register is limited.
Therefore automatically
converted to auto if necessary
register int number;
Storage Classes in C
Storage Class Life Scope

Static • Created when a function Accessible only


is called inside the function
• Mandatory for where it is defined
programmer to initialize
• Lives till the program
executes
static int n =10;
Extern Created when the Global variables
program execution starts that can be shared
across files
extern int n;
Static in C
Extern in C
Extern in C
Declaration and Definition of Variables in C
• Declaration – Information to compiler about the
variable
• Definition – Memory is allocated for the variable
according to type
• For all storage classes declaration and definition are
same except for extern
• When a keyword extern precedes, its only a
declaration and the compiler waits for definition
without raising error

You might also like