Upload
hitenbhardwaj
View
223
Download
0
Embed Size (px)
Citation preview
8/12/2019 c Study Material
1/201
Course Modules
Course Modules
Chapter 1: Introduction to Program Design
Chapter 1: Introduction to Program Design
Chapter 2: Programming Environment
Chapter 2: Programming Environment
Chapter 3: History of Programming Language
Chapter 3: History of Programming Language
Chapter 4: Structure of C Program
Chapter 4: Structure of C Program
Chapter 5: Data Types
Chapter 5: Data Types
Chapter 6: Identifiers
Chapter 6: Identifiers
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
2/201
Chapter 9: Arrays
Chapter 9: Arrays
Chapter 8: Control Structures
Chapter 8: Control Structures
Chapter 10: Functions
Chapter 10: Functions
Chapter 11: Advanced Control Constructs
Chapter 11: Advanced Control Constructs
Chapter 12: Storage Class and Scope Rules
Chapter 12: Storage Class and Scope Rules
Chapter 13: Advanced Functions
Chapter 13: Advanced Functions
Chapter 14: Recursion
Chapter 14: Recursion
8/12/2019 c Study Material
3/201
8/12/2019 c Study Material
4/201
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
What is a Program ?What is a Program ?
Stages of program developmentStages of program development
Some definitionsSome definitions
8/12/2019 c Study Material
5/201
Lets understand what a Program is
A Program is a set of instructions to solve a problem.
And now define an Algorithm
An Algorithm is a step by step solution to a problem
But both sound similar? So what is the difference ifany?
Program and an algorithm represent solutions to problems , but a
program is written in a programming language and an algorithm is not
language specific. It is written in English like language called . So we
can say that a program is an implementation of an algorithm in aspecific programming language.
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
8/12/2019 c Study Material
6/201
Program design is very important before coding the program.
Programmer must consider all aspects of the program in detail before
coding a program.
Why a program at all?
A program is not the problem: it is a solution to a problem. Henceproblem definition is very important.
Problem definition
Programmers are very clear about the input to the program and the
output from the program and constraints under which the program has
to operate.
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
8/12/2019 c Study Material
7/201
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
Outlining the program structure
The next step after the problem definition is to decide how to solve the
problem. We use the top-down approach. It means that decompose
the whole problem into the number of independent tasks, and then
cut the tasks unto smaller subtasks and so on until they are small
enough to be grasped by mind. The task and subtasks are nothing but
functions. Each small module or tasks can be easily programmed and
linked together in the main program.
Algorithm development
An algorithm is any well defined computational procedure that takes
some value or set of values, as input and produces some value, or set of
values, as output.
8/12/2019 c Study Material
8/201
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
Algorithm are never concerned with software engineering issues of
data abstraction, modularity, error handling etc. It is pure logic.
Enough time must be always spent in algorithm development.
Selection of control structure
Control structure are nothing but the way to direct the flow of
execution. the three basic control structure are:
1. Sequence structure :- control flow goes from one statement toanother in sequence.
2. Selection structure :- Based on the condition, flow of control may go
to different in the program as in the if....else statement.
8/12/2019 c Study Material
9/201
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
3. Looping structure :- It is used when a set of instruction is to be
evaluated repeatedly.
Program Coding
As explained above, program is always to be coded into small
procedures i.e. to achieve modular design.
Meaningful variable name are to be used.
For example, area = length * breadth is more meaningful thana = l*b;
Function name must be meaningful so that anybody could understand
it's functionality in the program.
8/12/2019 c Study Material
10/201
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
Code must be well documented. Comments must be used whenever
necessary.
To increase the readability of the code, proper indentation must be
used. For example the following code :
if (x
8/12/2019 c Study Material
11/201
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
Use indentation to write it as
if ( x < y )
{
flag = TRUE;
printf(" x is larger than y");
}
else
flag = FALSE;
8/12/2019 c Study Material
12/201
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
Program Testing
Detection of error is called program testing. It is very difficult to
write an error free program in the first time even by expert
programmer.
Error type
Syntax Error :- Violation of rule of the language result in the
syntax error. Compiler detect it at the time of compilation.
Logical Error :- This cause incorrect result. This is due to the lackof emphasis on the algorithm development.
Run-time Error :- Errors such as mismatch of data type or
referencing an out of range array element or division by zero result
in the run-time error. Program may give wrong result.
8/12/2019 c Study Material
13/201
Chapter 1: Introduction to Program DesignChapter 1: Introduction to Program Design
Let us take an example. Mr.Samasya staying in Delhi wants to
purchase a book from Calcutta. He approaches Ms. Samadan to solvethe problem. Hence buying a book is the problem. Now, Ms. Samadan
starts dividing the problem into small tasks. She jots down the various
steps - enquire whether the book is available, book a ticket, purchase
book, return ticket. These are stepwise solution to the problem. (Analgorithm). She then sends one of her staff members to
Calcutta and Mr. Samasya is very happy. So,
PROBLEM DESIGN ----->ALGORITHM------>PROGRAM
Seven steps in all - This is what program design is all
about!!!
8/12/2019 c Study Material
14/201
Chapter 2: Programming EnvironmentChapter 2: Programming Environment
Various programming environmentsVarious programming environments
Various stages while executing a C programVarious stages while executing a C program
8/12/2019 c Study Material
15/201
Chapter 2: Programming EnvironmentChapter 2: Programming Environment
Various programming environments
Entering a Program
Once the program has been written, it must be entered into the
computer. Most new version of C include a screen editor. To enter anew program, it must be typed into the editing area. Once the
program has been entered it should be saved before it is executed.
Select Save As from the File menu and supply a program name such asarea.c. Once saved, the same program can be recalled by selecting Open
from the File menu.
8/12/2019 c Study Material
16/201
Compiling & Executing To compile and execute, select Run from
the Debug menu. If the program does not compile successfully, alist of error will appear in the separate window, otherwise,
program will ask you for input (if any) and display output within
the new window.
Entering a Program
The program must be entered into a file say area.c. If thefile is created with the help of a text editor, either ed or vi. The
command for calling the editor and creating the file is:
ed filename
If the file already existed, it is loaded else a new file is created.
Various stages while executing a C program
Chapter 2: Programming EnvironmentChapter 2: Programming Environment
8/12/2019 c Study Material
17/201
Compiling and linking
The compiling command is
cc filename.c.
If there is no error object file filename.o will be created. Linking with
a library file such as sqrt() are done automatically.
Executing
Use the command a.out and get the desired result.
Note: Linker always gives executable object code the same namea.out. In order to save a program from overwriting while compiling
another program you should rename the file by command
mv a.out filename.
Chapter 2: Programming EnvironmentChapter 2: Programming Environment
8/12/2019 c Study Material
18/201
Generation of computer languagesGeneration of computer languages
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
Structured, Functional, Modular ProgrammingStructured, Functional, Modular Programming
Introduction to C languageIntroduction to C language
8/12/2019 c Study Material
19/201
The olden days of machine language
The computer was an electronic machine in the 1950s. The capabilities
of this electronic machine as a computing machine have increasedphenomenally in the subsequent years.Since the earlier days
programmers have been looking for various ways of feeding computers
with the most appropriate instructions to carry out the task in the best
possible manner. Thus the earliest computers had to be programmedby directly loading their memories with machine level instructions.
Generation of computer languages
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
8/12/2019 c Study Material
20/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
The advantage was:
It was very fast as the program directly interacted with the
machines hardware.Disadvantage
It was very cumbersome to translate the program to machine level
instruction.
Different machines from different vendors had different sets ofmachine instructions.
Whew! Different different and different --- You can imagine how
difficult that was.
8/12/2019 c Study Material
21/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
Assembly Languages
This was the first refinement to the cumbersome machine languages.Using assembly languages a programmer can represent a computation
using textual mnemonics to represent instructions and data. Special
software called assemblers can translate such representation i.e.
Assembly language program into a set of machine level instructions.Advantage:
Since it uses text mnemonics to represent the program it is
comparatively easier thanmachine language.
8/12/2019 c Study Material
22/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
Disadvantage
Assembly languages are machine-dependent i.e. the program writtenfor a certain model of the machine may not be portable on a different
machine.
OOPS! That means I have to write different code fordifferent machines! Thats bad news!
8/12/2019 c Study Material
23/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
The High Level languages
The high level languages like C, Fortran ,Cobol etc. solved this
problem of machine dependence.These languages had standardized
ways of writing code and also had a language syntax so thatprogramsbecame more readable. The high level languages were mostly
general purpose with few exceptions like COBOL and others.The
translation from high level code to low level code(i.e.. The machine
level instructions) was done the compiler or the interpreter.(RememberAssemblers!)
8/12/2019 c Study Material
24/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
Understand terms- Structured,functional,modular
Structured Programming
In 1968, Computer Scientist Edsger Dijkstra of the Netherlands
published a letter to the editor in the Communication of the ACM
(Association of Computing Machinery) containing a title "GOTOStatement considered harmful". GOTO is a command available in all
the languages (including BASIC) to transfer control to a particular
statement. For the last 25 years, Dijkstra has been crusading for a
better way of programming - a systematic way to organize programs -called Structured Programming.
Structured Programming has been called arevolution in programming
and one of the most important advances in computer software of the
past two decades.
8/12/2019 c Study Material
25/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
There is no standard definition of structured programming available
but is often thought to beprogramming without the use of a GOTO
statement. Indeed, structured programming does discourage thefrequent use of GOTO but there is more to it than that.
Features of Structured Programming
Top-down analysis for program solvingModularisation for program structure and organization
Structured codes for the individual modules.
A High Level Language supports several control statements (also called
structured control statements or structured code) to produce a well-organised (structured) module.
8/12/2019 c Study Material
26/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
These control statements represent conditional and repetitive type of
executions. Each language has different syntax for these statements.
In PASCAL, the IF and CASE statements are examples of conditional
execution whereas FOR, WHILE and REPEAT statements represent
repetitive execution. In BASIC, FOR-NEXT and WHILE-WEND are
examples of repetitive execution.
Problems with Structured Programming
Analyzing the reasons for the failures in program development revealsthat there are weaknesses in the procedural paradigm itself. No matter
how well the structured programming approach is implemented, large
8/12/2019 c Study Material
27/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Languageprograms become excessively complex. What are the reasons for this
failure of procedural languages? One of the most crucial is the role
played by data.
Data Undervalued
In a procedural language, the emphasis is on doing things. And the
subdivision of a program into functions continues this emphasis.
Where does data fit in this paradigm? Data is usually the reason for a
program's existence.
Thus Structured ness is only one aspect of modular design. When the
project becomes very large management of the modules themselves
becomes a serious burden. The quest for finding a solution has led tothe popularity of object oriented programming in the recent years.
Structured is good Object oriented is more real-world I
suppose!
8/12/2019 c Study Material
28/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
Introduction to C language
C is a general purpose, structured programming language. It was
developed at AT&T's Bell laboratories of USA in 1972 by a single
person Dennis Ritchie.
In 1970s, the work on Unix system was going on. it was being writtenin Assembly level language (ALP), a language which uses simple
English words like MOV, ADD etc. But that was very difficult to
debug. So a new language C was developed along with Unix. Although
few high level language existed but they could not get popularity due toone reason or other.
The table below shows the evolution of C :
8/12/2019 c Study Material
29/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
YEAR LANGUAGE DEVELOPED BY REMARKS
- ALP - Difficult to debug
1960 ALGOLInternational
committeeToo general
1963 CPLCambridge
UniversityBig size
1967 BCPL Martin Richard No data types
1970B
Ken Thomson Very specific
1972 C Dennis Ritchie Versatile
8/12/2019 c Study Material
30/201
Chapter 3:History of Programming LanguageChapter 3:History of Programming Language
The growing popularity of C, changes made into over years has created
a necessity of its standard definition. It was done in 1983 by AmericanNational Standard Institute (ANSI)
That's quite an effort. We have A's then B then C
8/12/2019 c Study Material
31/201
Chapter 4: Structure of C ProgramChapter 4: Structure of C Program
Basic structure of a C programBasic structure of a C program
Using Comments in CUsing Comments in C
8/12/2019 c Study Material
32/201
Chapter 4: Structure of C ProgramChapter 4: Structure of C Program
The basic structure of the C program is as follows:
Ex: To print a message on the screen
#include
//Header FileInclusion
void main()//Start of the main function
{
printf("This is my first program in C");
//Executable statements
}
//End of main()
8/12/2019 c Study Material
33/201
Chapter 4: Structure of C Program
Chapter 4: Structure of C ProgramThe above program prints the message This is my first program in C
on the screen.
The first section shows header file inclusions. These header files contain
the definitions for the various funtions and keywords used in the
program. Here, the header file is stdio.h and this basically contains the
input output related functions.(For the time being).
The main() is the start of the program. A function is denoted by ().
void indicates that the function does not return any values. main() is
the name of the function .
The executable lines are terminated with a ; and here it displays the
message on the screen. printf is a function used to display data on thescreen
Shall we dissect this program and understand the contentsplease?
8/12/2019 c Study Material
34/201
Comments in C
Comments are almost always a good thing. Comments are used to
inform the person looking at the listing what is being done.
This type of comment begins with the /* character pair and ends
with */, not the end of the line.
While this style is not generally used in C++, it has uses in special
situations.
You can write a multi-line comment with only two comment symbols:
/* this is a potentially very long
multi-line comment */
Chapter 4: Structure of C ProgramChapter 4: Structure of C Program
8/12/2019 c Study Material
35/201
The main() starts with a { and ends with a }. This
is called a block.
I got it! But what is that // doing here?
You can also insert a /* */ comment anywhere in the middle of a
program line:
Chapter 4: Structure of C ProgramChapter 4: Structure of C Program
8/12/2019 c Study Material
36/201
The building block of C programs are functions. A function is a
subroutine that may include one or more statements designed to
perform a specific task. Writing a C program means writing
functions and putting them together.
Let's take a bigger example.
Chapter 4: Structure of C Program
Chapter 4: Structure of C Program
/* This program displays the cosine of an angle*/
#include #define PI =3.1416
main()
{ int angle=60;
float x,y;x=(PI/180)*angle;
y=cos(x);
printf("cos 50 degree is %f", y);
}
8/12/2019 c Study Material
37/201
Chapter 4: Structure of C ProgramChapter 4: Structure of C Program
SECTIONS MEANING EXAMPLE
Documentation set of comments like
name, use of programand others details
/* This program
displays the cosine ofan angle */
Link instruction to compilersto link function from
system library.
#include
Definition symbolic name
definition.
#define PI =3.1416
8/12/2019 c Study Material
38/201
SECTIONS MEANING EXAMPLE
Global Declaration variables whichcan be used in
different function.
/* No such declarationin this program */
Main()Program
tells compilerabout variable
used in the
executable part.
instruction to
execute
main() { int angle=60;float x,y;
x=(PI/180)*angle;
y=cos(x);printf("cos 50
degree is %f", y)}
Declaration
Execution
Chapter 4: Structure of C ProgramChapter 4: Structure of C Program
8/12/2019 c Study Material
39/201
Display can well be done in main() function only but for proper
work division display() function was used. In computer
program, it becomes a complete necessity.It will be explained further in coming chapters.
Chapter 4: Structure of C ProgramChapter 4: Structure of C Program
8/12/2019 c Study Material
40/201
Chapter 5: Data Types
Chapter 5: Data Types
Datatypes in CDatatypes in C
Constants and variablesConstants and variables
Escape sequencesEscape sequences
8/12/2019 c Study Material
41/201
Datatypes in C
The fundamental building blocks of any language are the datatypes it can
handle since a program has to represent data in order to do useful processing .
These datatypes are used in all languages to declare variables or constants
which will contain values when the program is running.C supports manydifferent types of data, each of which may be represented differently within
the computer's memory. the basic data types are listed below.
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
42/201
char single character 1 byte -128 to 127
int integer quantity 2 bytes or one word
(varies from one
compiler to another)
-32,768 to
32,767
float floating-point number 1 word(4 bytes)3.4e-38 to
3.4e+38
DATATYPE DESCRIPTION MEMORY
REQUIREMENTS
RANGE
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
43/201
8/12/2019 c Study Material
44/201
Chapter 5: Data TypesChapter 5: Data Types
In addition there are a no. ofdata type qualifiers short, long, signed
and unsigned which can be used to augment the basic data types. The
size and range of the basic data types using these qualifiers is listed in
the table below.
TYPE SIZE RANGE
char or
signed
char
1 byte -128 to 127
unsigned
char1 byte 0 to 255
int or
signed int2 byte -32,768 to 32,767
8/12/2019 c Study Material
45/201
TYPE SIZE RANGE
unsigned int 2 byte 0 to 65,535
short int or
signed int
1 byte -128 to 127
unsigned
short int1 byte 0 to 255
long int or
signedlong int
4 byte -2,147,483,648 to 2,147,483,647
unsigned
long int
4 byte 0 to 4,294,967,295
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
46/201
float 4 byte 3.4e-38 to 3.4e+38
double 8 byte 1.7e-308 to 1.7e+308
long
double 10 byte 3.4e-4392 to 1.1e+4392
TYPE SIZE RANGE
The standard headers and contains symbolic
constants for all of these sizes and other information.
Whew! That quite difficult. So many types and such large
numbers! Is there an easy way out!!?
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
47/201
To calculate the range for any datatype is very easy. For unsigned
numbers the range is0 - 2n-1
For signed numbers the range is
- 2n-1 to 2 n-1 -1
That's perfect and so very easy to work out!!!
Although so many datatypes have been mentioned the fundamentaltypes are char, int,float and double.
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
48/201
VARIABLES
Variables and constants are the basic data objects manipulated in aprogram. before using a variable it must be declared. Expression
combines variables and constants to produce new values
Rules for naming variables:
1.consists of a-z, A-Z, 0-9 but first character must be a letter.
2.case-sensitive.
3.underscore character can also be included.
4.special characters like *,-,+,',"" are not allowed.
5.blank space is not allowed within a variable name.
note: name of the variable should denote its use.
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
49/201
ex. sum, average_class, fun2.
note: Ram ,ram, RAM are different variable names.
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
50/201
CONSTANTS
A constant is a quantity that does not change.
A integer constant like 1234 consists of sequence of digits. It can be
decimal, octal or hexadecimal.
ex. 2415(decimal), 0xabc2(hexa), 0243(octal).
note:10,000(comma), 10-20(hypen or blank), 0900(preceded by 0) are
invalid integer constants.
A real constant is a base 10 number that contains either a decimal point
or an exponent or both.
ex. 1., 2.543, 0.9453e-34.
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
51/201
A real constant is a base 10 number that contains either a decimal point
or an exponent or both.
ex. 1., 2.543, 0.9453e-34.
note: 1. 1,00.00(comma), 2e+3.24(real exponent), 3e 10(blank space) are
invalid real constants.
2. Integer constants are exact quantities but real constants may be
approximations. 1.0 might be represented within the computer as0.99999 or 1.00001.
Chapter 5: Data TypesChapter 5: Data Types
A character constant is a single character enclosed in a apostrophe.
ex. 'a', '5', '*'.
note: ASCII characters showing the decimal equivalent of seven bits
represent a character in computer.
8/12/2019 c Study Material
52/201
Certain nonprinting characters, as well as the backslash(/) and the
apostrophe('), can be expressed in terms of escape sequences. Suchescape sequences always represent single characters, even though they
are written in terms of two or more characters.
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
53/201
8/12/2019 c Study Material
54/201
backslash \\ 092
null \0 000
A string constant consists of any number of consecutive
characters (including none), enclosed in quotationmarks("").
ex. "hello", "243-45+32", " ".
note: 1. 'A' and "A" are not equivalent.
2. The compiler places a null character(\0) theend of every string constant.
CHARACTER ESCAPE SEQUENCE ASCII VALUE
Chapter 5: Data TypesChapter 5: Data Types
8/12/2019 c Study Material
55/201
Shall we summarize the whole thing?Constants are those whose values do not change.For ex. India is a name constant, 10 is an integer constant and15th August 1949 (Indias independence) is a date constant.
The co-ordinates for the line are integer variables, a personsname is a character variable and so on.
In technical terms when we declare a variable then we speicfythe datatype and the variable name. Thus a variable name is thename given to a memory location.
Gotcha! When we want to store data, we require acontainer,a space to store it and the value stored maychange and thats why it is exactly called a variable.
Chapter 5: Data TypesChapter 5: Data Types
Ch 6 Id ifi
8/12/2019 c Study Material
56/201
Chapter 6: IdentifiersChapter 6: Identifiers
Objective:
Declaring a variable
Declaring a variable
Operators and expressionsOperators and expressions
Precedence of operatorsPrecedence of operators
Ch t 6 Id tifi
8/12/2019 c Study Material
57/201
All variables must be declared before its use. A declaration specifies a
type and contains a list of one or more variables of that type.
ex. int number, average, line[100];
Variable can also be initialized in its declaration.
ex. int number=0;
A qualifierconst can be applied to the declaration of any variable to
specify that its value cannot be changed.ex. const float mean=2.456383;
Chapter 6: IdentifiersChapter 6: Identifiers
Declaring a variable
Ch t 6 Id tifi
8/12/2019 c Study Material
58/201
OPERATORS AND EXPRESSIONS
Various elements of the program like constants, variables, array
elements, function references can be added together by various
operators to form expression
ARITHMETIC OPERATORS
They are binary operators as they work with two operands.The operators are + , - , * , / and % (modulo operator).
Chapter 6: IdentifiersChapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
59/201
There is a unary (minus operator) which multiplies its operand by
1 ie. It switches the sign.
Example:
int no1=10;int no2=20;
printf( no1+no2); //Will print 30
printf(no2%no1); //Will print 0
printf(no2%3); //Will print 2
Chapter 6: IdentifiersChapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
60/201
The Increment and Decrement operators
They are the ++ and -- operators
The ++ operator increments the operand by 1 and the operatordecrements its operand by 1.
Chapter 6: IdentifiersChapter 6: Identifiers
int no1=10;
no1++;printf(no1); //Will print 11 as the above
statement
is equivalent to saying no1=no1+1;
Chapter 6: Identifiers
f
8/12/2019 c Study Material
61/201
There are a prefix and postfix increment/decrement operators . Both
the forms are equivalent if used separately without the assignment.
But when the latter is done the meaning of the operation changes.
Chapter 6: IdentifiersChapter 6: Identifiers
For ex.
int no1=10;
no1++; (or) ++no1; will mean the same.
But,
int result = no1++; ----------------
Statement1
int result = ++no1; ----------------
Statement2
Chapter 6: Identifiers
Ch t 6 Id tifi
8/12/2019 c Study Material
62/201
Chapter 6: IdentifiersChapter 6: Identifiers
Statement1 will cause assignment to take place first followed by
increment(postfix increment)while
Statement2 will cause increment to take place first followed byassignment(prefix increment).
Thus result will have 10 if statement1 is executed and result will have 11
if statement2 is executed.
Assignment followed by operation in postfix and reverse inprefix. Good!
Chapter 6: Identifiers
Ch t 6 Id tifi
8/12/2019 c Study Material
63/201
Type Conversions
When an operator has operands of different types they undergo type
conversion before the expression takes its final value. If either operand
is long double, other is converted to long double.
Otherwise , If either operand is double, other is converted to double.
Otherwise , If either operand is float, other is converted to float.
Otherwise , convert char and short to int.
This conversion takes place automatically.
Chapter 6: IdentifiersChapter 6: Identifiers
Chapter 6: Identifiers
Ch t 6 Id tifi
8/12/2019 c Study Material
64/201
Chapter 6: IdentifiersChapter 6: Identifiers
RELATIONAL AND LOGICAL OPERATORS
The term relational specifies the relationships that the values canhave with each other. Expressions that contain relational operators
return true or false.
The relational operators used in C++ are
Operator Action
> Greater than
>= Greater than or equal< Less than
8/12/2019 c Study Material
65/201
Chapter 6: IdentifiersChapter 6: Identifiers
The Logical operators
They are so called because they return a logical value ie. True or false.They are used with relational operators in expressions.The operators
used are
Operator Action
&& Logical AND
| | Logical OR
! Logical NOT
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
66/201
The Bitwise Operators
C++ supports a full complement of bitwise operators . Bitwise
operation refers to testing,setting or shifting the actual bytes in a wordwhich correspond to the char and int data types and variants.
Operators Action
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise NOT>> Shift operator
8/12/2019 c Study Material
67/201
The ternary operator
C++ contains the very powerful and convenient operator that replaces
certain statements of the if-then-else form. It takes the general formExp1?exp2:exp3;
Exp1, the first expression1 is evaluate. If it is true then Exp2 i.e. The
expression2 becomes the value of the expression . If exp1 is false then
exp3 ie. Expression3 is the value of the expression.There are many more operators and will be discussed with the
relevant topics.
Chapter 6: IdentifiersChapter 6: Identifiers
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
68/201
Chapter 6: IdentifiersChapter 6: Identifiers
Precedence of operators
HIGHEST
! ,~ , ++, -- , (type) , *,&, sizeof
* , / , %
+ , -
=
= = , !=
&
^
|
&&
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
69/201
| |
?:LOWEST= ,+= ,-= ,*= ,/= etc.
pChapter 6: Identifiers
So ( ) (parenthesis or brackets)have highest priority andshorthand assignments the least.Must keep this in mind whilewriting expressions.
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
70/201
UNARY OPERATOR
These operator works on single operator to give a new result. Most
common example is unary minus such as -45.
Increment and decrement operator
The increment operator adds one to the operand while decrement
operator subtract one from the operand. Now comes the question what
is the difference between the prefix and postfix increment operator i.e.n++ and ++n. Both increment the operand by 1 but ++n increment n
before it's value is being used.
ex: if number=10, then a = number++; sets a to 10 although number is
incremented to 11.while a = ++number ; sets a to 11.
sizeof operator determines the number of bytes allocated to various
type of data item.
pChapter 6: Identifiers
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
71/201
ex: sizeof (integer) return 2 while for the declaration char madam[]
="meenakshi"; sizeof madam will return 10(one extra for null
character)
Casting is used to convert value of a expression to a different data type if
desired. Desired format is
(data type) expression
ex: if x is declared as integer with value 2, and y is declared as float
with value 3.5, then (x+y) % 2 is invalid because first operand need to be
integer. So to force operand to integer value casting is done as
((int) (x+y)) % 2
pChapter 6: Identifiers
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
72/201
note: data type associated with the expression is not changed by a cast.
Rather it is the value of the expression which undergoes change. Here
(int) (x+y) will have value 5.
ASSIGNMENT OPERATOR AND EXPRESSIONS
Expression such asi = i + 4
can be written in short hand form using arithmetic assignment operator
+= as
i += 2.Similarly other arithmetic operator can be used as assignmentoperator.
note: there should not be any blank space between + and = in arithmetic
assignment operator.
pChapter 6: Identifiers
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
73/201
CONDITIONAL OPERATOR
The statements
if(a>b)
max=a;
else
max=b;
finds the maximum of two number a and b. The sort hand rule is to use
conditional operator ( ? : ). Thus simple way to write above statement is
max = (a>b) ? a : b;
Chapter 6: Identifiers
PRECEDENCE
Precedence means order of evaluation. Operator with higher
precedence level is evaluated first.
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
74/201
While associativity is the order in which consecutive operations within
the same precedence group are carried out.
Chapter 6: Identifiers
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
75/201
OPERATOR
CATEGORY
OPERATORS ASSOCIATIVITY
Unary - ++ -- ! sizeof(type)
R L
Arithmetic * / %(same
precedence) + -
L
R
Relational
operators
> >= <
8/12/2019 c Study Material
76/201
OPERATOR
CATEGORY
OPERATORS ASSOCIATIVITY
Conditional
operator
? : L
R
Assignment
operator
= += -= *= /= %= L
R
p
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
77/201
Example :-
Evaluation of expression:
n=a*b/2+3/2*b+2+d; where a=3, b=2,c=3.4; n is declared as int.stepwise operation:
n=3*2/2+3/2*2+2+3.4
n=6/2+1*2+2+3.4 //note:3/2 is 1 not 1.5 as it is an integer division
and hence result is also integer.n=3+2+2+3.4
n=10 //note: n is declared as integer and hence can take
only integer value. It is assigned
10 ,not 10.4.
p
We have been talking of expressions so far can wehave a little more detail please?
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
78/201
EXPRESSIONS
Operators , constants and variables are the components of expressions.
An expression is a valid combination of the above mentionedelements. Great!
Order of evaluation
Neither C nor C ++ specifies the order in which the subexpressions
of an expression are evaluated. This leaves the compiler free to
rearrange an expression to produce more optimal code. For ex.X=exp1+exp2;
This statement does not ensure that exp2 will be evaluated after
exp1.
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
79/201
Type conversion in expressions
When constants and variables of different types are mixed in
expressions they are converted to the same type. This is called
type promotion. The compiler converts all operands upto thetype of the largest operand . The diagram can be shown as
follows:
Okay! Since lower dataypes are converted to higherdatatypes it is called promotion.
Chapter 6: Identifiers
Chapter 6: Identifiers
8/12/2019 c Study Material
80/201
CASTING IN EXPRESSIONS
We can force an expression to be of a specific typr by using a cast. Thegeneral form of the cast is
(type) expression
Technically casts are operators. A cast is unary and has the same
precedence as any other unary operator.
Short-hand assignment
There is a variation of the assignment statement that simplifies coding
of some types of assignment operations.
The are the +=, -= , *= , /= .
This notation is widely used in programming.
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
81/201
Various input output functionsVarious input output functions
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
82/201
C offers library functions for number of input/output operation like
getchar, putchar, scanf, printf, gets, puts. Most program begins with the
preprocessor statement #include . This header file gives
required information to the library functionscanf and printf.
getchar() and putchar() Function
getchar() takes a single character from the standard input device
generally keyboard.
char c= getchar(); statement assigns a single character inputted from
keyboard to the variable c.
Similarly putchar(c) function puts a single character c on the standardoutput device monitor.
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
83/201
Inputting data through scanf function
scanf() function is used to enter any datatype, an integer, a float or a
string.
eg: scanf("%d %f %s , &n,&interest, message);
The control string %d %f %s indicate that arguments n, interest,
message represent integer, float, string respectively as per its
declaration.
note: never forget to put &(ampersand) before variable name which arenot string or an array name.
note: A variable declared as character type will scan its ASCII value if
the control string is %d meant for integer.
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
84/201
Outputting data through printf function
printf() perform the similar function as scanf but to output the data.
eg: printf("%d", n);
note: No & is used while outputting the data.
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
85/201
Conversion string Corresponding controlled variable
type
%c character
%d integer
%e float with exponent( in output mode),
float (in input mode)
%f float without exponent( in output
mode), float (in input mode)
%g float using e-type and f-type. Trailing
zero and decimal point will not will be
displayed( in output mode), float (in
input mode)
%o Octal integer
8/12/2019 c Study Material
86/201
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
87/201
scanf(Revisited)
In case of string, %s will be able to control the input of a string only up tothe point a blank space is met. To solve this problem, we use control
string as %[ ABCDEFGHIJKLMNOPQRSTUVWXYZ12345;'./] .
Now inputted string may take all character specified inside [] and willterminate inputting string when any character outside this set is given as
input.
Another way to input string is by using the control argument
[^(character)]. Now the program will input the string until a character
or a escape sequence is inputted.
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
88/201
printf (Revisited)
It is possible to out the formatted data for example :to specify the
maximum number of decimal place for a float data type or maximumnumber of characters for a string.
Minimum width and precision may be specified for a float type data.
Minimum width is to limit the number of digit or character to a
specified limit while precision set the number of digit after the decimalpoint.
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
89/201
Example of formatting a float:
a=906.324
printf ("%7f %7.3f %7.1f ",a,a,a) output on execution will be 906.324000
906.324 906.3
printf ("%f %.3f %.1f",a,a,a) output on execution will be 906.324000
906.324 906.3
printf ("%e %.5e %.2e",a,a,a) output on execution will be 9.063240e+02
9.06324e+02 9.06e+02
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
90/201
In first example, field width is 7 and a has also 7 character width, so whole
number will be outputted. Precision is specified after field width with a
point. Default precision is 6 character after decimal. If field width
specification is more, then leading blank will come in the output before the
number.
Example of formatting a String:
char message[10];
printf ("%10s %20s %10.5s %.5",message,message,message,message)
Chapter 7: Basic I/O
Chapter 7: Basic I/O
8/12/2019 c Study Material
91/201
if message is assigned electronics during program, output on execution
will be electronics electronics elect elect
Even though electronics contains 11 character and field width
specification is only 10,the first string breaks the minimum field width
criteria. Second string is right justified within the specified width.
Precision criteria of 5 will just allow 5 character to be outputted and
field width criteria will work as earlier.
8/12/2019 c Study Material
92/201
Chapter 8 : Control Structures
Chapter 8 : Control Structures
C t l fl i th i hi h t l fl i
8/12/2019 c Study Material
93/201
Control flows is the manner in which control flows in a program.
It's type are :
1.sequential : control flows from one statement to other in sequence.
2.conditional : control flows as per the condition which can be either
true or false.
3.Iterative : control flows in a loop repeatedly
Any high level programming language has three features viz.Sequence,Iteration and Decision.Since C is a structured and High level
language it also has these constructs .
Selection statements imply decision.The constructs available here are
the if construct and the switch construct.
Selection statements(if and switch)
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
94/201
The if constructThe general format is
if(expression)
statement;
else
statement;
if(expression)
statement;else if(expression)
statement;
else
statement;
The other form of if is as follows:
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
95/201
Example. Accept a number from the user and display if it is an even or
odd number.
The if is an alternative to the ternary operator I guess!
#include
void main()
{
int no; //Declare a variable to
accept the number
printf(Enter the number);
scanf("%d); //Accept input from the
user
if(no%2==0 //Check for odd or even
no.the expression
evaluates
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
96/201
printf(Even number); //to a true or false.
else
printf(Odd number); //Executable statement
}Let us consider some more examples:
1. if (speed > 60)
printf("drive slowly");
else
printf(" your speed is all right"); //note the indentation i.e. the
way code are written with proper spacing.
2. if (square) {
scanf ("%f",&side);
area = side*side;
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
97/201
printf("area of square is: %f",area);
}
else {
scanf("%f %f",&length,&breadth);area = length*breadth;
printf("area of rectangle is: %f",area);
}
note: square must be assigned a non zero value before the second
example is being executed.
note: If there are more than one statement are to be executed if thecondition is true or false, they must be put under braces.
An example with if elseif
Accept an alphabet from the user and check if it is a vowel
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
98/201
#include
void main()
{
char alphabet; //Declare a variable
to accept the alphabet
printf(Enter the alphabet);
scanf("%c",&alphabet); //Accept
input from the user
if((alphabet==a) || (alphabet==A)) //The expression
evaluates
printf(vowel); //to a true or false
else if((alphabet==e) || (alphabet==E))
printf(vowel); //Executable
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
99/201
statement
else if((alphabet==i) || (alphabet==I))
printf(vowel);
else if((alphabet==o) || (alphabet==O)) //The
expression
uses logicaloperators
also
printf(vowel);
else if((alphabet==u) || (alphabet==U))
printf(vowel);
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
100/201
The switch construct
Switch statement is called a multiple-branch selection statement. It
successively tests the value of the expression against a list of integer or
character constants . When a match is found the statements associated with
that constant are executed.
else
printf(consonant);
}
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
101/201
break;
}
The general form of the switch clause is as follows:
switch(expression)
{
case constant1: statement;
break;
case constant2:statement;
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
102/201
Loops or iteration is another characteristic feature of any high levellanguage. This feature allows statements to be executed repeatedly
until a certain condition is reached. To understand the loop lets take a
real life example of a loop. Consider a relay race consisting of four
members. Here the athletes run around the track and pass on the rodtill the fourth player finishes. The components that we see are as
follows - there is astart condition i.e.. The first player starts the race,
there is astop condition the fourth player stops the race, there is an
action repeatedi.e.. Running and of course there is acounter , the judgewho counts the four athletes starting from one to four.
8.2 Looping statements(for,while,do..while)8.2 Looping statements(for,while,do..while)
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
103/201
Components of a loop
Similarly , in an iteration loop the above mentioned components should
ideally be present.If some of the components are missing it may result in
an infinite loop i.e. A loop which runs for infinite times.
C provides a number of looping constructs which may be used in
iteration problems.The following are the loops:
The for loop
The general form of the for loop is as follows:for (initialization;condition;reinitialization)
statement;
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
104/201
The initialization section is used to set the loop counter variable in
other words sets the start condition. Condition specifies the stop
condition and is a relational expression and this determines when the
loop will exit.
The reinitialization section increments or decrements the counter
variable according to the context of the loop. Statement indicates the
action repeated.
Ex.Print the first ten odd numbers.
Let us identify the four components in this simple loop problem.The start condition is 1 and stop condition is 10, action repeated is
printing of numbers .
Chapter 8 : Control Structures
Chapter 8 : Control Structures
h f l ill b i f ll
8/12/2019 c Study Material
105/201
The for loop will be written as follows:
for(int ctr=0,no=1;ctr
8/12/2019 c Study Material
106/201
In this example the counter has been decremented.
Okay!Reinitialization can both be increment and decrement. The
above loop rus for 100 times
Let us see some more examples.
Ex: Accept 10 alphabets from the user and convert them to uppercase if
they are in lowercase and vice versa.
#include //Header file inclusion
void main() //Main function
{
char alphabet; //Declaration of variables
Chapter 8 : Control Structures
Chapter 8 : Control Structures
for(int ctr=0;ctr
8/12/2019 c Study Material
107/201
for(int ctr=0;ctr=65 && alphabet
8/12/2019 c Study Material
108/201
scanf( %c ,&alphabet); //Accept the input
if((alphabet >=65 && alphabet =97 && alphabet
8/12/2019 c Study Material
109/201
In this example we have used some relational operators and relational
operators also.
ASCII link
Suppose I write for ( int I=0 ; ;I++) ,is it valid?
Very much. This is called an infinite loop where the condition part always
returns a true value.
This is a bodyless loop , a loop which has no action to be performed except
for iteration. We will see one such example when we do arrays .
One more question, for(int I=0;I
8/12/2019 c Study Material
110/201
The while loop
The syntax for the while loop is as follows:
Example:
Accept characters and display till the user presses n;
while(Condition)
{
}
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
111/201
#include
void main(){
char ch= ; //Declaration of variables
while(ch!=n) //Accept characters till user enters n
{sanf("%c",&ch);
printf(ch); //Display characters
}
}
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
112/201
Thus a while loop is normally used when the number of iterations are
not exactly known as in the above case.
Consider another example.
Print the first ten odd numbers.
#includevoid main()
{
int counter;
int number=1;
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
113/201
while(counter < 10)
{
printf(number);
number+=2;
}
}
There is something wrong,the initialization and reinitializationpart of loop is missing I suppose.
Chapter 8 : Control Structures
Chapter 8 : Control Structures
8/12/2019 c Study Material
114/201
Excellent! This may result in undesired consequences like infinite
loops. This is a logical error on the part of the programmer.
The correct code would be as follows:
int counter=0; //Statement 1
while(counter
8/12/2019 c Study Material
115/201
3.The do..while loop
The general structure of the do.while loop is as follows:
Then what is the difference? Why two loops doing the samejob?
do{
}while(condition);The loop works very much the same as that of the while loop.
8/12/2019 c Study Material
116/201
Chapter 8 : Control Structures
Chapter 8 : Control Structures
This will print the message once as the condition checking is done after
the loop is executed Had it been a while loop then the message would
8/12/2019 c Study Material
117/201
the loop is executed. Had it been a while loop then the message would
not have been printed at all.
Okay! The mantra is Use a for loop for finite iterations, awhile loop when number of iterations are not known and a dowhile loop if the loop has to be executed at least once.
8/12/2019 c Study Material
118/201
Arrays are collections of homogenous elements in
Chapter 9: Arrays
Chapter 9: Arrays
8/12/2019 c Study Material
119/201
continuous locations of memory having the same name.
Why arrays?
Most of the C application require the processing of large number of
data. The data may be identical and to be stored in sequential memory
location. So we share same name to to point a set of identical data. So
array is a collection of similar elements. these similar elements may be
int, char etc.
Three words- homogenous elements, continuouslocations and same name I'll remember that!
Chapter 9: Arrays
Chapter 9: Arrays
Array Declaration
8/12/2019 c Study Material
120/201
Like any other variable array need to be declared.
eg: int marks[60];
char message[40];
int specifies the type of variable stored in the array marks. 60 tells thecompiler the number of elements to be stored in the array.
note:- Compiler never gives error if you enter more than 60 elements in
the array. However, elements may go into the memory area notreserved by compiler for the array. This may cause data corruption . So
a proper check must be put in the program so that user may not enter
data more than the maximum specified limit.
Chapter 9: Arrays
Chapter 9: Arrays
Accessing Array element
8/12/2019 c Study Material
121/201
All the array element are given a label starting from 0. marks[0]
specifies the first element stored in the array. Similarly marks[20] is
the twenty-first element of the array. Thus the same variable namehave different content depending on it's label.
Entering Data into an Array
for (i=0;i
8/12/2019 c Study Material
122/201
times each time storing an element into the array.
note: We need not go for reading marks[60] as it will go out of bound.
Array initialization
note: In initialization, declaring the size of the array is optional.
If a array element is not initialized, it carries garbage value.
int number[5] ={1,2,3,4,5};
int n[]={1,2,3};
Chapter 9: Arrays
Chapter 9: Arrays
As soon as array is declared, compiler allocates the space to the array.
E h h i i dd h i l l i
8/12/2019 c Study Material
123/201
Each memory space has its unique address where a particular value is
stored.
An Example
Write a program to read marks of 60 student in the class and calculate
the class average.
main()
{
float avg, sum=0;
int i, marks[60];
Chapter 9: Arrays
Chapter 9: Arrays
for (i=0;i
8/12/2019 c Study Material
124/201
{
printf("\n Enter marks");
scanf("%d", &marks[i]);}
for (i=0;i
8/12/2019 c Study Material
125/201
A m*n array can be thought of with m rows and n column so as to keep
track of values in the tabular form.
for example: A two dimensional array containing float type data withmaximum 10 rows and 10 column can be declared as
float table[10][10];
note: This table may contain a maximum of 100 element, though the
compiler will not complain if you enter more than 100 element but this
may lead to data corruption. So a check on upper limit must be there in
the program.
8/12/2019 c Study Material
126/201
Chapter 9: Arrays
Chapter 9: Arrays
scanf ("%d", &n);printf("enter first matrix ");
f ( i i 0 i i )
8/12/2019 c Study Material
127/201
for ( int i=0;i
8/12/2019 c Study Material
128/201
note: A two dimension array can be read or written out using two
nested loop. In the above example, inner loop causes one row to be read
from the user while outer loop and outer loop controls the rows.In printing the matrix after adding ,we are changing line after
each row so as to give tabular look.
I can have arrays three dimensions too, but two itself iscomplex enough!
Chapter 9: Arrays
Chapter 9: Arrays
Arrays and Strings
8/12/2019 c Study Material
129/201
Arrays and Strings
Strings or simply any text are nothing but one dimensional array of
characters. Each character within the string will be stored within oneelement of the array.
eg:char text[] = "electronics";
There are 12 element in this array , 11 for the word and 1 for null
character(\0) which is added automatically at the end of the string.
There are different library function under the header file string.h which
processes the string.
Chapter 9: Arrays
Chapter 9: Arrays
for example:
strlen(s) will return the number of character in the string.
8/12/2019 c Study Material
130/201
( ) g
strcpy(s1,s2) copy string s2 to string s1.
The bottomline is character arrays have a terminator at theend.
8/12/2019 c Study Material
131/201
Chapter 10: Functions
Chapter 10: Functions
What are functions?
What are functions?
8/12/2019 c Study Material
132/201
Every C program is a collection of functions. Even main() is a function.
Program execution always begins with main().
A function is a set of instructions that does something.
Why functions?
i) Writing function avoids rewriting the same code over and over again.
Suppose it is required to find the number of ways of choosing r element
out of n element (i.e. n! / r! * (n-r)!). For this finding the factorial 3times is a tedious job. So it would be preferable to jump to factorial
subprogram three times and return to the main program.
Chapter 10: Functions
Chapter 10: Functions
ii) Functions help us to organize our work very well and keep track of
what we are doing. This way the work can be divided into separate
ll d l ll d f ti d th bi d t th
8/12/2019 c Study Material
133/201
smaller modules called functions and then combined together.
Example:
#include
void test();void again();
main()
{
printf ("\n Hello! I am in main");test();
Chapter 10: Functions
Chapter 10: Functions
again();
test();
8/12/2019 c Study Material
134/201
{
printf ("Are you there");}
void again() {printf ("I'm here again");
}
}
void test()
Output:
Hello! I'm in main.
Chapter 10: Functions
Chapter 10: Functions
Are you thereI'm here again
8/12/2019 c Study Material
135/201
I m here againAre you there
Explanation: void test(); and void again(); are the function prototypes
or declarations so that the compiler knows that these functions are
going to come later in the program. void specifies that function returnsnothing to the place where it is called.
test(); and again(); are the function calls.
void test() and void again() are the function headers from where the
function definition starts.
Chapter 10: Functions
Chapter 10: Functions
A function has a name, return type and a set of argumentsand arguments are optional
8/12/2019 c Study Material
136/201
g p
Function arguments and ReturnLet's see a function call avg = calavg(a,b,c);
On calling this function in main, function will return and assign
average of three numbers a, b, c to the variable avg. a, b, c are thefunction arguments and are called actual arguments.
Function can be defined as:-
float calavg( int x, int y, int z){
return (x+y+z) / 3; }
Chapter 10: Functions
Chapter 10: Functions
x, y, z are the formal arguments. Actual arguments and formal
t b th Th t t t t t th l
8/12/2019 c Study Material
137/201
parameters may be the same. The return statement returns the value
following it to the calling program. float specifies the type of value thatis to be returned by the function.
Chapter 11:ADVANCED CONTROL CONSTRUCTS
Chapter 11:ADVANCED CONTROL CONSTRUCTS
S t l t t
8/12/2019 c Study Material
138/201
Some more control constructs-
goto,continue,break statements
Some more control constructs-
goto,continue,break statements
Let's revise and add some more to what we have alreadyl t
Chapter 11:ADVANCED CONTROL CONSTRUCTS
Chapter 11:ADVANCED CONTROL CONSTRUCTS
8/12/2019 c Study Material
139/201
learnt.
The do-while statement
Sometimes it is required to execute the loop at least one time, we use do-
while loop.
example:
do {
..........(do some computation)printf("Do you want to continue the computation. enter y for
yes");
Chapter 11:ADVANCED CONTROL CONSTRUCTS
Chapter 11:ADVANCED CONTROL CONSTRUCTS
scanf("%c", ch);
} while ( ch = ='y');
8/12/2019 c Study Material
140/201
Again and again this message comes on the screen till youenter 'y' and at least one time the computation will go on
with this message.switch statement
In order to avoid the great size of if else statement, we use
switch statement. The general form is :
switch (expression)
{ case expression 1: statement;
..........
case expression m: statement; }
Chapter 11:ADVANCED CONTROL CONSTRUCTS
Chapter 11:ADVANCED CONTROL CONSTRUCTS
note: expression must result to only either integer or character type.
example:
8/12/2019 c Study Material
141/201
example:
switch (grade) {
case10: printf ("excellent"); break;
case 9:
case 8: printf ("good"); break;case 7:
case 6: printf ("average"); break;
case 5:
case 4:case 3:
Chapter 11:ADVANCED CONTROL CONSTRUCTS
Chapter 11:ADVANCED CONTROL CONSTRUCTS
case 2:
case 1:
case 0: printf ("improve"); break;
8/12/2019 c Study Material
142/201
p ( p ); ;
default: printf ("Wrong entry");
}
break statement is used so that control comes out of the switch block orany other block under braces {}where it is used.
note: If your grade is 9, then control flows from case 9: to case 8:
statement and a message good comes on screen.
Chapter 11:ADVANCED CONTROL CONSTRUCTS
Chapter 11:ADVANCED CONTROL CONSTRUCTS
The continue statement
8/12/2019 c Study Material
143/201
As the continue statement is met ,the next part of the loop is skippedand computation proceeds directly to the next pass through the loop.
for example:
for ( i =1; i
8/12/2019 c Study Material
144/201
goto statement
Chapter 11:ADVANCED CONTROL CONSTRUCTS
Chapter 11:ADVANCED CONTROL CONSTRUCTS
goto statement transfers the control from one part to any other part of
th H f t h ld b id d
8/12/2019 c Study Material
145/201
the program. However, use of goto should be avoided.
note: If the condition is satisfied the goto statement transfers control tothe label msg causing printf() following msg to be executed.
example: if (ans= = 5) goto msg;
............................
............................
msg: printf ("With good programming skills use of goto canalways be avoided");
Chapter 12: STORAGE CLASS AND SCOPE RULES
Chapter 12: STORAGE CLASS AND SCOPE RULES
8/12/2019 c Study Material
146/201
Auto,static and extern variablesAuto,static and extern variables
Lifetime and scope of these variablesLifetime and scope of these variables
Chapter 12: STORAGE CLASS AND SCOPE RULES
Chapter 12: STORAGE CLASS AND SCOPE RULES
Storage class refers to the visibility of a variable and its scope within
the program i e the portion of the program over which the variable is
8/12/2019 c Study Material
147/201
the program i.e. the portion of the program over which the variable is
recognized. There are four different storage class in C: automatic,external, static and register which are identified by the keywords auto,
extern, static and register respectively. They are classified depending on
the following four parameters:
1)storage: where these variables are stored.
2)default initial value: value assigned to the variable at the time of
declaration.
3)scope: refers to the portion of program over which the variable isrecognized.
4)life: how long would the variable exist.
Chapter 12: STORAGE CLASS AND SCOPE RULES
Chapter 12: STORAGE CLASS AND SCOPE RULES
STORAGE
CLASS
STORAGE DEFAULT I
NITIAL
VALUE
SCOPE LIFE
8/12/2019 c Study Material
148/201
auto memory garbagevalue
local tothe block
where it is
defined
till the controlremains within the
block in which the
variable is defined.
register CPU
registers
(fastest
memory)
garbage
value
local to
the block
where it is
defined
till the control
remains within the
block in which the
variable is defined.
Chapter 12: STORAGE CLASS AND SCOPE RULES
Chapter 12: STORAGE CLASS AND SCOPE RULES
STORAGE CLASS STORAGE DEFAULT
INITIAL
VALUE
SCOPE LIFE
8/12/2019 c Study Material
149/201
static memory zero local to theblock where
it is defined.
value ofvariable
persists
between
differentfunction
calls.
extern memory zero global throughout
theprogram
note: Default storage class for a variable is auto.
Chapter 12: STORAGE CLASS AND SCOPE RULES
Chapter 12: STORAGE CLASS AND SCOPE RULES
Variables declared have a certain scope I see or maybe I
8/12/2019 c Study Material
150/201
can't see!!
Chapter 12: STORAGE CLASS AND SCOPE RULES
Chapter 12: STORAGE CLASS AND SCOPE RULES
Local Variables
The variables declared within the function are called local variable
8/12/2019 c Study Material
151/201
because scope of these type of declaration of variable only exist to the
function in which they are defined. The local variables are declared at
the start of function body.
Example: int sum(){
int x, y, s;.............}
int difference(){
int x, y, s;
..............}
The variables x,y,s which are declared in both the functions are local
and have different memory allocation. They have no relation among
themselves.
Chapter 12: STORAGE CLASS AND SCOPE RULES
Chapter 12: STORAGE CLASS AND SCOPE RULES
Global Variables
Th f l b l i bl i h h h Al
8/12/2019 c Study Material
152/201
The scope of global variable remains throughout the program. Also,
they hold their values during the entire execution of the program.
Global variables are always declared outside of all functions.
It is used when a variable must be accessible to more than one
function. However, external variables create organizational problem
for the very reason that they can be accessed by any function. The
wrong function may access them or function may access them
incorrectly.
Global variables I can always see, local variables I can seeonly within the local block0
Scope rules of functions
By default the scope of a variable is local to the function in which it is
Chapter 12: STORAGE CLASS AND SCOPE RULES
Chapter 12: STORAGE CLASS AND SCOPE RULES
8/12/2019 c Study Material
153/201
By default the scope of a variable is local to the function in which it is
defined. Hence a variable defined in main() is local to the main()function and similarly a variable defined in a subprogram has to be
returned to make it available in the calling function.
Chapter 13: ADVANCED FUNCTIONS
Chapter 13: ADVANCED FUNCTIONS
Methods of parameter passing
Methods of parameter passing
8/12/2019 c Study Material
154/201
Call by valueCall by value
Call by referenceCall by reference
Functions and arrays
Functions and arrays
Chapter 13: ADVANCED FUNCTIONS
Chapter 13: ADVANCED FUNCTIONS
Now that we have seen functions and their usage, let us look into the
various concepts
B f d t th i t t t l t d t d
8/12/2019 c Study Material
155/201
Before we proceed to these important concepts, let us understand
something about the function. A function is only a set of instructions
and the function name is a pointer to the start of the instructions which
make the function. So when a function is called, the control switches
from the caller function to the called function. After the function is
executed the control returns back to the caller.
There are two ways of passing parameters: 1.call by value and 2. call by
reference.
13.1 Methods of parameter passing
13.1 Methods of parameter passing
Chapter 13: ADVANCED FUNCTIONS
Chapter 13: ADVANCED FUNCTIONS
In the first method value is passed to a function via actual argument
13.2 Call by value
13.2 Call by value
8/12/2019 c Study Material
156/201
In the first method value is passed to a function via actual argument.
Value of actual argument is copied into the formal argument in the
function. Therefore, the value of corresponding formal arguments can
be altered within the function but the value of actual argument within
the calling routine will not change.
Example: main(){
int x=10, y=20;
swap(x,y);
printf("\n x=%d y=%d", x, y);}swap( int a, int b){
int temp;a=b;
Chapter 13: ADVANCED FUNCTIONS
Chapter 13: ADVANCED FUNCTIONS
printf("\n a=%d b=%d", a, b);}
output: a=20 b=10
x 10 y 20
b=temp;
8/12/2019 c Study Material
157/201
x=10 y=20
note: The value of x and y remain unchanged even after exchanging the
value of a and b.
13.3 Call by reference13.3 Call by reference
In the second method (call by reference), the addresses of actual
arguments in the calling function are copied into formal arguments of
the called function. This will facilitate the programmer to access the
actual arguments and hence will be able to manipulate them. Addressesof the actual argument are sent from the calling program through
address of or & operator while they are received in the called function
by the pointer variable.
Chapter 13: ADVANCED FUNCTIONS
Chapter 13: ADVANCED FUNCTIONS
13.4 Functions and arrays
13.4 Functions and arrays
The entire array can be passed to a function as an argument
8/12/2019 c Study Material
158/201
The entire array can be passed to a function as an argument.
Example:
float avg (int , int []); //function prototype
main(){
int x, lot[100]; float average;
...............
average= avg (x, lot); //function call
...............}
float avg (int n, int a[]) //function definition
{....................}
Chapter 13: ADVANCED FUNCTIONS
Chapter 13: ADVANCED FUNCTIONS
Explanation: When declaring a one-dimensional array as formalargument the array name is written as pair of empty square braces
while the size must be declared in the main function at the time of
8/12/2019 c Study Material
159/201
declaration. To pass an array to a function the array name must appearby itself, without bracket, as actual argument within the function call.
argc and argvThe arguments that we pass on to main() at the command prompt are
called command line arguments. The function main can have two
arguments, argc and argv. Out of these argv is an array of pointers to
strings and argc is an integer whose value is equal to the number of
strings to which argv points. When the program is executed the string on
the command line are passed to main(). More precisely the string at
command line are stored in memory and addresses of first string is
stored in argv[0] , and so on.
Chapter 13: ADVANCED FUNCTIONS
Chapter 13: ADVANCED FUNCTIONS
If I pass the value to the function , I am doing it by call by value, and If I
pass the addresses of the arguments I am going for call by reference.Can
we have the advantages and disadvantages please?
8/12/2019 c Study Material
160/201
Call by value:
Advantages: 1. Simple mechanism 2. Used in calling functions with few
argumentsDisadvantages: Memory wastage as the variables are duplicated
Call by reference:
Advantages: 1. Used when one need not return a value or indirectly
return more than one value2.Useful in passing arrays
Disadvantages: More complicated than the previous mechanism.
Chapter 14: RECURSION
Chapter 14: RECURSION
Define recursion
Define recursion
8/12/2019 c Study Material
161/201
An example showing the working of recursive processAn example showing the working of recursive process
Chapter 14: RECURSION
Chapter 14: RECURSION
14.1 Define recursion
14.1 Define recursion
8/12/2019 c Study Material
162/201
Recursion is a low level feature of the 'C' language. It is a verypowerful mechanism of doing complicated programs and reducing the
size of the programs.
Recursion is a process by which the function calls itself repeatedly
until some specified condition has been satisfied. Also referred to as'circular definition', recursion is thus the process of defining ion terms
of own self.
Conditions that are to be satisfied for a recursive problem:
The problem must be written in recursive form.
The problem statement must include a stopping condition.
Chapter 14: RECURSION
Chapter 14: RECURSION
For example: In recursive form n! = n * (n-1)! and stopping condition is
1! = 1.
8/12/2019 c Study Material
163/201
Calculating Factorial of number n
#include
long int factorial(int n);
main()
{
int n;
printf(" \nEnter the number whose factorial is to be calculated\n");
scanf("%d", &n);
Example showing the working of recursive process
printf("n! = %ld\n", factorial(n));
}
long int factorial(int n)
Chapter 14: RECURSION
Chapter 14: RECURSION
8/12/2019 c Study Material
164/201
{if (n
8/12/2019 c Study Material
165/201
Chapter 15: POINTERS
Chapter 15: POINTERS
What are pointers?
What are pointers?
Pointer Arithmetic
Pointer Arithmetic
8/12/2019 c Study Material
166/201
Arrays and PointersArrays and Pointers
ExercisesExercises
Array of PointersArray of Pointers
Pointers and stringsPointers and strings
Two dimensional arrays and pointersTwo dimensional arrays and pointers
Chapter 15: POINTERS
Chapter 15: POINTERS
What is a Pointer?
o A pointer is a variable which contains the address in memory of
another variable. We can have a pointer to any variable type.
8/12/2019 c Study Material
167/201
o Pointers are basically the same as any other variable. However,
what is different about them is that instead of containing actual
information, they contain a pointer to the memory location where
information can be found. This is a very important concept, andmany programs and ideas rely on pointers to be able to carry out
their tasks, linked lists for example.
o So what is a pointer? A pointer is a way to get at another object.Essentially it is a way to grab an instance of an object and then
either pass that instance a message or retreive some data from that
object.
Chapter 15: POINTERS
Chapter 15: POINTERS
oA pointer is actually just an address of where an instance is held in
memory.
The unary or monadic operator & gives the ``address of a variable''.
8/12/2019 c Study Material
168/201
The indirection or dereference operator * gives the ``contents of an
object pointed to by a pointer''.
To declare a pointer to a variable do:
int *pointer;
note: We must associate a pointer to a particular type: You can't
assign the address of a short int to a long int, for instance.
Chapter 15: POINTERS
Chapter 15: POINTERS
It is worth considering what is going on at themachine levelin memoryto fully understand how pointer work. . Assume for the sake of this
discussion that variable x resides at memory location 100, y at 200 and
ip at 1000. Note A pointer is a variable and thus its values need to be
8/12/2019 c Study Material
169/201
stored somewhere. It is the nature of the pointers value that isnew.Pointer, Variables and Memory Now the assignments x = 1 and y = 2
obviously load these values into the variables. ip is declared to be a
pointer to an integer and is assigned to the address of x (&x). So ip gets
loaded with the value 100.
Next y gets assigned to thecontents ofip. In this example ip currently
points to memory location 100 -- the location of x. So y gets assigned to
the values of x -- which is 1.
8/12/2019 c Study Material
170/201
Chapter 15: POINTERS
Chapter 15: POINTERS
So ...int *ip; *ip = 100;
will generate an error (program crash!!). The correct use is:
i *i
8/12/2019 c Study Material
171/201
int *ip;
int x;
ip = &x;
*ip = 100;
We can do integer arithmetic on a pointer:
float *flp, *flq;
*flp = *flp + 10;
++*flp;
Chapter 15: POINTERS
Chapter 15: POINTERS
(*flp)++;flq = flp;
note: A pointer to any variable type is an address in memory -- which is
i t dd A i t i d fi it l NOT i t D t i t d
8/12/2019 c Study Material
172/201
an integer address. A pointer is definitely NOT an integer.Data is storedin memory like this :
The reason we associate a pointer to a data type is so that it knows how
many bytes the data is stored in. When we increment a pointer we
increase the pointer by one ``block'' memory.So for a character pointer ++ch_ptr adds 1 byte to the address.
For an integer or float ++ip or ++flp adds 4 bytes to the address.
Consider a float variable (fl) and a pointer to a float (flp)
Pointer Arithmetic Assume that flp points to fl then if we increment thepointer ( ++flp) it moves to the position shown 4 bytes on. If on the other
hand we added 2 to the pointer then it moves 2 float positions i.e 8 bytes
as shown in the Figure.
Chapter 16: STRUCTURES
Chapter 16: STRUCTURES
What are Structures?
What are Structures?
http://../meenakshy%20system%20backup/content%20files/cpage16.jsp8/12/2019 c Study Material
173/201
Referencing elements of a StructureReferencing elements of a Structure
Pointers to StructuresPointers to Structures
Chapter 16: STRUCTURES
Chapter 16: STRUCTURES
Structures are collections of heterogenous elements in continuous
locations of memory having same name.
H ! Thi d i il !
http://../meenakshy%20system%20backup/content%20files/cpage16.jsp8/12/2019 c Study Material
174/201
Hey! This sounds very similar!
Structures are different from arrays only with respect to the type of
elements, ie. homogenous in case of arrays and heterogenous in case of
structures.
Why structures?
An ordinary variable can store one piece of data and an array can store
large number of data but of same data-type. Structure is the data typewhich can store large number of data of different data type. Suppose in
a class there are 60 student, you want to store the name (string), age
(integer), marks (integer) of each student.
Chapter 16: STRUCTURES
Chapter 16: STRUCTURES
This can be done by defining structure variable as follows:struct class
{
char name[20];
int age;
8/12/2019 c Study Material
175/201
int age;int marks;
};
struct student[60];
Now each array element student[i] has memory space corresponding to
three variable name, age and marks.
note: To declare a structure the above group of statement is used. If
you want to add more element to the structure you can very well do it.
Always declare structure outside main() above main().
8/12/2019 c Study Material
176/201
Chapter 16: STRUCTURES
Chapter 16: STRUCTURES
student[1] = student [2]; is same as
student[1].name = student[2].name;
student[1] age = student[2] age;
8/12/2019 c Study Material
177/201
student[1].age = student[2].age;
student[1].marks = student[2].marks
Chapter 16: STRUCTURES
Chapter 1