SlideShare a Scribd company logo
1 of 83
Download to read offline
Programming For Problem
Solving (PFPS)
LECTURE 1
Introduction to Algorithms and
Flowcharts
Algorithms and Flowcharts
• Algorithm and flowchart are the powerful tools
for learning programming
• An algorithm is a step-by-step analysis of the
process, while a flowchart explains the steps of a
program in a graphical way.
• Algorithm and flowcharts helps to clarify all the
steps for solving the problem.
• For beginners, it is always recommended to
first write algorithm and draw flowchart for
solving a problem and then only write the
program.
2
Algorithms
• A typical programming task can be divided into two
phases:
• Problem solving phase
– Produce an ordered sequence of steps that describe
solution of problem
– This sequence of steps is called an algorithm
– An algorithm is a sequence of steps to solve a particular
problem
– An algorithm is defined as an ordered set of unambiguous
steps that produces a result and terminates in a finite time
• Implementation phase
– Implement the program in some programming language
3
Steps In Problem Solving
• First produce a general algorithm called
pseudocode.
• Pseudocode is an artificial and informal
language that is very similar to everyday
English. It helps programmers develop
algorithms.
• Refine the algorithm successively to get step
by step detailed algorithm that is very close to
a computer language.
4
Characteristics of an Algorithm
• Algorithm has the following characteristics
– Input: An algorithm may or may not require input
– Output: Each algorithm is expected to produce at
least one result
– Definiteness: Each instruction must be clear and
unambiguous.
– Finiteness: If the instructions of an algorithm are
executed, the algorithm should terminate after
finite number of steps
5
Control Structures Involved In
Algorithm and Flowchart
• The algorithm and flowchart include following three
types of control structures.
– Sequence: In the sequence structure, statements are
placed one after the other and the execution takes place
starting from up to down.
– Branching (Conditional): In branch control, there is a
condition and according to a condition, a decision of
either TRUE or FALSE is achieved. In the case of TRUE, one
of the two branches is explored; but in the case of
FALSE condition, the other alternative is taken. Generally,
the ‘IF-THEN’ construct is used to represent branch
control.
– Loop (Repetition): The Loop or Repetition allows a
statement(s) to be executed repeatedly based on certain
loop condition using WHILE, Do-WHILE and FOR loops.
6
Example of Pseudocode and Algorithm
• Example 1: Write the pseudocode and detailed algorithm
to determine a student’s final grade and indicate whether
the student is passing or failing. The final grade is
calculated as the average of four marks.
• Pseudocode:
– Input a set of 4 marks
– Calculate their average by adding the marks and
dividing the sum by 4
– if average is below 50
Print “FAIL”
else
Print “PASS
7
Example of Pseudocode and Algorithm
• Detailed Algorithm
– Step 1: Input M1,M2,M3,M4
– Step 2: GRADE = (M1+M2+M3+M4)/4
– Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
8
Advantages of Algorithm
• It is a step-wise representation of a solution to a
given problem, which makes it easy to
understand.
• An algorithm uses a definite procedure.
• It is not dependent on any programming
language, so it is easy to understand for anyone
even without programming knowledge.
• Every step in an algorithm has its own logical
sequence so it is easy to debug.
9
Flowchart
• Flowchart is defined as a diagrammatic /graphical
representation of sequence of steps to solve a
problem.
• By looking at a flowchart, any one can easily
understand the operations and sequence of steps
involved in the solution
• Flowchart is often considered as a blueprint of a
design used for solving a specific problem
• Different symbols are used to draw each type of
flowchart.
10
Advantages of Flowchart
• Flowchart is an excellent way of communicating the logic of a
program.
• It provides an easy and efficient way to analyze the solution to
a problem.
• During program development cycle, the flowchart plays the
role of a blueprint, which makes the program development
process easier.
• After successful development of a program, it needs
continuous timely maintenance during the course of its
operation. The flowchart makes program or system
maintenance easier.
• It is easy to convert the flowchart into any programming
language code.
11 12
Standard Symbols Used in a Flowchart
Control Structures Representation in
Flowchart
13
Symbols Used in Algorithm and
Flowchart
• Assignment Symbol (← or =) is used to assign
value to the variable. E.g., to assign value 5 to
the variable HEIGHT, statement is HEIGHT ← 5
or HEIGHT = 5
• The symbol ‘=’ is used in most of the
programming language as an assignment symbol,
the same has been used in all the algorithms and
flowcharts in the manual
• The statement C = A + B means that add the
value stored in variable A and variable B then
assign/store the value in variable C
14
15 16
17
GO TO statement is also called unconditional transfer of
control statement is used to transfer control of execution to
another step/statement. E.g. the statement GOTO n will
transfer control to step/statement n.
Note: We can use keyword INPUT or READ or GET to accept
input(s) /value(s) and keywords PRINT or WRITE or DISPLAY
to output the result(s).
Sequential: Algorithm and Flowchart
18
19
Branching (Selection): Algorithm and
Flowchart
Looping: Algorithm and Flowchart
20
Programming For Problem
Solving (PFPS)
LECTURE 2
Introduction to Programming
Languages and Programming
Language Translators
Introduction to Programming
• A language that is acceptable to a computer
system is called a programming language or
computer language
• The process of creating sequence of
instructions in any programming language is
called programming or coding
• A program is a set of instructions written to
perform a specific task by the computer
• A set of large programs is called a software
2
Computer Languages
• A computer language is the main medium of
communication between the users and the
computer systems
• Every computer language is bounded by rules
known as syntax of the language
• The user is bound by the syntax while
communicating with the computer system
• All the available computer languages are
categorized into two basic types of languages:
– Low level language
– High level language
3
Computer Languages and its Types
4
Low Level Language
• The term low level highlights the fact that this language
is closer to a language that the machine understands
• Low level languages are the machine codes in which
the instructions are given in machine language in the
form of 0 and 1 to a computer system
• The main function of the low level language is to
operate, manage and manipulate the hardware and
system components
• Low level language is also divided into two categories:
– Machine language
– Assembly language
5
Low Level Language
• Machine Language
• It is one of the low-level programming languages
which is the first generation language developed for
communicating with a Computer.
• It is written in machine code which represents 0 and 1
binary digits inside the computer string which makes
it easy to understand and perform the operations
• It is well known that a computer system can recognize
electric signals (0 stands for turning off electric pulse
and 1 stands for turning on electric pulse)
6
Low Level Language
• Advantages of Machine Language
– The main advantage of using Machine language is
that there is no need of a translator or interpreter to
translate the code, as the Computer directly can
understand
• Disadvantages of Machine Language
– The programmer have to remember the operation
codes, memory address every time you write a
program and also hard to find errors in a written
program
– It is a machine dependent and can be used by a single
type of computer
7
Low Level Language
• Assembly Language
– It is the second generation programming language
that has almost similar structure and set of commands
as machine language
– Instead of using numbers like in machine languages
here we use words or names in English and also
symbols for different operations
– The programs that have been written using words,
names and symbols in assembly language are
converted to machine language using an assembler
8
Low Level Language
• Advantages of Assembly Language
– The main advantage of using assembly language is its
speed that makes it the mostly used low level
language till today that is used by many programmers
• Disadvantages of Assembly Language
– The main disadvantage of this language is that it is
written only for a single type of CPU and does not run
on any other CPU (machine dependent)
9
High Level Language
• To overcome the limitation of low level languages, high
level language has evolved which uses normal English
and is easy to understand to solve any problem
• The high level languages are the most commonly used
that helps programmers to read, write and maintain code
• It is also considered as the third generation language that
is used by many programmers
• High level languages require a programming language
translator that can convert the high level language to
machine language
10
High Level Language
• Advantages:
– Programming with this kind of language is quite
easy and simple
– High level languages are computer independent
– Programs written in high level languages are
portable across multiple systems
11
High Level Language
• Some of the various high level languages are as given below:
– BASIC (Beginners All Purpose Symbolic Instruction Code): It
is widely used, easy to learn general purpose language. Mainly
used in microcomputers in earlier days.
– COBOL (Common Business Oriented language): A
standardized language used for commercial applications.
– FORTRAN (Formula Translation): Developed for solving
mathematical and scientific problems. One of the most
popular languages among scientific community
– C: Structured Programming Language used for all purpose
such as scientific application, commercial application,
developing games etc.
– C++: Popular object oriented programming language, used for
general purpose.
12
Programming Language Translators
• To make the machine understand the
instructions provided by both the languages,
programming language translators are used
• They transform the instructions written by
programmers into a form which can be
interpreted and executed by the computer.
• The various tools/programming language
translators used to achieve this purpose are:
– Compiler
– Interpreter
– Assembler
– Linker
13
Programming Language Translators
14
Programming Language Translators
• Flowing are the various tools to achieve this
purpose:
– Compiler: The software that reads a program written
in high level language and translates it into an
equivalent program in machine language is called
as compiler.
– The program written by the programmer in high
level language is called source program and the
program in binary code (machine language) generated
by the compiler after translation is called as object
program.
15
Working of a Compiler
16
Programming Language Translators
– Interpreter: It also coverts each high-level
program statement into the machine code.
– The interpreter takes 1 statement, translates it,
executes it and then again takes the next
statement.
17
Working of Interpreter and Assembler
• Both compiler and interpreters do the same job i.e.,
converting higher level programming language to
machine code but their method of execution is
different.
18
19
Programming Language Translators
– Assembler: The software that reads a program
written in assembly language and translates it into
an equivalent program in machine language is
called as assembler.
20
Programming Language Translators
• Linker: A linker or link editor is a computer program
that takes one or more object files generated by a
compiler and combines them into a single
executable file, library file, or another object file.
21
Loader
• In computer systems a loader is the part of an operating
system that is responsible for loading programs and
libraries.
• It is one of the essential stages in the process of starting
a program, as it places programs into memory and
prepares them for execution.
• Loading a program involves reading the contents of
the executable file containing the program instructions
into memory, and then carrying out other required
preparatory tasks to prepare the executable for running.
• Once loading is complete, the operating system starts the
program by passing control to the loaded program code.
22
Working of Linker
23
Program Design Methods
• There are two approaches mainly followed for
program design:
– Top-down programming
– Bottom-up programming
• Top-down programming:
• It refers to a style of programming where an application is
constructed starting with a high-level description of what it
is supposed to do
• It then breaks the specification down into simpler and
simpler pieces, until a level has been reached that
corresponds to the primitives of the programming
language to be used
24
Program Design Methods
• Bottom-up programming:
• Bottom-up programming is the opposite of top-
down programming.
• It refers to a style of programming where an
application is constructed starting with existing
primitives of the programming language.
• It constructs gradually more and more
complicated features, until the all of the
application has been written.
25
Top-down program design method
26
Bottom-up program design method
27
Programming For Problem
Solving (PFPS)
LECTURE 3
Introduction to C
Brief History of C
• The C programming language is a structure oriented
programming language, developed at Bell Laboratories in
1972 by Dennis Ritchie.
• C programming language features were derived from an
earlier language called “B” (Basic Combined
Programming Language – BCPL)
• C language was invented for implementing UNIX
operating system.
• In 1978, Dennis Ritchie and Brian Kernighan published
the first edition “The C Programming Language” and is
commonly known as K&R C.
2
Brief History of C
• In 1983, the American National Standards
Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C.
The resulting definition, the ANSI standard, or
“ANSI C”, was completed late 1988.
• Many of C’s ideas & principles were derived from the
earlier language B, thereby naming this new
language “C”.
3
Why is C popular?
• C is a reliable, simple and easy to use programming
language.
• It is a small, block-structured (modular) programming
language that allows the programmer to break the code
into smaller fragments to improve the readability of the
code and hence make the program simple to debug and
maintain.
• C is a portable language, which means that C programs
written in one platform can be run on other platforms
with little or no modification.
– Eg. Suppose you are a Windows user but for some
apparent reasons you want to switch to Linux. The
programs that you have written and executed in Windows
will work and give the same output when copied and
pasted in a terminal while using LINUX.
4
Why is C popular?
• C has one of the largest collection of operators,
such as those used for calculations and data
comparisons.
• The C standard library provides you a large range
of inbuilt functions that program development
quite easy for the programmers.
• The C programming language helps you to
manage memory efficiently as it supports the
feature of dynamic memory allocation and bit
fields.
5
Why to study C?
• C serves as the base language or a prerequisite for learning
other programming languages. Most of the popularly used
programming languages came after the birth of C.
• By the early 1980s, C was already a dominant language
in the minicomputer world of Unix systems. Since then, it
has spread to personal computers (microcomputers) and
to mainframes.
• C language is the most widely used language in operating
systems development today.
• Many software houses use C as the preferred language
for producing various types of software as programs written
in C are efficient and fast.
6
Characteristics of a C Program
• Middle level language – Such languages don’t provide all
the built-in functions found in high level languages, but
provides all building blocks that we need to produce the
result.
• Small size – C language has only 32 keywords.
• Extensive use of function calls – enables the end user to
add their own functions to the C library.
• Rich set of Library Functions – It is a robust language
with a rich set of built-in functions and operators that
can be used to write any complex program.
7
Characteristics of a C Program
• Structured language – The structured
programming language allows a programmer to code a
program by dividing the whole program into smaller
units or modules.
• Low level (Bitwise) programming – C supports low
level programming features which enable the
programmer to carry out bit-wise operations. These
features are normally provided in assembly
language or machine language.
• High level language constructs ̶ In addition to the low
level language constructs, high level constructs (data
type and operators) are available in C.
8
Characteristics of a C Program
• Pointer implementation ̶ Extensive use of pointers
for memory allocation dynamically, array, structures
and functions.
• Efficient and fast ̶ programs written in C are efficient
and fast due to its variety of data types and powerful
operators.
• Portable – It can be compiled on a variety of computers.
• Supports loose typing – C is considered to be
weakly typed, because you can convert any type to any
other type through a cast.
9
Uses of C
• Database systems
• Graphics packages
• Word processors
• Spreadsheets
• Operating system development
• Compilers and Assemblers
• Network drivers
• Interpreters
10
Structure of a C Program
• A C program is divided into different sections.
There are six main sections in a basic c
program. The six sections are:
1. Documentation Section
2. Link Section
3. Definition Section
4. Global Declarations Section
5. Main functions Section
6. Subprograms Section
11
Structure of a C Program
12
Structure of a C Program
• Documentation Section
– The Documentation Section consists of a set of
comment lines giving the name of the programmer,
date and other details about the program.
– Comments may appear anywhere within a program.
Text between /* and */ appears as a comment in C.
For Example: /* This is a Comment */
– Documentation section helps anyone to get an
overview of the program.
13
Structure of a C Program
• Link Section
̶ The link section provides instructions to the compiler
to link functions from the system library using
the #include directive.
̶ This leads to the compiler to link the header files from
the system libraries.
̶ Example:
#include<stdio.h>
̶ It tells the C compiler to include the contents of the
system file called stdio.h (Standard Input Output
header file).
14
Structure of a C Program
• Definition Section
– In this section, we define different symbolic constants
using the #define directive.
– The keyword define is used in this part.
– Example:
#define PI=3.14
– This statement defines a symbolic constant PI with
value 3.14.
15
Structure of a C Program
• Global Declaration Section:
̶ There are some variables that are used in more than
one function. Such variables are called global
variables and are declared in the global declaration
section that is outside of all the functions.
̶ This section also declares all the user-defined
functions.
̶ Example:
float area(float r);
int a=7;
16
Structure of a C Program
• main() function Section:
– Every C program must have one main function section
which is the starting point of the program execution.
– This section contains two parts: declaration part and
executable part.
• Declaration part: The declaration part declares all
the variables used in the executable part.
• Executable part: There is at least one statement in the
executable part.
– These two parts must appear between the opening
and closing braces.
17
Structure of a C Program
• main() function Section:
– The program execution begins at the opening brace and
ends at the closing brace.
– The closing brace of the main function is the logical end of
the program.
– All statements in the declaration and executable part end
with a semicolon.
– Example:
int main(void)
{
int a=10;
printf(" %d", a);
return 0;
}
18
Structure of a C Program
• Subprogram Section:
– The subprogram section contains all the user defined
functions that are used to perform a specific task.
– These user defined functions are called in the main
function.
– User defined functions are generally placed just after
the main() function, although they may appear in any
order.
– Example:
int add(int a, int b)
{
return a+b;
}
19
Sample Program
20
Things to know in the Sample Program
• #include <stdio.h>:
– #include is a pre-processor directive. It is an instruction to
the C compiler to include the contents of the file stdio.h.
– stdio.h is the name of the standard library definition
file for all STanDard Input and Output functions.
• void:
– Many programming languages need a data type to define
the lack of return value to indicate that nothing is being
returned.
– The void data type is typically used in the definition and
prototyping of functions to indicate that either nothing is
being passed in and/or nothing is being returned.
21
Things to know in the Sample Program
• scanf() and printf()
– The standard input/output library contains a
number of functions for formatted data
transfer
– The two functions that are used are scanf()
(scan formatted) and printf() (print formatted)
for reading input from keyboard and displaying
output on screen.
22
Sample Program
/*File Name: areaofcircle.c, Author: Manthan Naik, Date:
09/08/2019, Description: a program to calculate area of circle*/
#include<stdio.h> //link section
#define pi 3.14; //definition section
float area(float r); //global declaration
int main() //main function
{
float r; //Declaration part
printf(" Enter the radius:"); //Executable part
scanf("%f", &r);
printf(“The circle area is: %f", area(r));
return 0;
}
23
Sample Program
float area(float r) //Subprogram Section
{
return (pi * r * r);
}
• Output:
Enter the radius:
7
The circle area is: 153.860001
24
Files Used in a C Program
• Source File:
– This file contains the source code of the program.
– The file extension of any c file is .c.
– The file contains C source code that defines the main
function and may be other functions.
• Header File:
– A header file is a file with extension .h which
contains the C function declarations and macro
definitions for c inbuilt library functions.
25
Files Used in a C Program
• Object File:
– An object file is a file containing object code, with an
extension .o, which are produced by an assembler,
compiler, or other language translator
– This is then used as input to the linker, which in turn
generates an executable file by combining the
object files.
• Executable File:
– The binary executable file is generated by the linker.
The linker links the various object files to produce a
binary file that can be directly executed.
26
Compilation and Execution of a C Program
27
Programming For Problem
Solving (PFPS)
LECTURE 4
C Language Fundamentals
Elements of C
• This lecture deals with the basic elements, which are
used to create a C program. These elements are:-
– Character set
– Keywords
– Identifiers
– Data Types
– Constant and Variables
– Statements
2
Character Set
• Character set in C includes the following:
– The uppercase English alphabets A to Z
– The lowercase English alphabets a to z
– The digits 0 to 9
– Certain special characters as building blocks to form
basic program elements i.e., Constants, variables,
operators, expressions and statements.
3
Character Set
4
Keywords
• Keywords are the words whose meaning
has already been explained to the C
compiler.
• The keywords cannot be used as variable
names because assigning a new meaning to
the keyword is not allowed by the C compiler.
• There are only 32 keywords available in C.
5
Keywords
6
Identifiers
• Identifiers are user-defined names given to
various items in the program, such as variables,
functions, arrays, structure, union, etc.
• An identifier can be composed only of uppercase
letters, lowercase letters, underscore and digits,
but should start only with an alphabet or an
underscore.
• Underscore character is usually used as a link
between two words in long identifiers.
7
Rules for Constructing Identifiers
1) The first character in an identifier must be an alphabet or
an underscore and can be followed by any number of
alphabets, or digits or underscores.
2) Identifiers must not begin with a digit.
3) Uppercase and lowercase letters are distinct. That is,
identifiers are case sensitive.
4) Commas or blank spaces are not allowed within an
identifier.
5) Keywords cannot be used as an identifier.
6) Identifiers should not be of length more than 31
characters.
7) Identifiers must be meaningful, short, quickly and easily
typed and read.
8
Example of Identifiers
• Valid identifiers: total sum average
_x y_ mark_1 x1
• Invalid identifiers:
1x - begins with a digit
char - reserved word
x+y - special character
9
Data Types
• In the C programming language, data types refer to a
domain of allowed values and the operations that
can be performed on those values.
• The data type of a variable determines the
following information:
– Identify the type of a variable when it is declared
– The amount of space the variable occupies in storage
– Specific operations that can be performed on the
variable
10
Data Types
• There are 4 primary/basic data types in C, which are as
follows :–
– char is used to store any single character
– int is used to store any integer value, float and double
– float is used to store any single precision floating point
number
– double is used to store any double precision floating point
number
• We can use two qualifiers with these basic types to get
more data types. The two types of qualifiers are as
follows:
– Sign qualifier: signed and unsigned
– Size qualifier: short and long
11
Built-In/Basic Data Types in C
• Based on the combination of each of the primary data types
and the qualifiers (sign and size) we can have the following
basic data types:
12
Data Types in C
• C provides the following categories of data types:
13
Derived Data Types in C
• Derived data types are composed of fundamental
data types. Example of derived data types are arrays,
structures, pointers etc.
– A collection of integer values stored contiguously
makes an array
• Derived data types are what we can create by
combining various primitive data types. There are
basically three derived types in C:
– Array
– Function
– Pointer
14
User-defined Data Type (UDT)
• Sometimes, the basic set of data types defined in the C
language such as int, float etc. may be
insufficient for our application.
• In such circumstances, we can create your own data
types which are based on the standard ones.
• A User-defined Data Type (UDT) is a data type that
derived from an existing data type. UDTs can be used to
extend the built-in data types already available and
create your own customized data types.
• There are three mechanisms for doing this in C:
– using typedef
– using structure
– using union
15
Void Data Type in C
• Many programming languages need a data type to
define the lack of return value to indicate that
nothing is being returned.
• The void data type is used in the definition and
prototyping of functions to indicate the following:
– Nothing is being passed as parameter to the
function.
– No return value is being returned from the
function.
16
Size and Range of Data Types in C
• Size refers to the amount of memory each data type
requires for its storage in memory.
• We can use the sizeof() operator to check the size of
a variable.
• The size of data types in C is dependent on the
compiler.
• Range means the maximum and minimum value that
can be stored inside the variable of a given data type.
17
Steps to Print the Range of Data Types
• The following three steps are used to compute the range
(min to max) of permissible values in a particular data
type:
1) Convert the size of the data type in bytes into bits (N).
2) For signed data types, the following formula is used to
find the minimum and maximum range of values:
-(2N-1) to 2N-1 - 1
Note: N-1 bits are used to compute range because one bit is used to store
the sign of the signed data type.
3) The minimum and maximum range of an unsigned data
type is given by: 0 to (2N - 1)
where, N is the sizeof(datatype) × 8 i.e., total number of
bits used by the data type.
18
19 20
Constants
• C constants is the most fundamental and essential part of
the C programming language.
• They have fixed values that are used in a program i.e., its
value remains the same during the entire execution of
the program.
• Constants are also called literals and they can be of
various data types.
• The constants can be initialized once only.
• A constant can be defined using the following syntax:
const datatype constant_name;
const keyword defines a constant in C.
21
Types of Constants in C
• Constants are categorized into two basic types, and
each of these types has its subtypes.
• C constants can be divided into two major categories:
– Primary Constants
– Secondary Constants
• The primary constants can be further categorized as:
– Numeric Constants
• Integer Constants
• Real Constants
– Character Constants
• Single Character Constants
• String Constants
• Backslash Character Constants
22
Types of Constants in C
23
Integer Constants
• An integer is a numeric literal without any fractional or
exponential part.
• There are three types of integer literals in C
programming:
• Decimal Integer constant (base 10):
• Digits: 0 to 9
• E.g.: 49, 58, -62, etc.
• Octal Integer constant (base 8):
• Digits: 0 to 7
• Add “0” before the value.
• E.g.: 045, 056, 067, etc.
• Hexadecimal Integer constant (base 16):
• Digits: 0 to 9 and A to F
• Add “0x” before the value
• E.g.: 0x42, 0x56, 0x67, etc.
24
Integer Constants
Rules for constructing Integer Constants in C
– 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
(Note: This range is for 16-bit compiler. For a 32-bit
compiler the range would be even greater.)
25
Real Constants/Floating-point Literals
• A floating-point literal is a numeric literal that has
either a fractional form or an exponent form.
• Rules for constructing Real constants (Fractional
Form)
– A real constant must have at least one digit
– It must have a decimal point
– It could be either positive or negative
– If no sign precedes an real constant, it is assumed to
be positive.
– No commas or blanks are allowed within a real
constant.
• For example: +867.9, -26.9876, 654.0.
26
Real Constants/Floating-point Literals
• Rules for constructing Real Constants (Exponential
Form)
– The mantissa part and the exponential part should be
separated by the letter ‘e’
– The mantissa may have a positive or negative
sign(default sign is positive)
– The exponent must have at least one digit
– The exponent must be a positive or negative
integer(default sign is positive)
– The range of real constants in exponential form is -
3.4e38 and +3.4e38
• For example: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4
27
Character Constants
• A “single character constant" is formed by enclosing a
single character within single quotation marks (' ').
• A character constants can contain any uppercase
alphabet, any lowercase alphabet, a space, a digit and
any special character. For Example: ‘m‘, ‘=‘, ‘A’,
etc.
• Character constant declaration: A character constant is
declared by using const keyword.
Syntax: const char constant_name = 'value';
• Format Specifier for Character Variable :
– “%c” is used as format specifier for character inside C.
– We can also use “%d” as format specifier because each
character have its equivalent integer value known as ASCII
value. 28
Character Constants
• Rules for Constructing Single Character constants
– A single character constant or character constant is a
single alphabet, a single digit or a single special
symbol enclosed within single quotes.
– The maximum length of a single character constant
can be one character.
– Each character constant has an integer value that is
determined by the computer’s particular character
set.
29
String Character Constant
• A character string, a string constant consists of a
sequence of characters enclosed in double quotes.
• Rules for Constructing String Constants
– A string constant may consist of any combination of
digits, letters, escaped sequences and spaces enclosed
in double quotes.
– Every string constant ends up with a NULL character
(‘0’) which is automatically assigned by the compiler
before the closing double quotation mark.
• For Example: “a”, “Ali”, “123”, “How are you”, etc. are
string constants.
30
Escape Sequence or Backslash
Character Constant
• Escape sequence usually consists of a backslash
followed by a character. These characters
combinations are called as escape sequence.
• Although it consists of two characters, it
represents single character.
• Each escape sequence has unique ASCII value.
• They are non-printable characters.
31 32
Variables
• C variable is a named location in a memory where a
program can manipulate the data.
• This location is used to hold the value of the variable.
• The value of the C variable may get changed in the
program.
• C variable might be belonging to any of the data type
like int, float, char, etc.
33
Rules For Naming C Variable
• Variable name must begin with letter or underscore.
• Variables are case sensitive.
• They can be constructed with digits, letters.
• No special symbols are allowed other than
underscore.
• For Example: sum, height, _value are some variable
names.
34
Declaring and Initializing C Variable
• Variables should be declared in the C program before
they are in use. This is done is done for informing the
compiler that there exist a variable with specific data
type which is used in the program.
• Variable declaration does the following things:
– It tells the compiler what the variable name is.
– It specifies what type of data the variable will hold.
• There are two things which need to be defined while
declaring a variable:
– Data type - which type of value is going to be stored in the
variable.
– Identifier - Valid variable name (identifier is the name of
the allocated memory blocks for the variable).
35
Declaring and Initializing C Variable
• When a variable is declared, it contains undefined value
commonly known as garbage value.
• If we want we can assign some initial value to the variables
during the declaration itself. This is called initialization of the
variable.
36
Declaring and Initializing C Variable
37
Statements in C
• Statements are the primary building blocks of a program. A
program is a series of statements with some necessary
punctuation.
• A statement is a complete instruction to the computer.
• In C, statements are indicated by a semicolon at the end.
• Most of the statements in a C program are expression
statements. An expression statement is simply an expression
followed by a semicolon.
• The lines i = 0;
i = i + 1;
printf("Hello, world!n");
are all expression statements.
38
Compound Statements in C
• Compound statements (also called a block) are those that
appears as the body of another statement.
• Unlike expression statements, they do not end with a
semicolon.
• Compound statements is usually put on multiple lines, with
one statement per line and are executed together.
• Curly brackets { } are placed before and after compound
statements. For Example:
{
line_num = 0;
page_num++;
}
• Each inner statement ends with a semicolon, but the
compound statement itself does not.
39
Compound Statements in C
40
• Compound statements can also be executed within a
loop. For Example:
Programming For Problem
Solving (PFPS)
LECTURE 5
Operators and Expressions
Operators
• C language supports a rich set of built-in operators.
• An operator is a symbol that tells the compiler to
perform specific mathematical or logical operations that
are used in programs to manipulate data and variables.
• C operators can be classified into following types:
– Arithmetic Operators
– Relational Operators
– Logical Operators
– Bitwise Operators
– Assignment Operators
– Increment and Decrement Operators
– Conditional Operators
– Special Operators
2
Arithmetic Operators
• An arithmetic operator performs mathematical operations
such as addition, subtraction, multiplication, division etc. on
numerical values (constants and variables).
3
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
%
remainder after division (modulo
division)
NOTE: The % operator can only be used with integers.
Example: Arithmetic Operators
4
Relational Operators
• A relational operator checks the relationship
between two operands.
• If the relation is true, it returns 1; if the
relation is false, it returns value 0.
• Relational operators are used in decision
making and loops.
5
Relational Operators
6
Example: Relational Operators
7
Logical Operators
• An expression containing logical operator
returns either 0 or 1 depending upon whether
expression results true or false.
• Logical operators are commonly used
in decision making in C programming.
8
Logical Operators
Operator Meaning Example
&&
Logical AND. True
only if all operands
are true
If c = 5 and d = 2
then, expression
((c==5) && (d>5))
equals to 0.
||
Logical OR. True only
if either one operand
is true
If c = 5 and d = 2
then, expression
((c==5) || (d>5))
equals to 1.
!
Logical NOT. True only
if the operand is 0
If c = 5 then,
expression !(c==5)
equals to 0.
9 10
Example: Logical Operators
Bitwise Operators
• In arithmetic-logic unit (within the CPU),
mathematical operations like: addition, subtraction,
multiplication and division are done in bit-level (bit
level programming).
• To perform bit-level operations in C programming,
bitwise operators are used.
• These operators can operate upon int and char but
not on float and double.
• Bitwise operators in C language are: & (bitwise AND),
| (bitwise OR), ~ (bitwise Complement), ^ (bitwise
XOR), << (left shift) and >> (right shift).
11
Bitwise Operators
12
Truth Table of Bitwise Operators
• The truth tables for &, |, ^ and ~ are as follows:
13
Bitwise Left Shift Operator
14
Bitwise Right Shift Operator
15
Example of Bitwise Operations
• Assume variable A = 60 (00111100) and variable B = 13 (00001101),
then:
16
Assignment Operator
• An assignment operator is used for assigning a value to a
variable.
• The most common assignment operator is equal to (=).
17 18
Increment and Decrement Operators
• C programming has two operators ̶
increment (++) operator and decrement operator (--
) to change the value of an operand (constant or
variable) by 1.
• Increment ++ increases the value by 1 whereas
decrement -- decreases the value by 1.
• These two operators are unary operators, meaning
they only operate on a single operand.
19
Use of ++ and -- Operators as Prefix
and Postfix
• If you use the ++ operator as prefix like: ++var. The
value of var is incremented by 1 then, it returns the
value.
• If you use the ++ operator as postfix like: var++. The
original value of var is returned first then, var is
incremented by 1.
• The -- operator works in a similar way like
the ++ operator except it decreases the value by 1.
20
Increment and Decrement Operators
21 22
Example: Increment and Decrement Operators
23
NOTE: Here, the operators ++ and -- are used as prefixes. These two operators
can also be used as postfixes like a++ and a--.
Another Example of ++ and --
Operators as Prefix and Postfix
24
Conditional Operator
• The conditional operators in C language are known by
two more names:
– Ternary Operator
– ? : Operator
• It is actually the if condition that we use in decision
making, but using conditional operator, we turn
the if condition statement into a short and simple
operator.
• The syntax of a conditional operator is :
expression1 ? expression2: expression3
25
Explanation of Conditional Operator
• The question mark "?" in the syntax represents
the if part.
• The first expression (expression 1) generally returns
either true or false, based on which it is decided
whether (expression 2) will be executed or
(expression 3)
• If (expression 1) returns true then the expression on
the left side of " : " i.e., (expression 2) is executed.
• If (expression 1) returns false then the expression on
the right side of " : " i.e., (expression 3) is executed.
26
Conditional Operator
27 28
Other Operators In C
• Besides the operators discussed, there are a
few other important operators supported by
the C language as listed below:
– Comma operator,
– Address of operator
– sizeof() operator
29
Comma Operator
• The comma operator is a binary operator that
evaluates its first operand and discards the result, it
then evaluates the second operand and returns this
value.
• The comma operator has the lowest precedence
among the C operators
• Syntax:
res = (num1, num2);
– Value of rightmost variable will be assigned to the variable
on the LHS of the equation as the result of the expression.
– In this case, value of num2 will be assigned to variable res.
30
Example: Comma Operator
• Example:
a = 10,20,30;
b = (10,20,30);
– In the first statement, value of a will be 10,
because assignment operator (=) has more priority than
comma (,), thus 10 will be assigned to the variable a.
– In the second statement, value of b will be 30, because 10,
20, 30 are enclosed in braces, and braces has more
priority than assignment (=) operator.
– When multiple values are given with comma operator
within the braces, then right most value is considered as
result of the expression. Thus, 30 will be assigned to the
variable b.
31
Address of Operator
• The "Address of" Operator denoted by
the ampersand character (&)
• & is a unary operator, which returns the address of a
variable.
• After declaration of a pointer variable, we need to
initialize the pointer with the valid memory address
• To get the memory address of a variable Address
of (&) Operator is used
32
Example: Address of Operator
33
sizeof() Operator
• The sizeof is a unary operator and used to compute
the size of its operand.
• It returns the size of a variable.
• It can be applied to any data type – int, float, pointer
type variables, etc.
• When sizeof() is used with the data types, it simply
returns the amount of memory allocated to that
data type.
34
Example: sizeof() Operator
35
Operators Precedence and
Associativity in C
• Operator precedence dictates the order of evaluation
of operators in an expression.
• Certain operators have higher precedence than
others
• For example x = 7 + 3 * 2; here, x is assigned 13,
not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then
adds into 7.
• Associativity defines the order in which operators of
the same precedence are evaluated in an expression.
• Associativity can be either from left to right or right to
left.
36
Operator Precedence Table
37
Operators with highest precedence appear at the top and those with the
lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
Operator Precedence Table
38
Expression In C
• An expression is a combination of operators,
constants and variables.
• An expression may consist of one or more
operands, and zero or more operators to
produce a value.
• In C, every expression evaluates to a value
that can be assigned to a variable
39
Expression In C
40
Programming For Problem
Solving (PFPS)
LECTURE 6
Managing Input Output
Operations In C
Lesson-2
Introduction to I/O Operations
• One of the essential operations performed in C language
is to provide input values to the program and output the
data produced by the program to a standard output
device
• We can assign values to variable through assignment
statements such as x = 5, a = 0 ; and so on.
• Another method is to use scanf() function, which can be
used to read data from a keyboard
• For outputting results, we have used the printf() function
extensively which sends results to a terminal (output
device)
2
Introduction to I/O Operations
• There exists several functions in ‘C’ language that can
carry out input/output operations. These functions
collectively make up the Standard Input/output Library.
• Each program that uses standard input/out put
function(s) must contain the following statement at the
beginning of the C program:
# include <stdio.h >
where, stdio.h is the Standard Input Output Header file
containing all input/output library function(s).
3
Unformatted and Formatted I/O
Library Functions
• Unformatted Input/Output Functions
– The unformatted input/output functions provide the
most preliminary i/o functions that are used just to
take inputs and show outputs without any specified
format.
• Formatted Input/Output Functions
– The formatted input/output functions helps the user
to input and output in a certain format as specified
– For example, if you want to scan a string up to 50
characters and print it right justified or in a tabular
format, then you ought to go for formatted input
output
4
5 6
Unformatted I/O Functions
Single Character Input: the getchar
Function
• The getchar function is a part of the standard
C input/output library.
• It reads one character at a time from a standard input
device (typically a keyboard) till the user presses the
enter key.
• The function does not require any arguments, but a pair
of empty parentheses must follow the word getchar.
• In general, a function reference would be written as:
character_variable = getchar( );
where character_variable refers to some previously
declared character variable.
7
Single Character Input: the getchar
Function
• The getchar function can also be used to read multi-
character strings by reading one character at a time
within a multi-pass loop.
• If an End-Of-File (EOF) condition is encountered when
reading a character with the getchar(), the value of the
symbolic constant EOF will automatically be returned.
Typically, the EOF will be assigned the value -1.
8
getchar() Example
9
Other Unformatted Input Functions
10
getch() and getche() Example
11
Single Character Output: the putchar
Function
• Single characters can be displayed using the C library
function putchar complementary to the character input
function getchar.
• putchar transmits a single character to the standard
output device (the computer screen) that is represented
as a character-type variable.
• It must be expressed as an argument to the function,
enclosed in parentheses, following the word putchar.
• In general, a function reference would be written as:
putchar(character_variable);
where character_variable refers to some previously
declared character variable.
• It is defined in header file stdio.h.
12
putchar() Example
13
Other Unformatted Output Function
• putch()
– putch() is unformatted character output function that
is complementary to the character input
function getch().
– Its working and syntax is similar to that of putchar()
and is used for printing a character on a screen at the
current cursor location.
– While using getch(), the pressed character is not
echoed and is displayed by using putch() function.
– putch() is defined in header file conio.h.
– Syntax:
putch(character_variable);
14
putch() Example
15
gets() Function
• The gets() function enables the user to enter some
characters followed by the enter key.
• It keeps reading the characters until the new line
(enter) is encountered.
• All the characters entered by the user get stored in a
character array (string).
• The null character is added to the array to make it a
string.
16
gets() Function
• The gets() is similar to scanf() but also allows the user to
enter the space-separated strings (multi-word strings).
• The gets() function is defined in the <stdio.h> header file.
• Syntax for declaration:
char[] gets(char[]);
Where char[] is a previously declared character variable.
• The gets() function returns the string entered by the
user.
17
gets() Example
18
puts() Function
• This function prints the string or character array and is
complementary to the function gets()
• The puts() function is defined in the <stdio.h> header
file.
• Syntax for declaration:
int puts(char[]);
Where char[] is a previously declared character variable.
• The puts() function returns an integer value representing
the number of characters being printed on the console.
19
Example program (Involving both gets
and puts)
# include < stdio.h >
void main ( )
{
char str[80];
printf (“Type a string less than 80 characters:”);
gets(str);
printf (“The string types is:”);
puts(str);
}
20
21
Formatted I/O Functions
Formatted Input Function: scanf()
• The formatted input refers to input data that has
been arranged in a particular format.
• Input values are generally read by using the scanf
function.
• The scanf function has the general form:
scanf(“control string”, arg1, arg2, arg3 …, argn);
where control string refers to a string containing
required format specifications, and arg1, arg2, ….,
argn are arguments that represent the addresses of
individual variables.
22
Formatted Input Function: scanf()
• The control string entries are separated be space and
each entry is preceded by %.
• Address of operator (&) must be placed in front of each
of the variables used in scanf()
• The format specifiers are used in the control string for
input and output purposes.
• The format specifiers enable the compiler to understand:
– What type of data is in a variable while taking input using
the scanf() function
– What kind of values are being output using printf()
function.
23
Format Specifiers in I/O
24
Input specifications for an integer in
scanf()
• The general format for reading a integer number is:
%wd
• w is an integer number which specifies the field
width of the number that is being read.
• The data type character d indicates that the input
should be read in integer mode.
• The general format of reading an integer input using
scanf() is:
scanf(“%d”, &var);
where, var is a previously declared integer variable.
25
Input specifications for an integer in
scanf()
• Example:
scanf(“%3d %4d”, &sum1, &sum2);
– If the input values are 175 and 1342, then value 175 is
assigned to sum1 and 1342 to sum 2.
– Suppose the input data was follows 1342 and 175.
The number 134 will be assigned to sum1 and sum2
has the value 2 because of %3d the number 1342 will
be cut to 134 and the remaining part is assigned to
second variable sum2.
– If floating point numbers are assigned then the
decimal or fractional part is skipped by the computer.
26
Input specifications for a real number
in scanf()
• Real numbers are specified using %f specifier.
• The general format for reading a real number input
using scanf() is:
scanf(“%f”, &var);
where, var is a previously declared float variable.
• Example:
– scanf(“%f %f % f”, &a, &b, &c);
– With the input data 321.76, 4.321 and 678.5, the
values 321.76 is assigned to a , 4.321 is assigned to b
and 678.5 to c.
27
Input specifications for a character in
scanf()
• Single character or strings can be input by using the
character specifiers.
• The general format for reading a single character or
character array (string) is:
%wc or %ws
where c and s represent character and string
respectively and w represents the field width of the
input being read.
28
Input specifications for a character in
scanf()
• The general format of specifying a single character
input in scanf() is:
scanf(“%c", &var);
where, var is a previously declared character
variable.
• The general format of specifying a character array
(string) input in scanf() is:
scanf(“%s", str);
where, str is a previously declared character array.
29
Example: Input individual characters
using scanf()
• The address operator (&) is not required to be specified
while we input strings because string name itself
represents the starting address of the character array.
• If we read a string by using "%s" format specifier, string
will be terminated when the first white space is found.
• Consider the following statement:
scanf("%c %c %c", &x, &y, &z);
If the input is "a b c", then 'a' will be assigned to
variable x, SPACE will be assigned to
variable y and 'b' will be assigned to variable z.
30
Example: Read string with spaces using
scanf() function
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
scanf("%s", name);
printf("Name is: %sn", name);
return 0;
}
Output -1 (Enter name without space)
Enter name: Alex
Name is: Alex
Output -2 (Enter name with space)
Enter name: Alex Thomas
Name is: Alex
31
Formatted Output Function: printf()
• In C programming language, "printf" is the name of
one of the main C output functions, and stands for
"print formatted".
• printf() is complementary to the formatted input
function scanf()
• printf() function is used to print the character, string,
float, integer, octal and hexadecimal values onto the
output screen.
32
Formatted Output Function: printf()
• The printf function has the general form:
printf(“control string”, arg1, arg2, arg3 …, argn);
where control string refers to the format
specifications that define the output format,
and arg1, arg2, …., argn are the variables containing
the values that will be printed on the screen.
• The control string may also contain escape sequence
characters such as n, t, b, etc. for desired output
formatting.
33
Output of Integer Numbers
• The general format for printing an integer is:
%wd
where, w is the minimum field width for the output to be
printed.
• If w is not specified, the output will consume whatever
width is required for the output data.
• d indicates that the output should be read in integer
mode.
• If the output width is greater than ‘w’, the printf()
overrides the width specified by the user
34
Output of Integer Numbers
• By default, the number is output as right-justified
and leading blanks will appear as necessary
(depending on w).
• It is possible to make the output left justified be
placing a minus sign (-) after the % symbol in the
control string
• It is also possible to pad the output with leading
zeros instead of spaces by placing a ‘0’ before ‘w’
(%0wd)
35
Output of Real Numbers
• The general format for printing a real number is:
%w.pf
where,
– w is the minimum number of positions that are to be
used for displaying the output
– p is the number of digits to be displayed after the
decimal point (precision)
– The default precision is 6 decimal places.
• Negative numbers are printed with the minus sign be
placing a minus symbol before the corresponding
variable name in the argument list
36
Output of Real Numbers
• A real number in exponential notation is displayed
with the specification: %w.pe
• Padding with leading zeros and printing with left
justification by introducing ‘0’ or ‘-’ before w in the
format specification.
37
Printing of a Single Character
• A single character can be displayed using the
following format: %wc
• The character will be displayed right justified in the
field of ‘w’ columns
• Default value of w is 1.
• The display is made left justified by placing a minus
sign before the integer w.
38
Printing of Strings
• The format specifications for outputting strings:
%w.ps
where.
w: field width for displaying
p: it specifies only the first p characters of the string
that are to be displayed
• Display is right justified
39 40
EXAMPLE:
FORMATTED
OUTPUT
Programming For Problem
Solving (PFPS)
LECTURE 7
Decision Control/Selection
Statements Using If
Control Statements in C
• In C, programs are executed sequentially in the order
of which they appear.
• This condition does not hold true always.
Sometimes a situation may arise where we need
to execute a certain part of the program.
• Also it may happen that we may want to execute the
same part more than once.
• Control statements enable us to specify the order
in which the various
• instructions in the program are to be executed.
• They define how the control is transferred to other
parts of the program.
2
Classification of Control Statements
3
Selection Statements
• The selection statements are also known as Branching or
Decision Control Statements.
• Sometime we come across situations where we have
to make a decision.
• Decision making structures require the programmer to
specify one or more conditions to be evaluated or tested
by the program, along
• If the condition is determined to be true, a statement or
a set of statements is to be executed
• Otherwise if the condition is found to be false, the other
statement or a set of statements to be executed
4
if Statement
• The if statement allows us to put some decision-making
into our programs.
• The general form of the if statement is:
5
if Statement
• Syntax of if statement:
if (condition )
{
Statement 1;
…………..
Statement n;
}
//Rest of the code
• If the condition is true(nonzero), the statement will
be executed. If the condition is false(0), the statement
will not be executed.
6
Example of if Statement
7
if-else Statement
• The if statement is used to execute only one action.
If there are two statements to be executed
alternatively, then if-else statement is used.
• The if-else statement is a two way branching
statement as another group of statements is
executed if the expression evaluates to false.
• The group of statements after the if is called an ‘if
block’.
• Similarly, the statements after the else form the ‘else
block’.
8
if-else Statement
• The general syntax of simple if - else statement is:
• Where, statement may be a single statement or a
block.
• If we desire that multiple statements be executed on
a branch, we must block them inside of a pair of
opening and closing curly braces to make them a
single compound statement.
9 10
if-else Statement
Example of if-else Statement
11
Example of if-else Statement
12
Nested if-else statement
• An entire if-else construct can be written within either
the body of the if statement or the body of an else
statement.
• This is called ‘nesting’ of ifs. This is shown in the
structure given in the figure for syntax of nested if-else
construct.
• From the syntax it is clear that:
– If test condition – 1 is false, statemet3 is executed
otherwise test condition-2 is tested.
– If test condition – 2 is true, statemet1 is executed
otherwise statemet2 is executed .
13
Syntax of Nested if-else construct
14
Flowchart of Nested if-else construct
15
Example of Nested if-else Statement
16
Write a program to check whether the given number is even or odd using nested if-else
statement.
Example of Nested if-else Statement
17
The if-else-if/else-if Ladder
• When we are faced with a situation in which a
program must select from many processing
alternatives based on the value of a single variable, a
multi-way decision statement is required
• In C if-else-if ladder helps user decide from among
multiple options.
• The C if statements are executed from the top down.
• As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed,
and the rest of the C else-if ladder is bypassed.
• If none of the conditions is true, then the final else
statement will be executed.
18
General form of the if-else-if Ladder
19
Flowchart of if-else-if Ladder
20
21
Example of if-else-if Ladder
22
Write a program to check to check for the relation between two numbers using if-else-if
ladder.
Programming For Problem
Solving (PFPS)
LECTURE 8
Decision Control/Selection
Statements Using Switch Case
Statement
The Switch Statement
• The switch statement is a multi-way branch statement
• It tests the value of a given variable/expression against a
list of case values
• When a match is found, a block of statements associated
with that case is executed
• When we need to choose one among a number of
alternatives, a switch is used
• The switch keyword is followed by an integer or an
expression that evaluates to an integer
2
The Switch Statement
• Case keyword is followed by an integer or character
constant. We can also use char values in case and
switch
• Case labels always end with a colon (:). Each of these
cases is associated with a block.
• A block is nothing but multiple statements which are
grouped for a particular case.
3
General Form of Switch-Case Statement
4
5
The Switch Statement
• When the switch is executed, the expression is evaluated
once and compared with the values of each case label
• The value of the expression is compared against the each
of the case values value1, value2, ..., valuen.
• If a case is found whose value matches with the value of
the expression, then the corresponding block of
statements is executed
• The break statement at the end of each block signals the
end of a particular case and causes exit from the switch
statement
6
The Switch Statement
• If we do not use break, all statements after the matching
label are executed.
• Default is an optional case. If there is no match, the
default statements are executed.
• When present, the default case will be executed if the
value of expression does not match with any of the case
values.
• If not present, no statement is executed if all the
matches fail and the control goes to the statement
directly after the switch-case
7
Few Important points regarding
Switch- Case
• Case doesn’t always need to have order 1, 2, 3 and
so on. They can have any integer value after case
keyword.
• Also, case doesn’t need to be in an ascending order
always, you can specify them in any order as per the
need of the program.
• You can also use characters in switch case.
• The expression provided in the switch should result
in a constant value otherwise it would not be valid.
8
Few Important points regarding
Switch- Case
• Nesting of switch statements are allowed, which
means you can have switch statements inside
another switch. However nested switch statements
should be avoided as it makes program more
complex
• Duplicate case values are not allowed.
9 10
Example of Program Using Switch-Case Statement
11
Lecture-9
Loop Control Statements
• A Loop executes the sequence of statements many
times until the stated condition becomes false.
• A loop consists of two parts, a body of a loop and a
control statement.
• The control statement is a combination of some
conditions that direct the body of the loop to
execute until the specified condition becomes false.
• The purpose of the loop is to repeat the same code a
number of times.
Types of Loops
• Depending upon the position of a control statement
in a program, a loop is classified into two types:
1. Entry controlled loop
2. Exit controlled loop
• In an entry controlled loop, a condition is checked
before executing the body of a loop. It is also called
as a pre-checking loop.
• In an exit controlled loop, a condition is checked
after executing the body of a loop. It is also called as
a post-checking loop.
The control conditions must be well
defined and specified otherwise the
loop will execute an infinite number
of times. The loop that does not
stop executing and processes the
statements number of times is
called as an infinite loop. An infinite
loop is also called as an "Endless
loop." Following are some
characteristics of an infinite loop:
1. No termination condition is
specified.
2. The specified conditions never
meet.
The specified condition determines
whether to execute the loop body
or not
There are three types of loop constructs:
1. The while loop
2. The do-while loop
3. The for loop
While Loop
A while loop is the most
straightforward looping
structure. The basic format of
while loop is as follows:
while (condition)
{
statements;
}
• While loop is an entry-controlled loop.
• In this loop, a condition is evaluated before processing a
body of the loop.
• If a condition is true then and only then the body of a loop
is executed. After the body of a loop is executed then
control again goes back at the beginning, and the condition
is checked if it is true, the same process is executed until
the condition becomes false. Once the condition becomes
false, the control goes out of the loop.
• After exiting the loop, the control goes to the statements
which are immediately after the loop. The body of a loop
can contain more than one statement. If it contains only
one statement, then the curly braces are not compulsory.
• If the condition is not true, then the body of a loop will not
be executed, not even once.
Wright a program to print series of numbers from 1 to 10 using a while
loop.
#include<stdio.h>
#include<conio.h>
int main()
{ int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%dn",num);
num++; //incrementing operation
}
return 0;
}
Do-While loop
A do-while loop is similar to
the while loop except that
the condition is always
executed after the body of
a loop. It is also called an
exit-controlled loop.
The basic format of while
loop is as follows:
do {
Statements
} while (expression);
As we saw in a while loop, the body is
executed if and only if the condition is
true. In some cases, we have to execute a
body of the loop at least once even if the
condition is false. This type of operation
can be achieved by using a do-while loop.
• In the do-while loop, the body of a loop is always
executed at least once. After the body is executed, then
it checks the condition. If the condition is true, then it
will again execute the body of a loop otherwise control
is transferred out of the loop.
• Similar to the while loop, once the control goes out of
the loop the statements which are immediately after
the loop is executed.
• The main difference between the while and do-while
loop is that in while loop the while is written at the
beginning. In do-while loop, the while condition is
written at the end and terminates with a semi-colon (;)
Wright a program to print series of numbers from 1 to 10 using a
do while loop
#include<stdio.h>
#include<conio.h>
int main()
{
int num = 1; // Initialize starting number
do{ //Start do while loop
printf("%dn", num);
++num; //increment the number by 1
}while (num <= 10);
return 0;
}
Difference between do while and while loop: do…while loop guaranteed to
execute at least one time whereas while loop does not.
For loop
A for loop is a more efficient
loop structure in 'C'
programming. It has three
sections:
initialization, condition,
increment or decrement.
The general structure of for
loop is as follows:
for (initial value; condition;
increment or decrement )
{
statements;
}
The initial value of the for loop is performed
only once.
The condition is a Boolean expression that tests
and compares the counter to a fixed value
after each iteration, stopping the for loop
when false is returned.
The increment/decrement increases (or
decreases) the counter by 1.
Wright a program to print a series of numbers from 1 to
10 using for loop
#include<stdio.h>
#include<stdio.h>
int main()
{
int num = 1; //Initialize starting number
for (num = 1; num <= 10; ++num)
{
printf("%dn", num);
}
return 0;
}
• In C, the for loop can have multiple expressions
separated by commas in each part.
For example:
for (x = 0, y = num; x < y; i++, y--)
{
statements;
}
• Also, we can skip the initial value expression, condition
and/or increment by adding a semicolon.
For example:
int i=0;
int max = 10;
for (; i < max; i++)
{
printf("%dn", i);
}
Nesting of loops
• loops can also be nested where there is an outer
loop and an inner loop. For each iteration of the
outer loop, the inner loop repeats its entire cycle.
• The syntax for a nested for loop statement in C is as
follows −
for ( init; condition; increment )
{
for ( init; condition; increment )
{ statement(s);
} statement(s);
}
The syntax for a nested
while loop:
while(condition)
{
while(condition)
{ statement(s);
}
statement(s);
}
The syntax for a nested do
while loop:
do
{
statement(s);
do
{
statement(s);
} while( condition );
}while( condition );
Wright a program for Multiplication table using nested for loop
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++) // outer loop
{
for(j = 0; j <= max; j++) // inner
loop
` {
printf("%d x %d = %dn", i, j,
i*j);
}
printf("n");
}
}
Output:
1 x 0 = 0
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
2 x 0 = 0
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
Exercises
1. Write a program to print all natural numbers from 1 to n using loop.
2. Write a C program to print all alphabets from a to z. - using while loop
3. Write a C program to print all odd number between 1 to 100.
4. Write a C program to count number of digits in a number.
5. Write a C program to calculate sum of digits of a number.
6. Write a C program to find power of a number using for loop.
7. Write a C program to check whether a number is Prime number or not.
8. Write a C program to check whether a number is Armstrong number or
not.
9. Write a C program to print Pascal triangle upto n rows.
10. Write programs for the following patterns:
1
2 2
3 3 3
4 4 4 4
5 5 5 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
*
**
***
****
*****
Lecture-10
Programming on loop control statements
1. This program checks whether a given number is a palindrome or not
#include<stdio.h>
#include<conio.h>
void main()
{ int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or notn");
scanf("%d",&n);
temp = n;
while( temp != 0 )
{ reverse = reverse * 10; reverse = reverse +temp%10;
temp = temp/10; }
if ( n == reverse )
printf("%d is a palindrome number.n", n);
else
printf("%d is not a palindrome number.n", n);
getch();
}
Output:
Enter a number to check if it is a palindrome
or not
12321
12321 is a palindrome
2. Program to count the no of digits in a number
#include<stdio.h>
#include<conio.h>
void main()
{
int n, count=0;
clrscr();
printf("Enter an integer: ");
scanf("%d", &n);
do
{ n/=10; // n=n/10
count++;
} while(n!=0);
printf("Number of digits: %d“, count);
getch();
}
Output:
Enter an integer: 34523
Number of digits: 5
3. Program to print the sum of 1st N natural numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,sum=0;
clrscr();
printf("Enter the limit: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
sum = sum +i;
}
printf("Sum of N natural numbers is: %d",sum);
getch();
}
Output
Enter the limit: 5
Sum of N natural numbers is 15
C program to print right triangle star pattern series
#include <stdio.h>
#include <conio.h>
int main()
{ int i, j, n;
clrscr();
printf("Enter value of n: ");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf("*");
}
printf("n");
} return 0;
}
Output:
Enter the value of n: 5
*
**
***
****
*****
Jump Statements
Loops perform a set of repetitive task until text expression becomes false but it is
sometimes desirable to skip some statement/s inside loop or terminate the loop
immediately without checking the test expression. In such cases, jump statements are
used.
There are three jump statements.
1. Break statement
2. Continue statement
3. goto statement
1. break statement
The break statement provides an early exit from loops like for, while, and do..while. A
break causes the innermost enclosing loop or switch to be exited immediately. When break
is encountered inside any loop, control automatically passes to the first statement after the
loop.
Syntax:
break;
Wright a program to understand break statement
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
for(n=1;n<=5;n++)
{
if(n==3)
{ printf(“Breakn”);
break;}
printf(“Number=%dn”,n);
}
printf(“Out of loopn”);
getch();
}
Output:
Number=1
Number=2
Break
Out of loop
2. Continue statement
It is sometimes desirable to skip some statements inside the loop. In
such cases, continue statement is used
The continue statement is related to break, but less often used; it
causes the next iteration of the enclosing for, while, or do loop to
begin. In the while and do, this means that the test part is executed
immediately; in the for, control passes to the increment step. The
continue statement applies only to loops, not to switch.
Syntax:
continue;
Wright a program to understand continue statement
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
for(n=1;n<=5;n++)
{
if(n==3)
{ printf(“Continue Statementn”);
continue;}
printf(“Number=%dn”,n);
}
printf(“Out of loopn”);
getch();
}
Output:
Number=1
Number=2
Continue Statement
Number=4
Number=5
3. goto statement
In C programming, goto statement is used for altering the normal sequence of
program execution by transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto
statement, the control of the program will jump to the label: and executes the code
below it
C Program Which Print 1 To 10 Number Using goto statement.
#include<stdio.h>
#include<conio.h>
void main()
{ int i=1;
clrscr();
count: //This is Label
printf("%dn",i);
i++;
if(i<=10)
{
goto count; //This jumps to label "count:"
}
getch();
}
Output:
1
2
3
4
5
6
7
8
9
10
Reasons to avoid goto statement:
• Though, using goto statement give power to jump to any part of
program, using goto statement makes the logic of the program
complex and tangled.
• In modern programming, goto statement is considered a harmful
construct and a bad programming practice.
• The goto statement can be replaced in most of C program with the
use of break and continue statements.
• In fact, any program in C programming can be perfectly written
without the use of goto statement.
• All programmer should try to avoid goto statement as possible as they
can.
Exercises
1. WAP to input the 3 sides of a triangle & print its corresponding type.
2. WAP to input the name of salesman & total sales made by him. Calculate & print the commission earned.
TOTAL SALES RATE OF COMMISSION
1-1000 3 %
1001-4000 8 %
6001-6000 12 %
6001 and above 15 %
3. WAP to print the following series
i. S = 1 + 1/2 + 1/3 ……..1/10
ii. P= (1*2) + (2 *3) + (3* 4)+…….(8 *9) +(9 *10)
iii. S = x + x2 + x3 + x4......+ x9 + x10
iv. S = 1/1! + 1/2! + 1/3! ……………+1/n!
v. S = 1 + x + x2/2 + x3/3…….+xn/n
4. Write a C program to print Fibonacci series up to n terms.
5. Write a C program to find frequency of each digit in a given integer.
Lecture-11
Function
Monolithic Vs Modular Programming:
1. Monolithic Programming indicates the program which contains a single function
for the large program.
2. Modular programming help the programmer to divide the whole program into
different modules and each module is separately developed and tested. Then the
linker will link all these modules to form the complete program.
3. On the other hand monolithic programming will not divide the program and it is a
single thread of execution. When the program size increases it leads inconvenience
and difficult to maintain.
Disadvantages of monolithic programming: 1. Difficult to check error on large
programs. 2. Difficult to maintain. 3. Code can be specific to a particular problem. i.e.
it can not be reused.
Advantage of modular programming: 1. Modular program are easier to code and
debug. 2. Reduces the programming size. 3. Code can be reused in other programs. 4.
Problem can be isolated to specific module so easier to find the error and correct it.
User Define Functions Vs Standard Function
User Define Function:
A function that is declared, called and defined by the user is called user
define function. Every user define function has three parts as:
1. Prototype or Declaration
2. Calling
3. Definition
Standard Function:
The C standard library is a standardized collection of header files and
library routines used to implement common operations, such as
input/output and character string handling. Unlike other languages
(such as COBOL, FORTRAN, and PL/I) C does not include built in
keywords for these tasks, so nearly all C programs rely on the standard
library to function.
FUNCTION
A function is a group of statements that together performs a task. Every C
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
Function Declaration OR Function Prototype
1. It is also known as function prototype .
2. It informs the computer about the three things
a) Name of the function
b) Number and type of arguments received by the function.
c) Type of value return by the function
Syntax :
return_type function_name (type1 arg1 , type2 arg2,…);
OR
return_type function_name (type1, type2,…);
3. Calling function need information about called function .If called function is place
before calling function then the declaration is not needed.
Function Definition:
1. It consists of code description and code of a function .
It consists of two parts
a) Function header
b) Function body
Function definition tells what are the I/O function and what is going to do.
Syntax:
return_type function_name (type1 arg1 , type2 arg2)
{
local variable; statements ; return (expression);
}
2. Function definition can be placed any where in the program but
generally placed after the main function .
3. Local variable declared inside the function is local to that function. It
cannot be used anywhere in the program and its existence is only
within the function.
4. Function definition cannot be nested.
5. Return type denote the type of value that function will return and
return type is optional if omitted it is assumed to be integer by default.
Wright a program to add two numbers using function
#include <stdio.h>
#include <conio.h>
int sum(int , int); //function declaration or prototype
int main()
{ int num1,num2,total; //variable declaration
clrscr();
printf("Enter the two number ");
scanf("%d %d",&num1,&num2); //getting two number as input from user
total=sum(num1,num2); //calling the function //The total value (returned by the function) is stored in total variable.
printf("The sum of these numbers :%d", total); //display the total value
getch();
return 0;
}
int sum(int a, int b) //defining function based in declaration
{ int result=a+b; //find sum of two numbers //and result of sum stored in result variable
return result; //returning result
}
Output
Enter the two numbers 45
75
The sum of these numbers :120
ACTUAL ARGUMENTS AND FORMAL ARGUMENTS
Actual Arguments
1. Arguments which are mentioned in the function call are known as actual
arguments.
2. These are the values which are actually sent to the function.
It can be written as constant, variable or an expression which return a value .
Example: funct (6,9) , funct ( a,b )
Formal Arguments
1. Arguments which are mentioned in function definition are called dummy or
formal arguments.
2. These arguments are used to just hold the value that are sent by calling function.
3. Formal arguments are like other local variables of the function which are created
when function call starts and destroyed when end function.
Example: return_type func(int x,int y)
Write a program to find GCD (Greatest Common Divisor) of two numbers
#include<stdio.h>
int GCD(int,int);
void main()
{
int a,b,gcd;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
gcd=GCD(a,b); // a,b are actual arguments
printf(“GCD of %d and %d is %d”,a,b,gcd);
}
int GCD(int x, int y) // x and y are formal arguments
{
if(y==0) return x;
else
return GCD(y,x%y);
}
Output:
Enter two numbers 21
35
GCD of 21 and 35 is 7
PARAMETER PASSING TECHNIQUES
In C programming parameters can be passed in two ways:
1. call by value
2. call by reference
Call by value:
Here values of actual arguments are passed to the formal arguments
and operation is done in the formal arguments.
Since formal argument is photo copy of actual argument, any changes
made with the formal arguments do not affect the actual argument.
Changes made to the formal argument are local to the block of called
function, so when control comes back to calling function changes
made, vanish.
Program to explain a function with call by value.
#include<stdio.h>
void change(int num)
{
printf("Before adding value inside function num=%d n",num);
num=num+100;
printf("After adding value inside function num=%d n", num);
}
int main() {
int x=100;
printf("Before function call x=%d n", x);
change(x); //passing value in function
printf("After function call x=%d n", x);
return 0;
}
Output:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Note: Value of actual argument is not changed
i.e. 100
Call by reference
• In call by reference, the address of the variable is passed into the
function call as the actual parameter. So formal arguments are the
pointers to the actual arguments.
• The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is
passed.
• In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function
are performed on the value stored at the address of the actual
parameters, and the modified value gets stored at the same address.
i.e. changes made to the formal argument reflects the actual
argument.
Program to understand the concept of call by reference.
#include<stdio.h>
void change(int *num)
{
printf("Before adding value inside function num=%d n",*num);
(*num) += 100;
printf("After adding value inside function num=%d n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d n", x);
change(&x); //passing reference in function
printf("After function call x=%d n", x);
return 0;
}
Output:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Lecture-12
FUNCTION CATAGORIES
There are four main categories of the functions these are
as follows:
1. Function with no arguments and no return values.
2. Function with no arguments and a return value.
3. Function with arguments and no return values.
4. Function with arguments and return values.
Function with no arguments and no return values:
syntax:
void funct(void);
main( )
{
funct( );
}
void funct( void )
{
}
There is no communication between calling and called
function. Functions are executed independently, they read
data & print result in same block.
Wright a program to estimate the area of square using
the function with no arguments and no return values
#include <stdio.h>
#include <conio.h>
void area(void); //function prototype
int main()
{
area(); //function call
getch();
return 0;
}
void area() // function definition
{
int square_area, square_side;
printf("Enter the side of square :");
scanf("%d",&square_side);
square_area = square_side * square_side;
printf("Area of Square = %d",square_area);
}
Function with no arguments and a return value
This type of functions has no arguments but a return value
syntax:
return_type funct(void);
main( )
{
int x;
x=funct( );
printf(“%d=x”);
}
return_type funct( void )
{
return();
}
Here called function is independent, it read the value from the
keyboard, initialize and return a value .Both calling and called function
are partly communicated with each other.
Wright a program to estimate the area of square using
the function with no arguments and return values
#include <stdio.h>
#include <conio.h>
int area(); //function prototype with return type int
int main()
{ int square_area;
clrscr();
square_area = area(); //function call
printf("Area of Square = %d",square_area);
getch(); return 0;
}
int area() // function definition
{
int square_area,square_side;
printf("Enter the side of square :");
scanf("%d",&square_side);
square_area = square_side * square_side;
getch();
return square_area;
}
Function with arguments and no return values
syntax:
void funct(type);
main( )
{
funct(type);
}
void funct(type)
{
}
Here functions have arguments so, calling function send
data to called function but called function does no return
value. such functions are partly dependent on calling
function and result obtained is utilized by called function .
Wright a program to estimate the area of square using
the function with arguments and no return values
#include <stdio.h>
#include <conio.h>
void area( int square_side); //function prototype
int main()
{ int square_side;
clrscr();
printf("Enter the side of square :");
scanf("%d",&square_side);
area(square_side); //function call
getch(); return 0;
}
void area(int square_side)
{
int square_area;
square_area = square_side * square_side;
printf("Area of Square = %d",square_area);
}
Function with arguments and return value
syntax:
return_type funct(type);
main( )
{
funct(type);
}
return_type funct(type)
{
}
Here calling function passes arguments to the called
function and called function returns value to calling
function. Both the calling function and called function will
receive data from each other. It’s like a dual
communication.
Wright a program to estimate the area of square using
the function with arguments and return values
#include <stdio.h>
#include <conio.h>
int area(int square_side); //function prototype with return type int
int main()
{ int square_area,square_side;
clrscr();
printf("Enter the side of square :");
scanf("%d",&square_side);
square_area = area(square_side); //function call
printf("Area of Square = %d",square_area);
getch();
return 0;
}
int area(int square_side)
{
int square_area;
square_area = square_side * square_side;
return square_area;
}
Lecture-13
Recursion
RECURSION
• Recursion is a process in which a problem is defined in terms of
itself.
• Functions that call themselves are known as recursive functions, i.e.
a statement within the body of a function calls the same function.
Example:
void main()
{
……………………… /* Some statements*/ fun1();
……………………… /* Some statements */
} void fun1()
{
……………………… /* Some statements */
fun1(); /*RECURSIVE CALL*/
………………………
Way to write a Recursive Function:
Before writing a recursive function for a problem its
necessary to define the solution of the problem in terms
of a similar type of a smaller problem.
Two main steps in writing recursive function are as
follows:
(i). Identify the Non-Recursive part(base case) of
the problem and its solution(Part of the problem whose
solution can be achieved without recursion).
(ii). Identify the Recursive part(general case) of the
problem(Part of the problem where recursive call will be
made).
Identification of Non-Recursive part of the problem is
mandatory because without it the function will keep on
calling itself resulting in infinite recursion.
control flows in successive recursive calls
Flow of control in successive recursive calls can be demonstrated in following example:
Consider the following program which uses recursive function to compute the factorial
of a number.
void main()
{ int n,f;
printf(“Enter a number”);
scanf(“%d”,&n);
f=fact(a);
printf(“Factorial of %d is %d”,n,f);
}
int fact(int m)
{ int a;
if (m==1)
return (1);
else
a=m*fact(m-1);
return (a);
}
Execution steps for n=4
fact(4) returns (4*fact(3) )
fact(3) returns (3*fact(2) )
fact(2) returns (2*fact(1) )
fact(1) returns (1)
So for n=4, the factorial of 4 is
evaluated to 4*3*2*1=24.
For n=3, the control flow of the program is as
follows:
Winding and Unwinding phase
All recursive functions work in two phases- winding phase and
unwinding phase.
Winding phase starts when the recursive function is called
for the first time, and ends when the termination condition
becomes true in a call i.e. no more recursive call is required. In
this phase, a function calls itself and no return statements are
executed.
After winding phase unwinding phase starts and all the
recursive function calls start returning in reverse order till the first
instance of function returns. In this phase the control returns
through each instance of the function.
Implementation of Recursion
All function calls(Whether Recursive or Non-Recursive) are
implemented through run time stack. Stack is a Last In First
Out(LIFO) data structure. This means that the last item to
be stored on the stack(PUSH Operation) is the first one
which will be deleted(POP Operation) from the stack. Stack
stores Activation Record(AR) of function during run time.
Here we will take the example of function fact() in the
previous recursive program to find factorial of a number.
Suppose fact() is called from main() with argument 3 i.e.
fact(3);
The run time stack changes during the evaluation of
factorial of 3 is shown in the next slide.
Stack changes during the evaluation of factorial
of 3
The following steps will reveal how the above stack contents were
expressed:
• First main() is called, so PUSH AR of main() into the stack.
• Then main() calls fact(3) so PUSH AR of fact(3).
• Now fact(3) calls fact(2) so PUSH AR of fact(2) into the stack.
• Likewise PUSH AR of fact(1).
• After the above when fact(1) is completed, POP AR of fact(1),
Similarly after completion of a specific function POP its
corresponding AR.
• So when main() is completed POP AR of main(). Now stack is empty.
• In the winding phase the stack content increases as new Activation
Records(AR) are created and pushed into the stack for each
invocation of the function.
• In the unwinding phase the Activation Records are popped from
the stack in LIFO order till the original call returns.
RECURSION VERSES ITERATION
• Every repetitive problem can be implemented recursively or
iteratively.
• Recursion should be used when the problem is recursive in nature.
Iteration should be used when the problem is not inherently
recursive.
• Recursive solutions incur more execution overhead than their
iterative counterparts, but its advantage is that recursive code is
very simple.
• Recursive version of a problem is slower than iterative version since
it requires PUSH and POP operations.
• In both recursion and iteration, the same block of code is executed
repeatedly, but in recursion repetition occurs when a function calls
itself and in iteration repetition occurs when the block of code is
finished or a continue statement is encountered.
• For complex problems iterative algorithms are difficult to
implement but it is easier to solve recursively. Recursion can be
removed by using iterative version.
Tail Recursion
A recursive call is said to be tail recursive if the corresponding
recursive call is the last statement to be executed inside the
function.
Example:
void show(int a)
{
if(a==1)
return;
printf(“%d”,a);
show(a-1);
}
In the above example since the recursive call is the last
statement in the function so the above recursive call is Tail
recursive call.
In non void functions(return type of the function is other than void) , if the recursive call
appears in return statement and the call is not a part of an expression then the call is said
to be Tail recursive, otherwise Non Tail recursive.
Now look at the following example:
int hcf(int p, int q)
{
if(q==0)
return p;
else
return(hcf(q,p%q)); /*Tail recursive call*/
}
int factorial(int a)
{
if(a==0) return 1; else
return(a*factorial(a-1)); /*Not a Tail recursive call*/
}
In the above example in hcf() the recursive call is not a part of expression (i.e. the call is
the expression in the return statement) in the call so the recursive call is Tail recursive. But
in factorial() the recursive call is part of expression in the return statement(a*recursive
call) , so the recursive call in factorial() is not a Tail recursive call.
Write a program using recursion to find the
summation of numbers from 1 to n.
#include<stdio.h>
int sum(int);
void main()
{ int n,s;
printf(“Enter a number”);
scanf(“%d”,&n);
s=sum(n);
printf(“Sum of numbers from 1 to %d is %d”,n,s);
}
int sum(int m)
{ int r;
if(m==1)
return (1);
else
r=m+sum(m-1);/*Recursive Call*/
return r; }
Output:
Enter a number 5
15
Write a program to find GCD (Greatest
Common Divisor) of two numbers.
#include<stdio.h>
int GCD(int,int);
void main()
{ int a,b,gcd;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
gcd=GCD(a,b);
printf(“GCD of %d and %d is %d”,a,b,gcd);
}
int GCD(int x, int y)
{
if(y==0) return x;
else
return GCD(y,x%y);
}
Output:
Enter two numbers 21
35
GCD of 21 and 35 is 7
Exercises
1. What do you mean by function?
2. What is the difference between actual arguments and formal arguments?
3. What do you mean by call by value and call by address?
4. How many types of functions are available in C?
5. What is the use of recursion in a program, Explain?
6. How to write a recursive function, Explain with example?
7. What is the difference between iteration and recursion?
8. Write a function to return larger number between two numbers:
9. Write a program using function to find factorial of a number.
10. Write a function power(n, m), to calculate the value of n raised to m.
11. Write a function that receives marks obtained by a student in 3 subjects and
returns the average and percentage of these marks. Call this function from
main() and print the result in main().
12. Write a function to find GCD and LCM of two numbers.
13. Write a program using recursive function to find remainder when a positive
integer m is divided by a positive integer n.
14. Write a program using recursive function to reverse number.
15. Write a recursive function to count all the prime numbers between number
p and q(both inclusive).
Lecture-14
ARRAYS
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an
array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element.
One Dimensional Array
Declaration
To declare an array in C, a programmer specifies the type of the
elements and the number of elements required by an array as follows:
data_type array_name[size];
data_type represents the type of elements present in the array.
array_name represents the name of the array.
Size represents the number of elements that can be stored in the array.
Example:
int age[100];
float sal[15];
char grade[20];
Initialization:
We can explicitly initialize arrays at the time of declaration.
Syntax:
data_type array_name[size]={value1, value2,……..valueN};
Value1, value2, valueN are the constant values known as initializers,
which are assigned to the array elements one after another.
Example:
int marks[5]={10,2,0,23,4};
The values of the array elements after this initialization are:
marks[0]=10, marks[1]=2, marks[2]=0, marks[3]=23, marks[4]=4
1. In 1-D arrays it is optional to specify the size of the array. If size is omitted during
initialization then the compiler assumes the size of array equal to the number of
initializers.
Example:
int marks[]={10,2,0,23,4};
Here the size of array marks is initialized to 5.
2. We can’t copy the elements of one array to another array by simply assigning it.
Example:
int a[5]={9,8,7,6,5};
int b[5];
b=a; //not valid
we have to copy all the elements by using for loop.
for(a=i; i<5; i++)
b[i]=a[i];
LESSON__1-15 C-PROGRAMMING.p algorithm df
LESSON__1-15 C-PROGRAMMING.p algorithm df
LESSON__1-15 C-PROGRAMMING.p algorithm df
LESSON__1-15 C-PROGRAMMING.p algorithm df
LESSON__1-15 C-PROGRAMMING.p algorithm df
LESSON__1-15 C-PROGRAMMING.p algorithm df
LESSON__1-15 C-PROGRAMMING.p algorithm df

More Related Content

Similar to LESSON__1-15 C-PROGRAMMING.p algorithm df

COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxCOMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxSherinRappai
 
Algorithmic problem sloving
Algorithmic problem slovingAlgorithmic problem sloving
Algorithmic problem slovingMani Kandan
 
Logic Formulation 1
Logic Formulation 1Logic Formulation 1
Logic Formulation 1deathful
 
Python-unit -I.pptx
Python-unit -I.pptxPython-unit -I.pptx
Python-unit -I.pptxcrAmth
 
PPL_Unit01 for the insem study first year.pptx
PPL_Unit01 for the insem study first year.pptxPPL_Unit01 for the insem study first year.pptx
PPL_Unit01 for the insem study first year.pptxrockstarr066gj
 
Introduction to computer programming
Introduction to computer programming Introduction to computer programming
Introduction to computer programming VanessaBuensalida
 
C Course material
C Course materialC Course material
C Course materialFareed Khan
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfMMRF2
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)nharsh2308
 
C program execution and algorithm
C program execution and algorithm C program execution and algorithm
C program execution and algorithm Kunal Pandhram
 
Computer language.ppsx
Computer language.ppsxComputer language.ppsx
Computer language.ppsxSneha Suman
 
Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & LanguagesGaditek
 

Similar to LESSON__1-15 C-PROGRAMMING.p algorithm df (20)

COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxCOMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
 
Algorithmic problem sloving
Algorithmic problem slovingAlgorithmic problem sloving
Algorithmic problem sloving
 
Logic Formulation 1
Logic Formulation 1Logic Formulation 1
Logic Formulation 1
 
Python-unit -I.pptx
Python-unit -I.pptxPython-unit -I.pptx
Python-unit -I.pptx
 
Unit 2
Unit 2Unit 2
Unit 2
 
PPL_Unit01 for the insem study first year.pptx
PPL_Unit01 for the insem study first year.pptxPPL_Unit01 for the insem study first year.pptx
PPL_Unit01 for the insem study first year.pptx
 
sege.pdf
sege.pdfsege.pdf
sege.pdf
 
Introduction to computer programming
Introduction to computer programming Introduction to computer programming
Introduction to computer programming
 
Chap1
Chap1Chap1
Chap1
 
programming.pptx
programming.pptxprogramming.pptx
programming.pptx
 
C Course material
C Course materialC Course material
C Course material
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdf
 
PROG0101_CH02.pptx
PROG0101_CH02.pptxPROG0101_CH02.pptx
PROG0101_CH02.pptx
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)
 
Presentation-1.pptx
Presentation-1.pptxPresentation-1.pptx
Presentation-1.pptx
 
Program Logic and Design
Program Logic and DesignProgram Logic and Design
Program Logic and Design
 
C program execution and algorithm
C program execution and algorithm C program execution and algorithm
C program execution and algorithm
 
DMA113 Chap1
DMA113 Chap1DMA113 Chap1
DMA113 Chap1
 
Computer language.ppsx
Computer language.ppsxComputer language.ppsx
Computer language.ppsx
 
Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 

Recently uploaded (20)

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 

LESSON__1-15 C-PROGRAMMING.p algorithm df

  • 1. Programming For Problem Solving (PFPS) LECTURE 1 Introduction to Algorithms and Flowcharts Algorithms and Flowcharts • Algorithm and flowchart are the powerful tools for learning programming • An algorithm is a step-by-step analysis of the process, while a flowchart explains the steps of a program in a graphical way. • Algorithm and flowcharts helps to clarify all the steps for solving the problem. • For beginners, it is always recommended to first write algorithm and draw flowchart for solving a problem and then only write the program. 2 Algorithms • A typical programming task can be divided into two phases: • Problem solving phase – Produce an ordered sequence of steps that describe solution of problem – This sequence of steps is called an algorithm – An algorithm is a sequence of steps to solve a particular problem – An algorithm is defined as an ordered set of unambiguous steps that produces a result and terminates in a finite time • Implementation phase – Implement the program in some programming language 3 Steps In Problem Solving • First produce a general algorithm called pseudocode. • Pseudocode is an artificial and informal language that is very similar to everyday English. It helps programmers develop algorithms. • Refine the algorithm successively to get step by step detailed algorithm that is very close to a computer language. 4
  • 2. Characteristics of an Algorithm • Algorithm has the following characteristics – Input: An algorithm may or may not require input – Output: Each algorithm is expected to produce at least one result – Definiteness: Each instruction must be clear and unambiguous. – Finiteness: If the instructions of an algorithm are executed, the algorithm should terminate after finite number of steps 5 Control Structures Involved In Algorithm and Flowchart • The algorithm and flowchart include following three types of control structures. – Sequence: In the sequence structure, statements are placed one after the other and the execution takes place starting from up to down. – Branching (Conditional): In branch control, there is a condition and according to a condition, a decision of either TRUE or FALSE is achieved. In the case of TRUE, one of the two branches is explored; but in the case of FALSE condition, the other alternative is taken. Generally, the ‘IF-THEN’ construct is used to represent branch control. – Loop (Repetition): The Loop or Repetition allows a statement(s) to be executed repeatedly based on certain loop condition using WHILE, Do-WHILE and FOR loops. 6 Example of Pseudocode and Algorithm • Example 1: Write the pseudocode and detailed algorithm to determine a student’s final grade and indicate whether the student is passing or failing. The final grade is calculated as the average of four marks. • Pseudocode: – Input a set of 4 marks – Calculate their average by adding the marks and dividing the sum by 4 – if average is below 50 Print “FAIL” else Print “PASS 7 Example of Pseudocode and Algorithm • Detailed Algorithm – Step 1: Input M1,M2,M3,M4 – Step 2: GRADE = (M1+M2+M3+M4)/4 – Step 3: if (GRADE < 50) then Print “FAIL” else Print “PASS” endif 8
  • 3. Advantages of Algorithm • It is a step-wise representation of a solution to a given problem, which makes it easy to understand. • An algorithm uses a definite procedure. • It is not dependent on any programming language, so it is easy to understand for anyone even without programming knowledge. • Every step in an algorithm has its own logical sequence so it is easy to debug. 9 Flowchart • Flowchart is defined as a diagrammatic /graphical representation of sequence of steps to solve a problem. • By looking at a flowchart, any one can easily understand the operations and sequence of steps involved in the solution • Flowchart is often considered as a blueprint of a design used for solving a specific problem • Different symbols are used to draw each type of flowchart. 10 Advantages of Flowchart • Flowchart is an excellent way of communicating the logic of a program. • It provides an easy and efficient way to analyze the solution to a problem. • During program development cycle, the flowchart plays the role of a blueprint, which makes the program development process easier. • After successful development of a program, it needs continuous timely maintenance during the course of its operation. The flowchart makes program or system maintenance easier. • It is easy to convert the flowchart into any programming language code. 11 12 Standard Symbols Used in a Flowchart
  • 4. Control Structures Representation in Flowchart 13 Symbols Used in Algorithm and Flowchart • Assignment Symbol (← or =) is used to assign value to the variable. E.g., to assign value 5 to the variable HEIGHT, statement is HEIGHT ← 5 or HEIGHT = 5 • The symbol ‘=’ is used in most of the programming language as an assignment symbol, the same has been used in all the algorithms and flowcharts in the manual • The statement C = A + B means that add the value stored in variable A and variable B then assign/store the value in variable C 14 15 16
  • 5. 17 GO TO statement is also called unconditional transfer of control statement is used to transfer control of execution to another step/statement. E.g. the statement GOTO n will transfer control to step/statement n. Note: We can use keyword INPUT or READ or GET to accept input(s) /value(s) and keywords PRINT or WRITE or DISPLAY to output the result(s). Sequential: Algorithm and Flowchart 18 19 Branching (Selection): Algorithm and Flowchart Looping: Algorithm and Flowchart 20
  • 6. Programming For Problem Solving (PFPS) LECTURE 2 Introduction to Programming Languages and Programming Language Translators Introduction to Programming • A language that is acceptable to a computer system is called a programming language or computer language • The process of creating sequence of instructions in any programming language is called programming or coding • A program is a set of instructions written to perform a specific task by the computer • A set of large programs is called a software 2 Computer Languages • A computer language is the main medium of communication between the users and the computer systems • Every computer language is bounded by rules known as syntax of the language • The user is bound by the syntax while communicating with the computer system • All the available computer languages are categorized into two basic types of languages: – Low level language – High level language 3 Computer Languages and its Types 4
  • 7. Low Level Language • The term low level highlights the fact that this language is closer to a language that the machine understands • Low level languages are the machine codes in which the instructions are given in machine language in the form of 0 and 1 to a computer system • The main function of the low level language is to operate, manage and manipulate the hardware and system components • Low level language is also divided into two categories: – Machine language – Assembly language 5 Low Level Language • Machine Language • It is one of the low-level programming languages which is the first generation language developed for communicating with a Computer. • It is written in machine code which represents 0 and 1 binary digits inside the computer string which makes it easy to understand and perform the operations • It is well known that a computer system can recognize electric signals (0 stands for turning off electric pulse and 1 stands for turning on electric pulse) 6 Low Level Language • Advantages of Machine Language – The main advantage of using Machine language is that there is no need of a translator or interpreter to translate the code, as the Computer directly can understand • Disadvantages of Machine Language – The programmer have to remember the operation codes, memory address every time you write a program and also hard to find errors in a written program – It is a machine dependent and can be used by a single type of computer 7 Low Level Language • Assembly Language – It is the second generation programming language that has almost similar structure and set of commands as machine language – Instead of using numbers like in machine languages here we use words or names in English and also symbols for different operations – The programs that have been written using words, names and symbols in assembly language are converted to machine language using an assembler 8
  • 8. Low Level Language • Advantages of Assembly Language – The main advantage of using assembly language is its speed that makes it the mostly used low level language till today that is used by many programmers • Disadvantages of Assembly Language – The main disadvantage of this language is that it is written only for a single type of CPU and does not run on any other CPU (machine dependent) 9 High Level Language • To overcome the limitation of low level languages, high level language has evolved which uses normal English and is easy to understand to solve any problem • The high level languages are the most commonly used that helps programmers to read, write and maintain code • It is also considered as the third generation language that is used by many programmers • High level languages require a programming language translator that can convert the high level language to machine language 10 High Level Language • Advantages: – Programming with this kind of language is quite easy and simple – High level languages are computer independent – Programs written in high level languages are portable across multiple systems 11 High Level Language • Some of the various high level languages are as given below: – BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn general purpose language. Mainly used in microcomputers in earlier days. – COBOL (Common Business Oriented language): A standardized language used for commercial applications. – FORTRAN (Formula Translation): Developed for solving mathematical and scientific problems. One of the most popular languages among scientific community – C: Structured Programming Language used for all purpose such as scientific application, commercial application, developing games etc. – C++: Popular object oriented programming language, used for general purpose. 12
  • 9. Programming Language Translators • To make the machine understand the instructions provided by both the languages, programming language translators are used • They transform the instructions written by programmers into a form which can be interpreted and executed by the computer. • The various tools/programming language translators used to achieve this purpose are: – Compiler – Interpreter – Assembler – Linker 13 Programming Language Translators 14 Programming Language Translators • Flowing are the various tools to achieve this purpose: – Compiler: The software that reads a program written in high level language and translates it into an equivalent program in machine language is called as compiler. – The program written by the programmer in high level language is called source program and the program in binary code (machine language) generated by the compiler after translation is called as object program. 15 Working of a Compiler 16
  • 10. Programming Language Translators – Interpreter: It also coverts each high-level program statement into the machine code. – The interpreter takes 1 statement, translates it, executes it and then again takes the next statement. 17 Working of Interpreter and Assembler • Both compiler and interpreters do the same job i.e., converting higher level programming language to machine code but their method of execution is different. 18 19 Programming Language Translators – Assembler: The software that reads a program written in assembly language and translates it into an equivalent program in machine language is called as assembler. 20
  • 11. Programming Language Translators • Linker: A linker or link editor is a computer program that takes one or more object files generated by a compiler and combines them into a single executable file, library file, or another object file. 21 Loader • In computer systems a loader is the part of an operating system that is responsible for loading programs and libraries. • It is one of the essential stages in the process of starting a program, as it places programs into memory and prepares them for execution. • Loading a program involves reading the contents of the executable file containing the program instructions into memory, and then carrying out other required preparatory tasks to prepare the executable for running. • Once loading is complete, the operating system starts the program by passing control to the loaded program code. 22 Working of Linker 23 Program Design Methods • There are two approaches mainly followed for program design: – Top-down programming – Bottom-up programming • Top-down programming: • It refers to a style of programming where an application is constructed starting with a high-level description of what it is supposed to do • It then breaks the specification down into simpler and simpler pieces, until a level has been reached that corresponds to the primitives of the programming language to be used 24
  • 12. Program Design Methods • Bottom-up programming: • Bottom-up programming is the opposite of top- down programming. • It refers to a style of programming where an application is constructed starting with existing primitives of the programming language. • It constructs gradually more and more complicated features, until the all of the application has been written. 25 Top-down program design method 26 Bottom-up program design method 27
  • 13. Programming For Problem Solving (PFPS) LECTURE 3 Introduction to C Brief History of C • The C programming language is a structure oriented programming language, developed at Bell Laboratories in 1972 by Dennis Ritchie. • C programming language features were derived from an earlier language called “B” (Basic Combined Programming Language – BCPL) • C language was invented for implementing UNIX operating system. • In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming Language” and is commonly known as K&R C. 2 Brief History of C • In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”, was completed late 1988. • Many of C’s ideas & principles were derived from the earlier language B, thereby naming this new language “C”. 3 Why is C popular? • C is a reliable, simple and easy to use programming language. • It is a small, block-structured (modular) programming language that allows the programmer to break the code into smaller fragments to improve the readability of the code and hence make the program simple to debug and maintain. • C is a portable language, which means that C programs written in one platform can be run on other platforms with little or no modification. – Eg. Suppose you are a Windows user but for some apparent reasons you want to switch to Linux. The programs that you have written and executed in Windows will work and give the same output when copied and pasted in a terminal while using LINUX. 4
  • 14. Why is C popular? • C has one of the largest collection of operators, such as those used for calculations and data comparisons. • The C standard library provides you a large range of inbuilt functions that program development quite easy for the programmers. • The C programming language helps you to manage memory efficiently as it supports the feature of dynamic memory allocation and bit fields. 5 Why to study C? • C serves as the base language or a prerequisite for learning other programming languages. Most of the popularly used programming languages came after the birth of C. • By the early 1980s, C was already a dominant language in the minicomputer world of Unix systems. Since then, it has spread to personal computers (microcomputers) and to mainframes. • C language is the most widely used language in operating systems development today. • Many software houses use C as the preferred language for producing various types of software as programs written in C are efficient and fast. 6 Characteristics of a C Program • Middle level language – Such languages don’t provide all the built-in functions found in high level languages, but provides all building blocks that we need to produce the result. • Small size – C language has only 32 keywords. • Extensive use of function calls – enables the end user to add their own functions to the C library. • Rich set of Library Functions – It is a robust language with a rich set of built-in functions and operators that can be used to write any complex program. 7 Characteristics of a C Program • Structured language – The structured programming language allows a programmer to code a program by dividing the whole program into smaller units or modules. • Low level (Bitwise) programming – C supports low level programming features which enable the programmer to carry out bit-wise operations. These features are normally provided in assembly language or machine language. • High level language constructs ̶ In addition to the low level language constructs, high level constructs (data type and operators) are available in C. 8
  • 15. Characteristics of a C Program • Pointer implementation ̶ Extensive use of pointers for memory allocation dynamically, array, structures and functions. • Efficient and fast ̶ programs written in C are efficient and fast due to its variety of data types and powerful operators. • Portable – It can be compiled on a variety of computers. • Supports loose typing – C is considered to be weakly typed, because you can convert any type to any other type through a cast. 9 Uses of C • Database systems • Graphics packages • Word processors • Spreadsheets • Operating system development • Compilers and Assemblers • Network drivers • Interpreters 10 Structure of a C Program • A C program is divided into different sections. There are six main sections in a basic c program. The six sections are: 1. Documentation Section 2. Link Section 3. Definition Section 4. Global Declarations Section 5. Main functions Section 6. Subprograms Section 11 Structure of a C Program 12
  • 16. Structure of a C Program • Documentation Section – The Documentation Section consists of a set of comment lines giving the name of the programmer, date and other details about the program. – Comments may appear anywhere within a program. Text between /* and */ appears as a comment in C. For Example: /* This is a Comment */ – Documentation section helps anyone to get an overview of the program. 13 Structure of a C Program • Link Section ̶ The link section provides instructions to the compiler to link functions from the system library using the #include directive. ̶ This leads to the compiler to link the header files from the system libraries. ̶ Example: #include<stdio.h> ̶ It tells the C compiler to include the contents of the system file called stdio.h (Standard Input Output header file). 14 Structure of a C Program • Definition Section – In this section, we define different symbolic constants using the #define directive. – The keyword define is used in this part. – Example: #define PI=3.14 – This statement defines a symbolic constant PI with value 3.14. 15 Structure of a C Program • Global Declaration Section: ̶ There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. ̶ This section also declares all the user-defined functions. ̶ Example: float area(float r); int a=7; 16
  • 17. Structure of a C Program • main() function Section: – Every C program must have one main function section which is the starting point of the program execution. – This section contains two parts: declaration part and executable part. • Declaration part: The declaration part declares all the variables used in the executable part. • Executable part: There is at least one statement in the executable part. – These two parts must appear between the opening and closing braces. 17 Structure of a C Program • main() function Section: – The program execution begins at the opening brace and ends at the closing brace. – The closing brace of the main function is the logical end of the program. – All statements in the declaration and executable part end with a semicolon. – Example: int main(void) { int a=10; printf(" %d", a); return 0; } 18 Structure of a C Program • Subprogram Section: – The subprogram section contains all the user defined functions that are used to perform a specific task. – These user defined functions are called in the main function. – User defined functions are generally placed just after the main() function, although they may appear in any order. – Example: int add(int a, int b) { return a+b; } 19 Sample Program 20
  • 18. Things to know in the Sample Program • #include <stdio.h>: – #include is a pre-processor directive. It is an instruction to the C compiler to include the contents of the file stdio.h. – stdio.h is the name of the standard library definition file for all STanDard Input and Output functions. • void: – Many programming languages need a data type to define the lack of return value to indicate that nothing is being returned. – The void data type is typically used in the definition and prototyping of functions to indicate that either nothing is being passed in and/or nothing is being returned. 21 Things to know in the Sample Program • scanf() and printf() – The standard input/output library contains a number of functions for formatted data transfer – The two functions that are used are scanf() (scan formatted) and printf() (print formatted) for reading input from keyboard and displaying output on screen. 22 Sample Program /*File Name: areaofcircle.c, Author: Manthan Naik, Date: 09/08/2019, Description: a program to calculate area of circle*/ #include<stdio.h> //link section #define pi 3.14; //definition section float area(float r); //global declaration int main() //main function { float r; //Declaration part printf(" Enter the radius:"); //Executable part scanf("%f", &r); printf(“The circle area is: %f", area(r)); return 0; } 23 Sample Program float area(float r) //Subprogram Section { return (pi * r * r); } • Output: Enter the radius: 7 The circle area is: 153.860001 24
  • 19. Files Used in a C Program • Source File: – This file contains the source code of the program. – The file extension of any c file is .c. – The file contains C source code that defines the main function and may be other functions. • Header File: – A header file is a file with extension .h which contains the C function declarations and macro definitions for c inbuilt library functions. 25 Files Used in a C Program • Object File: – An object file is a file containing object code, with an extension .o, which are produced by an assembler, compiler, or other language translator – This is then used as input to the linker, which in turn generates an executable file by combining the object files. • Executable File: – The binary executable file is generated by the linker. The linker links the various object files to produce a binary file that can be directly executed. 26 Compilation and Execution of a C Program 27
  • 20. Programming For Problem Solving (PFPS) LECTURE 4 C Language Fundamentals Elements of C • This lecture deals with the basic elements, which are used to create a C program. These elements are:- – Character set – Keywords – Identifiers – Data Types – Constant and Variables – Statements 2 Character Set • Character set in C includes the following: – The uppercase English alphabets A to Z – The lowercase English alphabets a to z – The digits 0 to 9 – Certain special characters as building blocks to form basic program elements i.e., Constants, variables, operators, expressions and statements. 3 Character Set 4
  • 21. Keywords • Keywords are the words whose meaning has already been explained to the C compiler. • The keywords cannot be used as variable names because assigning a new meaning to the keyword is not allowed by the C compiler. • There are only 32 keywords available in C. 5 Keywords 6 Identifiers • Identifiers are user-defined names given to various items in the program, such as variables, functions, arrays, structure, union, etc. • An identifier can be composed only of uppercase letters, lowercase letters, underscore and digits, but should start only with an alphabet or an underscore. • Underscore character is usually used as a link between two words in long identifiers. 7 Rules for Constructing Identifiers 1) The first character in an identifier must be an alphabet or an underscore and can be followed by any number of alphabets, or digits or underscores. 2) Identifiers must not begin with a digit. 3) Uppercase and lowercase letters are distinct. That is, identifiers are case sensitive. 4) Commas or blank spaces are not allowed within an identifier. 5) Keywords cannot be used as an identifier. 6) Identifiers should not be of length more than 31 characters. 7) Identifiers must be meaningful, short, quickly and easily typed and read. 8
  • 22. Example of Identifiers • Valid identifiers: total sum average _x y_ mark_1 x1 • Invalid identifiers: 1x - begins with a digit char - reserved word x+y - special character 9 Data Types • In the C programming language, data types refer to a domain of allowed values and the operations that can be performed on those values. • The data type of a variable determines the following information: – Identify the type of a variable when it is declared – The amount of space the variable occupies in storage – Specific operations that can be performed on the variable 10 Data Types • There are 4 primary/basic data types in C, which are as follows :– – char is used to store any single character – int is used to store any integer value, float and double – float is used to store any single precision floating point number – double is used to store any double precision floating point number • We can use two qualifiers with these basic types to get more data types. The two types of qualifiers are as follows: – Sign qualifier: signed and unsigned – Size qualifier: short and long 11 Built-In/Basic Data Types in C • Based on the combination of each of the primary data types and the qualifiers (sign and size) we can have the following basic data types: 12
  • 23. Data Types in C • C provides the following categories of data types: 13 Derived Data Types in C • Derived data types are composed of fundamental data types. Example of derived data types are arrays, structures, pointers etc. – A collection of integer values stored contiguously makes an array • Derived data types are what we can create by combining various primitive data types. There are basically three derived types in C: – Array – Function – Pointer 14 User-defined Data Type (UDT) • Sometimes, the basic set of data types defined in the C language such as int, float etc. may be insufficient for our application. • In such circumstances, we can create your own data types which are based on the standard ones. • A User-defined Data Type (UDT) is a data type that derived from an existing data type. UDTs can be used to extend the built-in data types already available and create your own customized data types. • There are three mechanisms for doing this in C: – using typedef – using structure – using union 15 Void Data Type in C • Many programming languages need a data type to define the lack of return value to indicate that nothing is being returned. • The void data type is used in the definition and prototyping of functions to indicate the following: – Nothing is being passed as parameter to the function. – No return value is being returned from the function. 16
  • 24. Size and Range of Data Types in C • Size refers to the amount of memory each data type requires for its storage in memory. • We can use the sizeof() operator to check the size of a variable. • The size of data types in C is dependent on the compiler. • Range means the maximum and minimum value that can be stored inside the variable of a given data type. 17 Steps to Print the Range of Data Types • The following three steps are used to compute the range (min to max) of permissible values in a particular data type: 1) Convert the size of the data type in bytes into bits (N). 2) For signed data types, the following formula is used to find the minimum and maximum range of values: -(2N-1) to 2N-1 - 1 Note: N-1 bits are used to compute range because one bit is used to store the sign of the signed data type. 3) The minimum and maximum range of an unsigned data type is given by: 0 to (2N - 1) where, N is the sizeof(datatype) × 8 i.e., total number of bits used by the data type. 18 19 20
  • 25. Constants • C constants is the most fundamental and essential part of the C programming language. • They have fixed values that are used in a program i.e., its value remains the same during the entire execution of the program. • Constants are also called literals and they can be of various data types. • The constants can be initialized once only. • A constant can be defined using the following syntax: const datatype constant_name; const keyword defines a constant in C. 21 Types of Constants in C • Constants are categorized into two basic types, and each of these types has its subtypes. • C constants can be divided into two major categories: – Primary Constants – Secondary Constants • The primary constants can be further categorized as: – Numeric Constants • Integer Constants • Real Constants – Character Constants • Single Character Constants • String Constants • Backslash Character Constants 22 Types of Constants in C 23 Integer Constants • An integer is a numeric literal without any fractional or exponential part. • There are three types of integer literals in C programming: • Decimal Integer constant (base 10): • Digits: 0 to 9 • E.g.: 49, 58, -62, etc. • Octal Integer constant (base 8): • Digits: 0 to 7 • Add “0” before the value. • E.g.: 045, 056, 067, etc. • Hexadecimal Integer constant (base 16): • Digits: 0 to 9 and A to F • Add “0x” before the value • E.g.: 0x42, 0x56, 0x67, etc. 24
  • 26. Integer Constants Rules for constructing Integer Constants in C – 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 (Note: This range is for 16-bit compiler. For a 32-bit compiler the range would be even greater.) 25 Real Constants/Floating-point Literals • A floating-point literal is a numeric literal that has either a fractional form or an exponent form. • Rules for constructing Real constants (Fractional Form) – A real constant must have at least one digit – It must have a decimal point – It could be either positive or negative – If no sign precedes an real constant, it is assumed to be positive. – No commas or blanks are allowed within a real constant. • For example: +867.9, -26.9876, 654.0. 26 Real Constants/Floating-point Literals • Rules for constructing Real Constants (Exponential Form) – The mantissa part and the exponential part should be separated by the letter ‘e’ – The mantissa may have a positive or negative sign(default sign is positive) – The exponent must have at least one digit – The exponent must be a positive or negative integer(default sign is positive) – The range of real constants in exponential form is - 3.4e38 and +3.4e38 • For example: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4 27 Character Constants • A “single character constant" is formed by enclosing a single character within single quotation marks (' '). • A character constants can contain any uppercase alphabet, any lowercase alphabet, a space, a digit and any special character. For Example: ‘m‘, ‘=‘, ‘A’, etc. • Character constant declaration: A character constant is declared by using const keyword. Syntax: const char constant_name = 'value'; • Format Specifier for Character Variable : – “%c” is used as format specifier for character inside C. – We can also use “%d” as format specifier because each character have its equivalent integer value known as ASCII value. 28
  • 27. Character Constants • Rules for Constructing Single Character constants – A single character constant or character constant is a single alphabet, a single digit or a single special symbol enclosed within single quotes. – The maximum length of a single character constant can be one character. – Each character constant has an integer value that is determined by the computer’s particular character set. 29 String Character Constant • A character string, a string constant consists of a sequence of characters enclosed in double quotes. • Rules for Constructing String Constants – A string constant may consist of any combination of digits, letters, escaped sequences and spaces enclosed in double quotes. – Every string constant ends up with a NULL character (‘0’) which is automatically assigned by the compiler before the closing double quotation mark. • For Example: “a”, “Ali”, “123”, “How are you”, etc. are string constants. 30 Escape Sequence or Backslash Character Constant • Escape sequence usually consists of a backslash followed by a character. These characters combinations are called as escape sequence. • Although it consists of two characters, it represents single character. • Each escape sequence has unique ASCII value. • They are non-printable characters. 31 32
  • 28. Variables • C variable is a named location in a memory where a program can manipulate the data. • This location is used to hold the value of the variable. • The value of the C variable may get changed in the program. • C variable might be belonging to any of the data type like int, float, char, etc. 33 Rules For Naming C Variable • Variable name must begin with letter or underscore. • Variables are case sensitive. • They can be constructed with digits, letters. • No special symbols are allowed other than underscore. • For Example: sum, height, _value are some variable names. 34 Declaring and Initializing C Variable • Variables should be declared in the C program before they are in use. This is done is done for informing the compiler that there exist a variable with specific data type which is used in the program. • Variable declaration does the following things: – It tells the compiler what the variable name is. – It specifies what type of data the variable will hold. • There are two things which need to be defined while declaring a variable: – Data type - which type of value is going to be stored in the variable. – Identifier - Valid variable name (identifier is the name of the allocated memory blocks for the variable). 35 Declaring and Initializing C Variable • When a variable is declared, it contains undefined value commonly known as garbage value. • If we want we can assign some initial value to the variables during the declaration itself. This is called initialization of the variable. 36
  • 29. Declaring and Initializing C Variable 37 Statements in C • Statements are the primary building blocks of a program. A program is a series of statements with some necessary punctuation. • A statement is a complete instruction to the computer. • In C, statements are indicated by a semicolon at the end. • Most of the statements in a C program are expression statements. An expression statement is simply an expression followed by a semicolon. • The lines i = 0; i = i + 1; printf("Hello, world!n"); are all expression statements. 38 Compound Statements in C • Compound statements (also called a block) are those that appears as the body of another statement. • Unlike expression statements, they do not end with a semicolon. • Compound statements is usually put on multiple lines, with one statement per line and are executed together. • Curly brackets { } are placed before and after compound statements. For Example: { line_num = 0; page_num++; } • Each inner statement ends with a semicolon, but the compound statement itself does not. 39 Compound Statements in C 40 • Compound statements can also be executed within a loop. For Example:
  • 30. Programming For Problem Solving (PFPS) LECTURE 5 Operators and Expressions Operators • C language supports a rich set of built-in operators. • An operator is a symbol that tells the compiler to perform specific mathematical or logical operations that are used in programs to manipulate data and variables. • C operators can be classified into following types: – Arithmetic Operators – Relational Operators – Logical Operators – Bitwise Operators – Assignment Operators – Increment and Decrement Operators – Conditional Operators – Special Operators 2 Arithmetic Operators • An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc. on numerical values (constants and variables). 3 Operator Meaning of Operator + addition or unary plus - subtraction or unary minus * multiplication / division % remainder after division (modulo division) NOTE: The % operator can only be used with integers. Example: Arithmetic Operators 4
  • 31. Relational Operators • A relational operator checks the relationship between two operands. • If the relation is true, it returns 1; if the relation is false, it returns value 0. • Relational operators are used in decision making and loops. 5 Relational Operators 6 Example: Relational Operators 7 Logical Operators • An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. • Logical operators are commonly used in decision making in C programming. 8
  • 32. Logical Operators Operator Meaning Example && Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0. || Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1. ! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(c==5) equals to 0. 9 10 Example: Logical Operators Bitwise Operators • In arithmetic-logic unit (within the CPU), mathematical operations like: addition, subtraction, multiplication and division are done in bit-level (bit level programming). • To perform bit-level operations in C programming, bitwise operators are used. • These operators can operate upon int and char but not on float and double. • Bitwise operators in C language are: & (bitwise AND), | (bitwise OR), ~ (bitwise Complement), ^ (bitwise XOR), << (left shift) and >> (right shift). 11 Bitwise Operators 12
  • 33. Truth Table of Bitwise Operators • The truth tables for &, |, ^ and ~ are as follows: 13 Bitwise Left Shift Operator 14 Bitwise Right Shift Operator 15 Example of Bitwise Operations • Assume variable A = 60 (00111100) and variable B = 13 (00001101), then: 16
  • 34. Assignment Operator • An assignment operator is used for assigning a value to a variable. • The most common assignment operator is equal to (=). 17 18 Increment and Decrement Operators • C programming has two operators ̶ increment (++) operator and decrement operator (-- ) to change the value of an operand (constant or variable) by 1. • Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. • These two operators are unary operators, meaning they only operate on a single operand. 19 Use of ++ and -- Operators as Prefix and Postfix • If you use the ++ operator as prefix like: ++var. The value of var is incremented by 1 then, it returns the value. • If you use the ++ operator as postfix like: var++. The original value of var is returned first then, var is incremented by 1. • The -- operator works in a similar way like the ++ operator except it decreases the value by 1. 20
  • 35. Increment and Decrement Operators 21 22 Example: Increment and Decrement Operators 23 NOTE: Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes like a++ and a--. Another Example of ++ and -- Operators as Prefix and Postfix 24
  • 36. Conditional Operator • The conditional operators in C language are known by two more names: – Ternary Operator – ? : Operator • It is actually the if condition that we use in decision making, but using conditional operator, we turn the if condition statement into a short and simple operator. • The syntax of a conditional operator is : expression1 ? expression2: expression3 25 Explanation of Conditional Operator • The question mark "?" in the syntax represents the if part. • The first expression (expression 1) generally returns either true or false, based on which it is decided whether (expression 2) will be executed or (expression 3) • If (expression 1) returns true then the expression on the left side of " : " i.e., (expression 2) is executed. • If (expression 1) returns false then the expression on the right side of " : " i.e., (expression 3) is executed. 26 Conditional Operator 27 28
  • 37. Other Operators In C • Besides the operators discussed, there are a few other important operators supported by the C language as listed below: – Comma operator, – Address of operator – sizeof() operator 29 Comma Operator • The comma operator is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value. • The comma operator has the lowest precedence among the C operators • Syntax: res = (num1, num2); – Value of rightmost variable will be assigned to the variable on the LHS of the equation as the result of the expression. – In this case, value of num2 will be assigned to variable res. 30 Example: Comma Operator • Example: a = 10,20,30; b = (10,20,30); – In the first statement, value of a will be 10, because assignment operator (=) has more priority than comma (,), thus 10 will be assigned to the variable a. – In the second statement, value of b will be 30, because 10, 20, 30 are enclosed in braces, and braces has more priority than assignment (=) operator. – When multiple values are given with comma operator within the braces, then right most value is considered as result of the expression. Thus, 30 will be assigned to the variable b. 31 Address of Operator • The "Address of" Operator denoted by the ampersand character (&) • & is a unary operator, which returns the address of a variable. • After declaration of a pointer variable, we need to initialize the pointer with the valid memory address • To get the memory address of a variable Address of (&) Operator is used 32
  • 38. Example: Address of Operator 33 sizeof() Operator • The sizeof is a unary operator and used to compute the size of its operand. • It returns the size of a variable. • It can be applied to any data type – int, float, pointer type variables, etc. • When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. 34 Example: sizeof() Operator 35 Operators Precedence and Associativity in C • Operator precedence dictates the order of evaluation of operators in an expression. • Certain operators have higher precedence than others • For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. • Associativity defines the order in which operators of the same precedence are evaluated in an expression. • Associativity can be either from left to right or right to left. 36
  • 39. Operator Precedence Table 37 Operators with highest precedence appear at the top and those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Operator Precedence Table 38 Expression In C • An expression is a combination of operators, constants and variables. • An expression may consist of one or more operands, and zero or more operators to produce a value. • In C, every expression evaluates to a value that can be assigned to a variable 39 Expression In C 40
  • 40. Programming For Problem Solving (PFPS) LECTURE 6 Managing Input Output Operations In C Lesson-2 Introduction to I/O Operations • One of the essential operations performed in C language is to provide input values to the program and output the data produced by the program to a standard output device • We can assign values to variable through assignment statements such as x = 5, a = 0 ; and so on. • Another method is to use scanf() function, which can be used to read data from a keyboard • For outputting results, we have used the printf() function extensively which sends results to a terminal (output device) 2 Introduction to I/O Operations • There exists several functions in ‘C’ language that can carry out input/output operations. These functions collectively make up the Standard Input/output Library. • Each program that uses standard input/out put function(s) must contain the following statement at the beginning of the C program: # include <stdio.h > where, stdio.h is the Standard Input Output Header file containing all input/output library function(s). 3 Unformatted and Formatted I/O Library Functions • Unformatted Input/Output Functions – The unformatted input/output functions provide the most preliminary i/o functions that are used just to take inputs and show outputs without any specified format. • Formatted Input/Output Functions – The formatted input/output functions helps the user to input and output in a certain format as specified – For example, if you want to scan a string up to 50 characters and print it right justified or in a tabular format, then you ought to go for formatted input output 4
  • 41. 5 6 Unformatted I/O Functions Single Character Input: the getchar Function • The getchar function is a part of the standard C input/output library. • It reads one character at a time from a standard input device (typically a keyboard) till the user presses the enter key. • The function does not require any arguments, but a pair of empty parentheses must follow the word getchar. • In general, a function reference would be written as: character_variable = getchar( ); where character_variable refers to some previously declared character variable. 7 Single Character Input: the getchar Function • The getchar function can also be used to read multi- character strings by reading one character at a time within a multi-pass loop. • If an End-Of-File (EOF) condition is encountered when reading a character with the getchar(), the value of the symbolic constant EOF will automatically be returned. Typically, the EOF will be assigned the value -1. 8
  • 42. getchar() Example 9 Other Unformatted Input Functions 10 getch() and getche() Example 11 Single Character Output: the putchar Function • Single characters can be displayed using the C library function putchar complementary to the character input function getchar. • putchar transmits a single character to the standard output device (the computer screen) that is represented as a character-type variable. • It must be expressed as an argument to the function, enclosed in parentheses, following the word putchar. • In general, a function reference would be written as: putchar(character_variable); where character_variable refers to some previously declared character variable. • It is defined in header file stdio.h. 12
  • 43. putchar() Example 13 Other Unformatted Output Function • putch() – putch() is unformatted character output function that is complementary to the character input function getch(). – Its working and syntax is similar to that of putchar() and is used for printing a character on a screen at the current cursor location. – While using getch(), the pressed character is not echoed and is displayed by using putch() function. – putch() is defined in header file conio.h. – Syntax: putch(character_variable); 14 putch() Example 15 gets() Function • The gets() function enables the user to enter some characters followed by the enter key. • It keeps reading the characters until the new line (enter) is encountered. • All the characters entered by the user get stored in a character array (string). • The null character is added to the array to make it a string. 16
  • 44. gets() Function • The gets() is similar to scanf() but also allows the user to enter the space-separated strings (multi-word strings). • The gets() function is defined in the <stdio.h> header file. • Syntax for declaration: char[] gets(char[]); Where char[] is a previously declared character variable. • The gets() function returns the string entered by the user. 17 gets() Example 18 puts() Function • This function prints the string or character array and is complementary to the function gets() • The puts() function is defined in the <stdio.h> header file. • Syntax for declaration: int puts(char[]); Where char[] is a previously declared character variable. • The puts() function returns an integer value representing the number of characters being printed on the console. 19 Example program (Involving both gets and puts) # include < stdio.h > void main ( ) { char str[80]; printf (“Type a string less than 80 characters:”); gets(str); printf (“The string types is:”); puts(str); } 20
  • 45. 21 Formatted I/O Functions Formatted Input Function: scanf() • The formatted input refers to input data that has been arranged in a particular format. • Input values are generally read by using the scanf function. • The scanf function has the general form: scanf(“control string”, arg1, arg2, arg3 …, argn); where control string refers to a string containing required format specifications, and arg1, arg2, …., argn are arguments that represent the addresses of individual variables. 22 Formatted Input Function: scanf() • The control string entries are separated be space and each entry is preceded by %. • Address of operator (&) must be placed in front of each of the variables used in scanf() • The format specifiers are used in the control string for input and output purposes. • The format specifiers enable the compiler to understand: – What type of data is in a variable while taking input using the scanf() function – What kind of values are being output using printf() function. 23 Format Specifiers in I/O 24
  • 46. Input specifications for an integer in scanf() • The general format for reading a integer number is: %wd • w is an integer number which specifies the field width of the number that is being read. • The data type character d indicates that the input should be read in integer mode. • The general format of reading an integer input using scanf() is: scanf(“%d”, &var); where, var is a previously declared integer variable. 25 Input specifications for an integer in scanf() • Example: scanf(“%3d %4d”, &sum1, &sum2); – If the input values are 175 and 1342, then value 175 is assigned to sum1 and 1342 to sum 2. – Suppose the input data was follows 1342 and 175. The number 134 will be assigned to sum1 and sum2 has the value 2 because of %3d the number 1342 will be cut to 134 and the remaining part is assigned to second variable sum2. – If floating point numbers are assigned then the decimal or fractional part is skipped by the computer. 26 Input specifications for a real number in scanf() • Real numbers are specified using %f specifier. • The general format for reading a real number input using scanf() is: scanf(“%f”, &var); where, var is a previously declared float variable. • Example: – scanf(“%f %f % f”, &a, &b, &c); – With the input data 321.76, 4.321 and 678.5, the values 321.76 is assigned to a , 4.321 is assigned to b and 678.5 to c. 27 Input specifications for a character in scanf() • Single character or strings can be input by using the character specifiers. • The general format for reading a single character or character array (string) is: %wc or %ws where c and s represent character and string respectively and w represents the field width of the input being read. 28
  • 47. Input specifications for a character in scanf() • The general format of specifying a single character input in scanf() is: scanf(“%c", &var); where, var is a previously declared character variable. • The general format of specifying a character array (string) input in scanf() is: scanf(“%s", str); where, str is a previously declared character array. 29 Example: Input individual characters using scanf() • The address operator (&) is not required to be specified while we input strings because string name itself represents the starting address of the character array. • If we read a string by using "%s" format specifier, string will be terminated when the first white space is found. • Consider the following statement: scanf("%c %c %c", &x, &y, &z); If the input is "a b c", then 'a' will be assigned to variable x, SPACE will be assigned to variable y and 'b' will be assigned to variable z. 30 Example: Read string with spaces using scanf() function #include <stdio.h> int main() { char name[30]; printf("Enter name: "); scanf("%s", name); printf("Name is: %sn", name); return 0; } Output -1 (Enter name without space) Enter name: Alex Name is: Alex Output -2 (Enter name with space) Enter name: Alex Thomas Name is: Alex 31 Formatted Output Function: printf() • In C programming language, "printf" is the name of one of the main C output functions, and stands for "print formatted". • printf() is complementary to the formatted input function scanf() • printf() function is used to print the character, string, float, integer, octal and hexadecimal values onto the output screen. 32
  • 48. Formatted Output Function: printf() • The printf function has the general form: printf(“control string”, arg1, arg2, arg3 …, argn); where control string refers to the format specifications that define the output format, and arg1, arg2, …., argn are the variables containing the values that will be printed on the screen. • The control string may also contain escape sequence characters such as n, t, b, etc. for desired output formatting. 33 Output of Integer Numbers • The general format for printing an integer is: %wd where, w is the minimum field width for the output to be printed. • If w is not specified, the output will consume whatever width is required for the output data. • d indicates that the output should be read in integer mode. • If the output width is greater than ‘w’, the printf() overrides the width specified by the user 34 Output of Integer Numbers • By default, the number is output as right-justified and leading blanks will appear as necessary (depending on w). • It is possible to make the output left justified be placing a minus sign (-) after the % symbol in the control string • It is also possible to pad the output with leading zeros instead of spaces by placing a ‘0’ before ‘w’ (%0wd) 35 Output of Real Numbers • The general format for printing a real number is: %w.pf where, – w is the minimum number of positions that are to be used for displaying the output – p is the number of digits to be displayed after the decimal point (precision) – The default precision is 6 decimal places. • Negative numbers are printed with the minus sign be placing a minus symbol before the corresponding variable name in the argument list 36
  • 49. Output of Real Numbers • A real number in exponential notation is displayed with the specification: %w.pe • Padding with leading zeros and printing with left justification by introducing ‘0’ or ‘-’ before w in the format specification. 37 Printing of a Single Character • A single character can be displayed using the following format: %wc • The character will be displayed right justified in the field of ‘w’ columns • Default value of w is 1. • The display is made left justified by placing a minus sign before the integer w. 38 Printing of Strings • The format specifications for outputting strings: %w.ps where. w: field width for displaying p: it specifies only the first p characters of the string that are to be displayed • Display is right justified 39 40 EXAMPLE: FORMATTED OUTPUT
  • 50. Programming For Problem Solving (PFPS) LECTURE 7 Decision Control/Selection Statements Using If Control Statements in C • In C, programs are executed sequentially in the order of which they appear. • This condition does not hold true always. Sometimes a situation may arise where we need to execute a certain part of the program. • Also it may happen that we may want to execute the same part more than once. • Control statements enable us to specify the order in which the various • instructions in the program are to be executed. • They define how the control is transferred to other parts of the program. 2 Classification of Control Statements 3 Selection Statements • The selection statements are also known as Branching or Decision Control Statements. • Sometime we come across situations where we have to make a decision. • Decision making structures require the programmer to specify one or more conditions to be evaluated or tested by the program, along • If the condition is determined to be true, a statement or a set of statements is to be executed • Otherwise if the condition is found to be false, the other statement or a set of statements to be executed 4
  • 51. if Statement • The if statement allows us to put some decision-making into our programs. • The general form of the if statement is: 5 if Statement • Syntax of if statement: if (condition ) { Statement 1; ………….. Statement n; } //Rest of the code • If the condition is true(nonzero), the statement will be executed. If the condition is false(0), the statement will not be executed. 6 Example of if Statement 7 if-else Statement • The if statement is used to execute only one action. If there are two statements to be executed alternatively, then if-else statement is used. • The if-else statement is a two way branching statement as another group of statements is executed if the expression evaluates to false. • The group of statements after the if is called an ‘if block’. • Similarly, the statements after the else form the ‘else block’. 8
  • 52. if-else Statement • The general syntax of simple if - else statement is: • Where, statement may be a single statement or a block. • If we desire that multiple statements be executed on a branch, we must block them inside of a pair of opening and closing curly braces to make them a single compound statement. 9 10 if-else Statement Example of if-else Statement 11 Example of if-else Statement 12
  • 53. Nested if-else statement • An entire if-else construct can be written within either the body of the if statement or the body of an else statement. • This is called ‘nesting’ of ifs. This is shown in the structure given in the figure for syntax of nested if-else construct. • From the syntax it is clear that: – If test condition – 1 is false, statemet3 is executed otherwise test condition-2 is tested. – If test condition – 2 is true, statemet1 is executed otherwise statemet2 is executed . 13 Syntax of Nested if-else construct 14 Flowchart of Nested if-else construct 15 Example of Nested if-else Statement 16 Write a program to check whether the given number is even or odd using nested if-else statement.
  • 54. Example of Nested if-else Statement 17 The if-else-if/else-if Ladder • When we are faced with a situation in which a program must select from many processing alternatives based on the value of a single variable, a multi-way decision statement is required • In C if-else-if ladder helps user decide from among multiple options. • The C if statements are executed from the top down. • As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. • If none of the conditions is true, then the final else statement will be executed. 18 General form of the if-else-if Ladder 19 Flowchart of if-else-if Ladder 20
  • 55. 21 Example of if-else-if Ladder 22 Write a program to check to check for the relation between two numbers using if-else-if ladder.
  • 56. Programming For Problem Solving (PFPS) LECTURE 8 Decision Control/Selection Statements Using Switch Case Statement The Switch Statement • The switch statement is a multi-way branch statement • It tests the value of a given variable/expression against a list of case values • When a match is found, a block of statements associated with that case is executed • When we need to choose one among a number of alternatives, a switch is used • The switch keyword is followed by an integer or an expression that evaluates to an integer 2 The Switch Statement • Case keyword is followed by an integer or character constant. We can also use char values in case and switch • Case labels always end with a colon (:). Each of these cases is associated with a block. • A block is nothing but multiple statements which are grouped for a particular case. 3 General Form of Switch-Case Statement 4
  • 57. 5 The Switch Statement • When the switch is executed, the expression is evaluated once and compared with the values of each case label • The value of the expression is compared against the each of the case values value1, value2, ..., valuen. • If a case is found whose value matches with the value of the expression, then the corresponding block of statements is executed • The break statement at the end of each block signals the end of a particular case and causes exit from the switch statement 6 The Switch Statement • If we do not use break, all statements after the matching label are executed. • Default is an optional case. If there is no match, the default statements are executed. • When present, the default case will be executed if the value of expression does not match with any of the case values. • If not present, no statement is executed if all the matches fail and the control goes to the statement directly after the switch-case 7 Few Important points regarding Switch- Case • Case doesn’t always need to have order 1, 2, 3 and so on. They can have any integer value after case keyword. • Also, case doesn’t need to be in an ascending order always, you can specify them in any order as per the need of the program. • You can also use characters in switch case. • The expression provided in the switch should result in a constant value otherwise it would not be valid. 8
  • 58. Few Important points regarding Switch- Case • Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex • Duplicate case values are not allowed. 9 10 Example of Program Using Switch-Case Statement 11
  • 59. Lecture-9 Loop Control Statements • A Loop executes the sequence of statements many times until the stated condition becomes false. • A loop consists of two parts, a body of a loop and a control statement. • The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false. • The purpose of the loop is to repeat the same code a number of times. Types of Loops • Depending upon the position of a control statement in a program, a loop is classified into two types: 1. Entry controlled loop 2. Exit controlled loop • In an entry controlled loop, a condition is checked before executing the body of a loop. It is also called as a pre-checking loop. • In an exit controlled loop, a condition is checked after executing the body of a loop. It is also called as a post-checking loop. The control conditions must be well defined and specified otherwise the loop will execute an infinite number of times. The loop that does not stop executing and processes the statements number of times is called as an infinite loop. An infinite loop is also called as an "Endless loop." Following are some characteristics of an infinite loop: 1. No termination condition is specified. 2. The specified conditions never meet. The specified condition determines whether to execute the loop body or not There are three types of loop constructs: 1. The while loop 2. The do-while loop 3. The for loop While Loop A while loop is the most straightforward looping structure. The basic format of while loop is as follows: while (condition) { statements; }
  • 60. • While loop is an entry-controlled loop. • In this loop, a condition is evaluated before processing a body of the loop. • If a condition is true then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false. Once the condition becomes false, the control goes out of the loop. • After exiting the loop, the control goes to the statements which are immediately after the loop. The body of a loop can contain more than one statement. If it contains only one statement, then the curly braces are not compulsory. • If the condition is not true, then the body of a loop will not be executed, not even once. Wright a program to print series of numbers from 1 to 10 using a while loop. #include<stdio.h> #include<conio.h> int main() { int num=1; //initializing the variable while(num<=10) //while loop with condition { printf("%dn",num); num++; //incrementing operation } return 0; } Do-While loop A do-while loop is similar to the while loop except that the condition is always executed after the body of a loop. It is also called an exit-controlled loop. The basic format of while loop is as follows: do { Statements } while (expression); As we saw in a while loop, the body is executed if and only if the condition is true. In some cases, we have to execute a body of the loop at least once even if the condition is false. This type of operation can be achieved by using a do-while loop. • In the do-while loop, the body of a loop is always executed at least once. After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop. • Similar to the while loop, once the control goes out of the loop the statements which are immediately after the loop is executed. • The main difference between the while and do-while loop is that in while loop the while is written at the beginning. In do-while loop, the while condition is written at the end and terminates with a semi-colon (;)
  • 61. Wright a program to print series of numbers from 1 to 10 using a do while loop #include<stdio.h> #include<conio.h> int main() { int num = 1; // Initialize starting number do{ //Start do while loop printf("%dn", num); ++num; //increment the number by 1 }while (num <= 10); return 0; } Difference between do while and while loop: do…while loop guaranteed to execute at least one time whereas while loop does not. For loop A for loop is a more efficient loop structure in 'C' programming. It has three sections: initialization, condition, increment or decrement. The general structure of for loop is as follows: for (initial value; condition; increment or decrement ) { statements; } The initial value of the for loop is performed only once. The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned. The increment/decrement increases (or decreases) the counter by 1. Wright a program to print a series of numbers from 1 to 10 using for loop #include<stdio.h> #include<stdio.h> int main() { int num = 1; //Initialize starting number for (num = 1; num <= 10; ++num) { printf("%dn", num); } return 0; } • In C, the for loop can have multiple expressions separated by commas in each part. For example: for (x = 0, y = num; x < y; i++, y--) { statements; } • Also, we can skip the initial value expression, condition and/or increment by adding a semicolon. For example: int i=0; int max = 10; for (; i < max; i++) { printf("%dn", i); }
  • 62. Nesting of loops • loops can also be nested where there is an outer loop and an inner loop. For each iteration of the outer loop, the inner loop repeats its entire cycle. • The syntax for a nested for loop statement in C is as follows − for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } The syntax for a nested while loop: while(condition) { while(condition) { statement(s); } statement(s); } The syntax for a nested do while loop: do { statement(s); do { statement(s); } while( condition ); }while( condition ); Wright a program for Multiplication table using nested for loop #include <stdio.h> #include<conio.h> void main() { int i, j; int table = 2; int max = 5; for (i = 1; i <= table; i++) // outer loop { for(j = 0; j <= max; j++) // inner loop ` { printf("%d x %d = %dn", i, j, i*j); } printf("n"); } } Output: 1 x 0 = 0 1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5 2 x 0 = 0 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 Exercises 1. Write a program to print all natural numbers from 1 to n using loop. 2. Write a C program to print all alphabets from a to z. - using while loop 3. Write a C program to print all odd number between 1 to 100. 4. Write a C program to count number of digits in a number. 5. Write a C program to calculate sum of digits of a number. 6. Write a C program to find power of a number using for loop. 7. Write a C program to check whether a number is Prime number or not. 8. Write a C program to check whether a number is Armstrong number or not. 9. Write a C program to print Pascal triangle upto n rows. 10. Write programs for the following patterns: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 * ** *** **** *****
  • 63. Lecture-10 Programming on loop control statements 1. This program checks whether a given number is a palindrome or not #include<stdio.h> #include<conio.h> void main() { int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or notn"); scanf("%d",&n); temp = n; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse +temp%10; temp = temp/10; } if ( n == reverse ) printf("%d is a palindrome number.n", n); else printf("%d is not a palindrome number.n", n); getch(); } Output: Enter a number to check if it is a palindrome or not 12321 12321 is a palindrome 2. Program to count the no of digits in a number #include<stdio.h> #include<conio.h> void main() { int n, count=0; clrscr(); printf("Enter an integer: "); scanf("%d", &n); do { n/=10; // n=n/10 count++; } while(n!=0); printf("Number of digits: %d“, count); getch(); } Output: Enter an integer: 34523 Number of digits: 5 3. Program to print the sum of 1st N natural numbers. #include<stdio.h> #include<conio.h> void main() { int n,i,sum=0; clrscr(); printf("Enter the limit: "); scanf("%d", &n); for(i=1;i<=n;i++) { sum = sum +i; } printf("Sum of N natural numbers is: %d",sum); getch(); } Output Enter the limit: 5 Sum of N natural numbers is 15 C program to print right triangle star pattern series #include <stdio.h> #include <conio.h> int main() { int i, j, n; clrscr(); printf("Enter value of n: "); scanf("%d", &n); for(i=1; i<=n; i++) { for(j=1; j<=i; j++) { printf("*"); } printf("n"); } return 0; } Output: Enter the value of n: 5 * ** *** **** *****
  • 64. Jump Statements Loops perform a set of repetitive task until text expression becomes false but it is sometimes desirable to skip some statement/s inside loop or terminate the loop immediately without checking the test expression. In such cases, jump statements are used. There are three jump statements. 1. Break statement 2. Continue statement 3. goto statement 1. break statement The break statement provides an early exit from loops like for, while, and do..while. A break causes the innermost enclosing loop or switch to be exited immediately. When break is encountered inside any loop, control automatically passes to the first statement after the loop. Syntax: break; Wright a program to understand break statement #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); for(n=1;n<=5;n++) { if(n==3) { printf(“Breakn”); break;} printf(“Number=%dn”,n); } printf(“Out of loopn”); getch(); } Output: Number=1 Number=2 Break Out of loop 2. Continue statement It is sometimes desirable to skip some statements inside the loop. In such cases, continue statement is used The continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do loop to begin. In the while and do, this means that the test part is executed immediately; in the for, control passes to the increment step. The continue statement applies only to loops, not to switch. Syntax: continue; Wright a program to understand continue statement #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); for(n=1;n<=5;n++) { if(n==3) { printf(“Continue Statementn”); continue;} printf(“Number=%dn”,n); } printf(“Out of loopn”); getch(); } Output: Number=1 Number=2 Continue Statement Number=4 Number=5
  • 65. 3. goto statement In C programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program. Syntax: goto label; ............. ............. ............. label: statement; In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control of the program will jump to the label: and executes the code below it C Program Which Print 1 To 10 Number Using goto statement. #include<stdio.h> #include<conio.h> void main() { int i=1; clrscr(); count: //This is Label printf("%dn",i); i++; if(i<=10) { goto count; //This jumps to label "count:" } getch(); } Output: 1 2 3 4 5 6 7 8 9 10 Reasons to avoid goto statement: • Though, using goto statement give power to jump to any part of program, using goto statement makes the logic of the program complex and tangled. • In modern programming, goto statement is considered a harmful construct and a bad programming practice. • The goto statement can be replaced in most of C program with the use of break and continue statements. • In fact, any program in C programming can be perfectly written without the use of goto statement. • All programmer should try to avoid goto statement as possible as they can. Exercises 1. WAP to input the 3 sides of a triangle & print its corresponding type. 2. WAP to input the name of salesman & total sales made by him. Calculate & print the commission earned. TOTAL SALES RATE OF COMMISSION 1-1000 3 % 1001-4000 8 % 6001-6000 12 % 6001 and above 15 % 3. WAP to print the following series i. S = 1 + 1/2 + 1/3 ……..1/10 ii. P= (1*2) + (2 *3) + (3* 4)+…….(8 *9) +(9 *10) iii. S = x + x2 + x3 + x4......+ x9 + x10 iv. S = 1/1! + 1/2! + 1/3! ……………+1/n! v. S = 1 + x + x2/2 + x3/3…….+xn/n 4. Write a C program to print Fibonacci series up to n terms. 5. Write a C program to find frequency of each digit in a given integer.
  • 66. Lecture-11 Function Monolithic Vs Modular Programming: 1. Monolithic Programming indicates the program which contains a single function for the large program. 2. Modular programming help the programmer to divide the whole program into different modules and each module is separately developed and tested. Then the linker will link all these modules to form the complete program. 3. On the other hand monolithic programming will not divide the program and it is a single thread of execution. When the program size increases it leads inconvenience and difficult to maintain. Disadvantages of monolithic programming: 1. Difficult to check error on large programs. 2. Difficult to maintain. 3. Code can be specific to a particular problem. i.e. it can not be reused. Advantage of modular programming: 1. Modular program are easier to code and debug. 2. Reduces the programming size. 3. Code can be reused in other programs. 4. Problem can be isolated to specific module so easier to find the error and correct it. User Define Functions Vs Standard Function User Define Function: A function that is declared, called and defined by the user is called user define function. Every user define function has three parts as: 1. Prototype or Declaration 2. Calling 3. Definition Standard Function: The C standard library is a standardized collection of header files and library routines used to implement common operations, such as input/output and character string handling. Unlike other languages (such as COBOL, FORTRAN, and PL/I) C does not include built in keywords for these tasks, so nearly all C programs rely on the standard library to function. FUNCTION A function is a group of statements that together performs a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. Function Declaration OR Function Prototype 1. It is also known as function prototype . 2. It informs the computer about the three things a) Name of the function b) Number and type of arguments received by the function. c) Type of value return by the function Syntax : return_type function_name (type1 arg1 , type2 arg2,…); OR return_type function_name (type1, type2,…); 3. Calling function need information about called function .If called function is place before calling function then the declaration is not needed. Function Definition: 1. It consists of code description and code of a function . It consists of two parts a) Function header b) Function body Function definition tells what are the I/O function and what is going to do. Syntax: return_type function_name (type1 arg1 , type2 arg2) { local variable; statements ; return (expression); }
  • 67. 2. Function definition can be placed any where in the program but generally placed after the main function . 3. Local variable declared inside the function is local to that function. It cannot be used anywhere in the program and its existence is only within the function. 4. Function definition cannot be nested. 5. Return type denote the type of value that function will return and return type is optional if omitted it is assumed to be integer by default. Wright a program to add two numbers using function #include <stdio.h> #include <conio.h> int sum(int , int); //function declaration or prototype int main() { int num1,num2,total; //variable declaration clrscr(); printf("Enter the two number "); scanf("%d %d",&num1,&num2); //getting two number as input from user total=sum(num1,num2); //calling the function //The total value (returned by the function) is stored in total variable. printf("The sum of these numbers :%d", total); //display the total value getch(); return 0; } int sum(int a, int b) //defining function based in declaration { int result=a+b; //find sum of two numbers //and result of sum stored in result variable return result; //returning result } Output Enter the two numbers 45 75 The sum of these numbers :120 ACTUAL ARGUMENTS AND FORMAL ARGUMENTS Actual Arguments 1. Arguments which are mentioned in the function call are known as actual arguments. 2. These are the values which are actually sent to the function. It can be written as constant, variable or an expression which return a value . Example: funct (6,9) , funct ( a,b ) Formal Arguments 1. Arguments which are mentioned in function definition are called dummy or formal arguments. 2. These arguments are used to just hold the value that are sent by calling function. 3. Formal arguments are like other local variables of the function which are created when function call starts and destroyed when end function. Example: return_type func(int x,int y) Write a program to find GCD (Greatest Common Divisor) of two numbers #include<stdio.h> int GCD(int,int); void main() { int a,b,gcd; printf(“Enter two numbers”); scanf(“%d%d”,&a,&b); gcd=GCD(a,b); // a,b are actual arguments printf(“GCD of %d and %d is %d”,a,b,gcd); } int GCD(int x, int y) // x and y are formal arguments { if(y==0) return x; else return GCD(y,x%y); } Output: Enter two numbers 21 35 GCD of 21 and 35 is 7
  • 68. PARAMETER PASSING TECHNIQUES In C programming parameters can be passed in two ways: 1. call by value 2. call by reference Call by value: Here values of actual arguments are passed to the formal arguments and operation is done in the formal arguments. Since formal argument is photo copy of actual argument, any changes made with the formal arguments do not affect the actual argument. Changes made to the formal argument are local to the block of called function, so when control comes back to calling function changes made, vanish. Program to explain a function with call by value. #include<stdio.h> void change(int num) { printf("Before adding value inside function num=%d n",num); num=num+100; printf("After adding value inside function num=%d n", num); } int main() { int x=100; printf("Before function call x=%d n", x); change(x); //passing value in function printf("After function call x=%d n", x); return 0; } Output: Before function call x=100 Before adding value inside function num=100 After adding value inside function num=200 After function call x=100 Note: Value of actual argument is not changed i.e. 100 Call by reference • In call by reference, the address of the variable is passed into the function call as the actual parameter. So formal arguments are the pointers to the actual arguments. • The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed. • In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address. i.e. changes made to the formal argument reflects the actual argument. Program to understand the concept of call by reference. #include<stdio.h> void change(int *num) { printf("Before adding value inside function num=%d n",*num); (*num) += 100; printf("After adding value inside function num=%d n", *num); } int main() { int x=100; printf("Before function call x=%d n", x); change(&x); //passing reference in function printf("After function call x=%d n", x); return 0; } Output: Before function call x=100 Before adding value inside function num=100 After adding value inside function num=200 After function call x=200
  • 69. Lecture-12 FUNCTION CATAGORIES There are four main categories of the functions these are as follows: 1. Function with no arguments and no return values. 2. Function with no arguments and a return value. 3. Function with arguments and no return values. 4. Function with arguments and return values. Function with no arguments and no return values: syntax: void funct(void); main( ) { funct( ); } void funct( void ) { } There is no communication between calling and called function. Functions are executed independently, they read data & print result in same block. Wright a program to estimate the area of square using the function with no arguments and no return values #include <stdio.h> #include <conio.h> void area(void); //function prototype int main() { area(); //function call getch(); return 0; } void area() // function definition { int square_area, square_side; printf("Enter the side of square :"); scanf("%d",&square_side); square_area = square_side * square_side; printf("Area of Square = %d",square_area); } Function with no arguments and a return value This type of functions has no arguments but a return value syntax: return_type funct(void); main( ) { int x; x=funct( ); printf(“%d=x”); } return_type funct( void ) { return(); } Here called function is independent, it read the value from the keyboard, initialize and return a value .Both calling and called function are partly communicated with each other.
  • 70. Wright a program to estimate the area of square using the function with no arguments and return values #include <stdio.h> #include <conio.h> int area(); //function prototype with return type int int main() { int square_area; clrscr(); square_area = area(); //function call printf("Area of Square = %d",square_area); getch(); return 0; } int area() // function definition { int square_area,square_side; printf("Enter the side of square :"); scanf("%d",&square_side); square_area = square_side * square_side; getch(); return square_area; } Function with arguments and no return values syntax: void funct(type); main( ) { funct(type); } void funct(type) { } Here functions have arguments so, calling function send data to called function but called function does no return value. such functions are partly dependent on calling function and result obtained is utilized by called function . Wright a program to estimate the area of square using the function with arguments and no return values #include <stdio.h> #include <conio.h> void area( int square_side); //function prototype int main() { int square_side; clrscr(); printf("Enter the side of square :"); scanf("%d",&square_side); area(square_side); //function call getch(); return 0; } void area(int square_side) { int square_area; square_area = square_side * square_side; printf("Area of Square = %d",square_area); } Function with arguments and return value syntax: return_type funct(type); main( ) { funct(type); } return_type funct(type) { } Here calling function passes arguments to the called function and called function returns value to calling function. Both the calling function and called function will receive data from each other. It’s like a dual communication.
  • 71. Wright a program to estimate the area of square using the function with arguments and return values #include <stdio.h> #include <conio.h> int area(int square_side); //function prototype with return type int int main() { int square_area,square_side; clrscr(); printf("Enter the side of square :"); scanf("%d",&square_side); square_area = area(square_side); //function call printf("Area of Square = %d",square_area); getch(); return 0; } int area(int square_side) { int square_area; square_area = square_side * square_side; return square_area; }
  • 72. Lecture-13 Recursion RECURSION • Recursion is a process in which a problem is defined in terms of itself. • Functions that call themselves are known as recursive functions, i.e. a statement within the body of a function calls the same function. Example: void main() { ……………………… /* Some statements*/ fun1(); ……………………… /* Some statements */ } void fun1() { ……………………… /* Some statements */ fun1(); /*RECURSIVE CALL*/ ……………………… Way to write a Recursive Function: Before writing a recursive function for a problem its necessary to define the solution of the problem in terms of a similar type of a smaller problem. Two main steps in writing recursive function are as follows: (i). Identify the Non-Recursive part(base case) of the problem and its solution(Part of the problem whose solution can be achieved without recursion). (ii). Identify the Recursive part(general case) of the problem(Part of the problem where recursive call will be made). Identification of Non-Recursive part of the problem is mandatory because without it the function will keep on calling itself resulting in infinite recursion. control flows in successive recursive calls Flow of control in successive recursive calls can be demonstrated in following example: Consider the following program which uses recursive function to compute the factorial of a number. void main() { int n,f; printf(“Enter a number”); scanf(“%d”,&n); f=fact(a); printf(“Factorial of %d is %d”,n,f); } int fact(int m) { int a; if (m==1) return (1); else a=m*fact(m-1); return (a); } Execution steps for n=4 fact(4) returns (4*fact(3) ) fact(3) returns (3*fact(2) ) fact(2) returns (2*fact(1) ) fact(1) returns (1) So for n=4, the factorial of 4 is evaluated to 4*3*2*1=24.
  • 73. For n=3, the control flow of the program is as follows: Winding and Unwinding phase All recursive functions work in two phases- winding phase and unwinding phase. Winding phase starts when the recursive function is called for the first time, and ends when the termination condition becomes true in a call i.e. no more recursive call is required. In this phase, a function calls itself and no return statements are executed. After winding phase unwinding phase starts and all the recursive function calls start returning in reverse order till the first instance of function returns. In this phase the control returns through each instance of the function. Implementation of Recursion All function calls(Whether Recursive or Non-Recursive) are implemented through run time stack. Stack is a Last In First Out(LIFO) data structure. This means that the last item to be stored on the stack(PUSH Operation) is the first one which will be deleted(POP Operation) from the stack. Stack stores Activation Record(AR) of function during run time. Here we will take the example of function fact() in the previous recursive program to find factorial of a number. Suppose fact() is called from main() with argument 3 i.e. fact(3); The run time stack changes during the evaluation of factorial of 3 is shown in the next slide. Stack changes during the evaluation of factorial of 3
  • 74. The following steps will reveal how the above stack contents were expressed: • First main() is called, so PUSH AR of main() into the stack. • Then main() calls fact(3) so PUSH AR of fact(3). • Now fact(3) calls fact(2) so PUSH AR of fact(2) into the stack. • Likewise PUSH AR of fact(1). • After the above when fact(1) is completed, POP AR of fact(1), Similarly after completion of a specific function POP its corresponding AR. • So when main() is completed POP AR of main(). Now stack is empty. • In the winding phase the stack content increases as new Activation Records(AR) are created and pushed into the stack for each invocation of the function. • In the unwinding phase the Activation Records are popped from the stack in LIFO order till the original call returns. RECURSION VERSES ITERATION • Every repetitive problem can be implemented recursively or iteratively. • Recursion should be used when the problem is recursive in nature. Iteration should be used when the problem is not inherently recursive. • Recursive solutions incur more execution overhead than their iterative counterparts, but its advantage is that recursive code is very simple. • Recursive version of a problem is slower than iterative version since it requires PUSH and POP operations. • In both recursion and iteration, the same block of code is executed repeatedly, but in recursion repetition occurs when a function calls itself and in iteration repetition occurs when the block of code is finished or a continue statement is encountered. • For complex problems iterative algorithms are difficult to implement but it is easier to solve recursively. Recursion can be removed by using iterative version. Tail Recursion A recursive call is said to be tail recursive if the corresponding recursive call is the last statement to be executed inside the function. Example: void show(int a) { if(a==1) return; printf(“%d”,a); show(a-1); } In the above example since the recursive call is the last statement in the function so the above recursive call is Tail recursive call. In non void functions(return type of the function is other than void) , if the recursive call appears in return statement and the call is not a part of an expression then the call is said to be Tail recursive, otherwise Non Tail recursive. Now look at the following example: int hcf(int p, int q) { if(q==0) return p; else return(hcf(q,p%q)); /*Tail recursive call*/ } int factorial(int a) { if(a==0) return 1; else return(a*factorial(a-1)); /*Not a Tail recursive call*/ } In the above example in hcf() the recursive call is not a part of expression (i.e. the call is the expression in the return statement) in the call so the recursive call is Tail recursive. But in factorial() the recursive call is part of expression in the return statement(a*recursive call) , so the recursive call in factorial() is not a Tail recursive call.
  • 75. Write a program using recursion to find the summation of numbers from 1 to n. #include<stdio.h> int sum(int); void main() { int n,s; printf(“Enter a number”); scanf(“%d”,&n); s=sum(n); printf(“Sum of numbers from 1 to %d is %d”,n,s); } int sum(int m) { int r; if(m==1) return (1); else r=m+sum(m-1);/*Recursive Call*/ return r; } Output: Enter a number 5 15 Write a program to find GCD (Greatest Common Divisor) of two numbers. #include<stdio.h> int GCD(int,int); void main() { int a,b,gcd; printf(“Enter two numbers”); scanf(“%d%d”,&a,&b); gcd=GCD(a,b); printf(“GCD of %d and %d is %d”,a,b,gcd); } int GCD(int x, int y) { if(y==0) return x; else return GCD(y,x%y); } Output: Enter two numbers 21 35 GCD of 21 and 35 is 7 Exercises 1. What do you mean by function? 2. What is the difference between actual arguments and formal arguments? 3. What do you mean by call by value and call by address? 4. How many types of functions are available in C? 5. What is the use of recursion in a program, Explain? 6. How to write a recursive function, Explain with example? 7. What is the difference between iteration and recursion? 8. Write a function to return larger number between two numbers: 9. Write a program using function to find factorial of a number. 10. Write a function power(n, m), to calculate the value of n raised to m. 11. Write a function that receives marks obtained by a student in 3 subjects and returns the average and percentage of these marks. Call this function from main() and print the result in main(). 12. Write a function to find GCD and LCM of two numbers. 13. Write a program using recursive function to find remainder when a positive integer m is divided by a positive integer n. 14. Write a program using recursive function to reverse number. 15. Write a recursive function to count all the prime numbers between number p and q(both inclusive).
  • 76. Lecture-14 ARRAYS Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. One Dimensional Array Declaration To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows: data_type array_name[size]; data_type represents the type of elements present in the array. array_name represents the name of the array. Size represents the number of elements that can be stored in the array. Example: int age[100]; float sal[15]; char grade[20]; Initialization: We can explicitly initialize arrays at the time of declaration. Syntax: data_type array_name[size]={value1, value2,……..valueN}; Value1, value2, valueN are the constant values known as initializers, which are assigned to the array elements one after another. Example: int marks[5]={10,2,0,23,4}; The values of the array elements after this initialization are: marks[0]=10, marks[1]=2, marks[2]=0, marks[3]=23, marks[4]=4 1. In 1-D arrays it is optional to specify the size of the array. If size is omitted during initialization then the compiler assumes the size of array equal to the number of initializers. Example: int marks[]={10,2,0,23,4}; Here the size of array marks is initialized to 5. 2. We can’t copy the elements of one array to another array by simply assigning it. Example: int a[5]={9,8,7,6,5}; int b[5]; b=a; //not valid we have to copy all the elements by using for loop. for(a=i; i<5; i++) b[i]=a[i];