CSC231 Programming Language
CSC231 Programming Language
Page 1 of 115
3. Structured Programming: C supports structured programming concepts, such as
functions, loops, and conditionals, which allow for better modularity and code
organization.
4. Low-Level Manipulation: C provides direct access to memory through pointers, making it
suitable for system-level programming and for tasks requiring fine control over memory.
5. Rich Standard Library: The C Standard Library includes numerous functions for handling
input, output, memory allocation, and more, making it versatile for various programming
needs.
Fundamentals of C Programming
To understand C programming, it is essential to grasp its fundamental concepts, which form the
basis of writing effective C programs.
1. Data Types and Variables:
o Data Types: C provides basic data types such as int (integer), float (floating-point
number), char (character), and double (double-precision floating point). These
data types define the kind of data that can be stored and manipulated within a
program.
o Variables: Variables in C are named memory locations that store data values. They
must be declared with a specific data type before use.
2. Operators:
o C supports various operators for arithmetic operations (+, -, *, /), relational
operations (==, !=, <, >), logical operations (&&, ||), and bitwise operations (&, |,
^), among others. These operators enable complex calculations and conditions
within programs.
3. Control Structures:
o C offers several control structures, including conditional statements (if, else,
switch), loops (for, while, do-while), and jump statements (break, continue,
return). These structures allow the programmer to dictate the flow of execution in
the program.
4. Functions:
o Functions in C promote modular programming by allowing repetitive code to be
encapsulated into reusable units. A function is defined with a return type, name,
and parameter list, and it can be called from other parts of the program to perform
specific tasks.
Page 2 of 115
5. Pointers:
o Pointers are a critical feature of C that provide a way to directly access and
manipulate memory addresses. This capability is essential in systems
programming and is often used for dynamic memory allocation, efficient array
handling, and implementing data structures like linked lists.
6. Arrays and Strings:
o Arrays in C are used to store collections of data of the same type, providing a way
to handle large amounts of similar data efficiently. Strings are essentially arrays of
characters, terminated by a null character (\0), and are commonly used to handle
text data in C.
7. Structures and Unions:
o Structures: Structures in C are user-defined data types that group different types
of data under one name. They allow for the creation of more complex data types,
such as records that contain multiple data fields.
o Unions: Unions are similar to structures but allow storing different data types in
the same memory location, meaning only one of the members can hold a value at
any given time.
8. Dynamic Memory Allocation:
o C provides standard library functions like malloc, calloc, realloc, and free for
dynamic memory allocation, allowing memory to be allocated at runtime. This is
crucial for creating flexible data structures and managing memory usage
efficiently.
9. File Handling:
o C enables file operations through standard I/O functions such as fopen, fclose,
fread, fwrite, fprintf, and fscanf. File handling allows programs to read, write, and
manipulate external files, which is essential for data persistence.
Significance of C in Modern Computing
Despite its age, C remains a highly relevant language today. Many programming languages,
including C++, Java, and Python, have borrowed syntax and concepts from C. Its efficiency makes
it ideal for systems programming and embedded systems, where direct hardware interaction is
required. Furthermore, operating systems like UNIX, Linux, and Windows have core components
written in C, emphasizing its foundational role in computing.
C’s syntax and control structures have influenced modern languages, making it an ideal language
for students to learn as a stepping stone to other languages. It serves as an excellent language for
Page 3 of 115
understanding how computers manage memory, execute code, and perform at a low level,
making it invaluable in computer science education.
However, the C programming language is not only historical but fundamental to modern
computing. Understanding its history and fundamentals equips students with essential
programming skills and a deeper appreciation of computer architecture and software
development. From systems programming to high-level application development, C continues to
be a powerful tool, providing a solid foundation for anyone entering the field of programming or
computer science.
Page 4 of 115
Example: Ebay on Internet
COMPUTER LANGUAGES
To write a program (tells what to do) for a computer, we must use a computer language.
Over the years computer languages have evolved from machine languages to natural languages.
The following is the summary of computer languages
1940‘s -- Machine Languages
1950‘s -- Symbolic Languages
1960‘s -- High Level Languages
Machine Language
In the earliest days of computers, the only programming languages available were
machine languages. Each computer has its own machine language which is made of streams of
0‘s and 1‘s. The instructions in machine language must be in streams of 0‘s and 1‘s. This is also
referred as binary digits. These are so named as the machine can directly understood the
programs
Advantages:
1) High speedexecution
2) The computer can understood instructionsimmediately
3) No translation is needed.
Disadvantages:
1) Machinedependent
2) Programming is verydifficult
3) Difficult tounderstand
4) Difficult to write bug freeprograms
5) Difficult to isolate anerror
Page 5 of 115
Example Additon of two numbers
2 →0010
+ 3 →0011
5 0101
Page 6 of 115
High-Level Languages
The symbolic languages greatly improved programming efficiency they still
required programmers to concentrate on the hardware that they were using working with
symbolic languages was also very tedious because each machine instruction had to be
individually coded. The desire to improve programmer efficiency and to change the focus from
the computer to the problems being solved led to the development of high-level languages.
High-level languages are portable to many different computer allowing the programmer
to concentrate on the application problem at hand rather than the intricacies of thecomputer.
C A systems implementation Language
C++ C with object oriented enhancements
JAVA Object oriented language for internet and general applications using basic C syntax
Advantages:
1) Easy to write andunderstand
2) Easy to isolate anerror
3) Machine independentlanguage
4) Easy tomaintain
5) Better readability
6) Low Development cost
7) Easier todocument
8) Portable
Disadvantages:
1) Needstranslator
2) Requires high executiontime
3) Poor control onhardware
4) Less efficient
Example: C language
#include<stdio.h>
void main()
{
int a,b,c;
scanf("%d%d%",&a,&b);
Page 7 of 115
c=a+b;
printf("%d",c);
}
Language Translators
These are the programs which are used for converting the programs in one language into
machine language instructions, so that they can be excuted by the computer.
Page 8 of 115
The executable program is stored in a disk for The executable program is generated in RAM
future use or to run it in another computer and the interpreter is required for each run of
the program
The compiled programs run faster The Interpreted programs run slower
Most of the Languages use compiler A very few languages use interpreters.
Page 9 of 115
TEXT EDITOR
(Source code)
COMPILER
(Error correction, memory
allocation, object code)
Library LINKE
R
RUNNER
(Execution,
exe. code)
OUTPUT
Page 10 of 115
Compiling Programs
The code in a source file stored on the disk must be translated into machine language.
This is the job of the compiler. The Compiler is a computer program that translates the source
code written in a high-level language into the corresponding object code of the low-level
language. This translation process is called compilation. The entire high level program is
converted into the executable machine code file. The Compiler which executes C programs is
called as C Compiler. Example Turbo C, Borland C, GC etc.,
The C Compiler is actually two separate programs:
The Preprocessor
The Translator
The Preprocessor reads the source code and prepares it for the translator. While preparing the
code, it scans for special instructions known as preprocessor commands. These commands tell
the preprocessor to look for special code libraries. The result of preprocessing is called the
translationunit.
After the preprocessor has prepared the code for compilation, the translator does the
actual work of converting the program into machine language. The translator reads the
translation unit and writes the resulting object module to a file that can then be combined with
other precompiled units to form the final program. An object module is the code in the machine
language.
Linking Programs
The Linker assembles all functions, the program‘s functions and system‘s functions into
one executable program.
Executing Programs
To execute a program we use an operating system command, such as run, to load the
program into primary memory and execute it. Getting the program into memory is the function
ofanoperatingsystemprogramknownastheloader.Itlocatestheexecutableprogramand
Page 11 of 115
reads it into memory. When everything is loaded the program takes control and it begin
execution.
ALGORITHM
Algorithm is a finite sequence of instructions, each of which has a clear meaning and can be
performed with a finite amount of effort in a finite length of time. No matter what the input
values may be, an algorithm terminates after executing a finite number of instructions.
We represent an algorithm using a pseudo language that is a combination of the constructs of a
programming language together with informal English statements.
The ordered set of instructions required to solve a problem is known as an algorithm.
The characteristics of a good algorithm are:
4Definiteness -
5 Effectiveness–
3 Finiteness – the algorithm stops after a finite number of instructions areexecuted. The
program must be terminated.
1 Input – the algorithm receives input.
2 Output – the algorithm must producesoutput.
Example
Q. Write a algorithem to find out number is odd or even?
Ans.
step 1 : start
step 2 : inputnumber
step 3 : rem=number mod 2
step 4 : if rem=0then
print "number even"
else
print "number odd"
endif
step 5 :stop
FLOWCHART
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing
program and explaining program to others.
Page 12 of 115
Symbols Used In Flowchart
Different symbols are used for different states in flowchart, For example: Input/Output and
decision making has different symbols. The table below describes all the symbols that are used in
making flowchart
Page 13 of 115
Draw flowchart to find the largest among three different numbers entered by user.
INTRODUCTION TO C LANGUAGE
C is a general-purpose high level language that was originally developed by Dennis Ritchie for
the Unix operating system. It was first implemented on the Digital Eqquipment Corporation
PDP-11 computer in 1972.
Page 14 of 115
The Unix operating system and virtually all Unix applications are written in the C language. C
has now become a widely used professional language for various reasons.
• Easy tolearn
• Structuredlanguage
• It produces efficientprograms.
• It can handle low-levelactivities.
• It can be compiled on a variety ofcomputers.
Facts about C
• C was invented to write an operating system calledUNIX.
• C is a successor of B language which was introduced around1970
• The language was formalized in 1988 by the American National Standard Institue
(ANSI).
• By 1973 UNIX OS almost totally written inC.
• Today C is the most widely used System ProgrammingLanguage.
• Most of the state of the art software have been implemented usingC
Why to use C?
C was initially used for system development work, in particular the programs that make-up the
operating system. C was adoped as a system development language because it produces code that
runs nearly as fast as code written in assembly language. Some examples of the use of C might
be:
• OperatingSystems
• LanguageCompilers
• Assemblers
• Text Editors
• PrintSpoolers
• NetworkDrivers
• ModernPrograms
• DataBases
• LanguageInterpreters
• Utilities
C ProgramFile
Page 15 of 115
All the C programs are writen into text files with extension ".c" for example hello.c. You can use
"vi" editor to write your C program into a file.
HISTORY TO C LANGUAGE
C is a general-purpose language which has been closely associated with the UNIXoperating
system for which it was developed - since the system and most of the programs that run it are
written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards.
The influence of BCPL on C proceeded indirectly through the language B, which was written by
Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DECPDP-
7. BCPL and B are "type less" languages whereas C provides a variety of datatypes.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C
ProgrammingLanguage by Kernighan & Ritchie caused a revolution in the computing world.
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.
Page 16 of 115
1. Documentation section: The documentation section consists of a set of comment lines
giving the name of the program, the author and other details, which the programmer
would like to uselater.
2. Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #includedirective.
3. Definition section: The definition section defines all symbolic constants such using
the #definedirective.
4. 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-definedfunctions.
5. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executablepart
1. Declaration part: The declaration part declares all the variablesused in the
executablepart.
2. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program
executionbegins 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 asemicolon.
6. Subprogram section: If the program is a multi-function programthen the subprogram
section contains all theuser-defined functionsthat are called in the main () function. User-
defined functions are generally placed immediately after the main () function, although
they may appear in anyorder.
Page 17 of 115
The C Compilation Model
The Preprocessor
The Preprocessor accepts source code as input and is responsible for
• removingcomments
• Interpreting special preprocessor directives denoted by #.
Forexample
• #include -- includes contents of a named file. Files usually called header files.e.g
o #include <math.h> -- standard library mathsfile.
o #include <stdio.h> -- standard library I/Ofile
• #define -- defines a symbolic name or constant. Macrosubstitution.
o #define MAX_ARRAY_SIZE100
C Compiler
The C compiler translates source to assembly code. The source code is received from the
preprocessor.
Assembler
The assembler creates object code. On a UNIX system you may see files with a .o suffix
(.OBJ on MSDOS) to indicate object code files.
Link Editor
If a source file references library functions or functions defined in other source files the link
editor combines these functions (with main()) to create an executable file.
Page 18 of 115
C TOKENS
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
Each and every smallest individual unit in a C program is known as C tokens.
C tokens are of six types. They are
Keywords (eg: int,while),
Identifiers (eg: main,total),
Constants (eg: 10,20),
Strings (eg: ―total‖,―hello‖),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)
C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names.
The list of C keywords is given below:
volatile while
Page 19 of 115
C IDENTIFIERS
Identifiers are used as the general terminology for the names of variables, functions and arrays.
These are user defined names consisting of arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore (_).
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain whitespace.
It should be up to 31 characters long as only first 31 characters aresignificant.
Some examples of cidentifiers:
Name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword
C CONSTANTS
A C constant refers to the data items that do not change their value during the program
execution. Several types of C constants that are allowed in C are:
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign.
Example of valid decimal integer constants
341, -341, 0,8972
Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal integer constants.
Page 20 of 115
Example of valid octal integer constants
010, 0424, 0,0540
Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits preceded by 0x or
0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used in programming.
Real Constants
The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Representing a real constant in exponent form
The general format in which a real number may be represented in exponential or scientific form
is
mantissa e exponent
The mantissa must be either an integer or a real number expressed in decimal notation.
The letter e separating the mantissa and the exponent can also be written in uppercase i.e. E
And, the exponent must be an integer.
Examples of valid real constants in exponent form are:
252E85, 0.15E-10,-3e+8
Character Constants
A character constant contains one single character enclosed within single quotes.
Examples of valid character constants
‗a‘ , ‗Z‘,‗5‘
It should be noted that character constants have numerical values known as ASCII values, for
example, the value of ‗A‘ is 65 which is its ASCII value.
Escape Characters/ Escape Sequences
Page 21 of 115
C allows us to have certain non graphic characters in character constants. Non graphic characters
are those characters that cannot be typed directly from keyboard, for example, tabs, carriage
return, etc.
These non graphic characters can be represented by using escape sequences represented by a
backslash() followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a single character.
Escape Sequence Description
a Audible alert(bell)
b Backspace
f Form feed
n New line
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash
― Double quotation mark
‗ Single quotation mark
? Question mark
Null
STRING CONSTANTS
String constants are sequence of characters enclosed within double quotes. For example,
―hello‖
―abc‖
―hello911‖
Everystingconstantisautomaticallyterminatedwithaspecialcharacter„‟calledthenull
character which represents the end of thestring.
For example, ―hello‖will represent ―hello‖in thememory.
Thus, the size of the string is the total number of characters plus one for the null character.
Page 22 of 115
Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be
used for some other purpose.
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −
Type Description
Page 23 of 115
C programming language also allows defining various other types of variables like
Enumeration, Pointer, Array, Structure, Union,etc.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable.
A variable definition specifies a data type and contains a list of one or more variables of that
type as follows−
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows−
Page 24 of 115
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the
given type and name so that the compiler can proceed for further compilation without requiring
the complete detail about the variable. A variable definition has its meaning at the time of
compilation only; the compiler needs actual variable definition at the time of linking the
program. A variable declaration is useful when multiple files are used.
4 Logical operators
These operators are used to perform logical
Page 25 of 115
operations on the given two variables.
ARITHMETIC OPERATORS IN C
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.
Arithmetic
S.no Operators Operation Example
1 + Addition A+B
2 – Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
Page 26 of 115
#include
<stdio.h>int
main()
add =a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
OUTPUT:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
ASSIGNMENT OPERATORS IN C
In C programs, values for the variables are assigned using assignment operators.
For example, if the value ―10‖ is to be assigned for the variable ―sum‖, it can be assignedas
―sum= 10;‖
Page 27 of 115
Operators Example Explanation
Simple
assignment 10 is assigned
operator = sum = 10 to variable sum
This is same as
-= sum -= 10 sum = sum – 10
This is same as
/+ sum /= 10 sum = sum / 10
This is same as
sum %= sum = sum %
%= 10 10
This is same as
sum = sum &
&= sum&=10 10
Compound
assignment sum ^= This is same as
operators ^= 10 sum = sum ^ 10
Page 28 of 115
# include <stdio.h>
int main()
int Total=0,I = 5;
for(i=0;i<10;i++)
}
Total += I;
Printf (“Total = %d”, Total);
Total *=I;
Printf (“Total= %d”, Total);
} [ o/p= Total = 5 Total = 25]
}
RELATIONAL OPERATORS IN C
}}]
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a Cprogram.
OUTPUT:
Total = 45
x is greater than
1 > x>y y
Page 29 of 115
2 < x<y x is less than y
x is greater than
3 >= x >= y or equal to y
x is less than or
4 <= x <= y equal to y
Page 30 of 115
5 == x == y x is equal to y
x is not equal to
6 != x != y y
int main()
int m=40,n=20;
if (m == n)
else
OUTPUT:
Page 31 of 115
LOGICAL OPERATORS IN C
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).
It returns true
when both
logical conditions
1 && AND (x>5)&&(y<5) aretrue
It returns true
when at-least
one of the
logical condition is
2 || OR (x>=10)||(y>=10) true
It reverses the
state of the
operand
―((x>5)&&
(y<5))‖
If―((x>5)
&& (y<5))‖
is true,
logical NOT
logical operator
3 ! NOT !((x>5)&&(y<5)) makes itfalse
int main()
Page 32 of 115
int m=40,n=20;
int o=20,p=30;
if (o>p || p!=20)
else
OUTPUT:
In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
Page 33 of 115
&& operator – ―if clause‖ becomes true only when both conditions (m>n and m! =0) is true.
Else, it becomes false.
||Operator – ―if clause‖ becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
! Operator – It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by ―!‖
operator.
So, ―! (m>n and m!=0)‖returns false(0).
x x
& ^
x y x|y y y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
Consider x=40 and y=80. Binary form of these values are givenbelow.
x =00101000
y= 01010000
Page 34 of 115
All bit wise operations for x and y are given below.
x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x = 11111111111111111111111111 11111111111111111111111111111111010111
.. ..= -41 (decimal)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80(decimal)
x >> 1 = 00010100 (binary) = 20(decimal)
Note:
Bit wise NOT: Value of 40 in binary
is0000000000000000000000000000000000000000000000000010100000000000. So, all 0‘s are
converted into 1‘s in bit wise NOT operation.
Bit wise left shift and right shift : In left shift operation ―x << 1 ―, 1 means that the bitswill be
left shifted by one place. If we use it as ―x << 2 ―, then, it means that the bitswill be left shifted
by 2 places.
int main()
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
Page 35 of 115
printf("XOR_opr value = %d\n",XOR_opr );
OUTPUT:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
<stdio.h>int
main()
int x=1, y;
y = ( x ==1 ? 2 : 0 ) ;
Page 36 of 115
}
OUTPUT:
x value is 1
y value is 2
C – Increment/decrement Operators
PREVNEXT
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in Cprograms.
Syntax:
Increment operator: ++var_name ;( or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++i; i ++ ;
Decrement operator : – – i ; i – – ;
EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C
In this program, value of ―i‖ is incremented one by one from 1 up to 9 using ―i++‖ operator and
output is displayed as ―1 2 3 4 5 6 7 8 9‖.
//Example for increment operators
#include <stdio.h>
int main()
int i=1;
while(i<10)
printf("%d ",i);
i++;
Page 37 of 115
OUTPUT:
123456789
#include <stdio.h>
int main()
int i=20;
while(i>10)
printf("%d ",i);
i--;
OUTPUT:
20 19 18 17 16 15 14 13 12 11
1 Pre increment
++i Value of i is
Page 38 of 115
incremented before
assigning it to variable
i.
Value of i is
incremented after
i++ assigning it to variable
2 Post–increment i.
Value of i is
decremented before
— –i assigning it to variable
3 Pre decrement i.
Value of i is
decremented after
i– — assigning it to variable
4 Post_decrement i.
#include <stdio.h>
int main()
int i=0;
while(++i < 5 )
printf("%d ",i);
return 0;
Page 39 of 115
OUTPUT:
1234
int main()
int i=0;
while(i++ < 5 )
printf("%d ",i);
return 0;
OUTPUT:
12345
Page 40 of 115
EXAMPLE PROGRAM FOR PRE – DECREMENT OPERATORS IN C
#include <stdio.h>
int main()
int i=10;
while(--i > 5 )
printf("%d ",i);
return 0;
OUTPUT:
9876
int main()
int i=10;
while(i-- > 5 )
Page 41 of 115
printf("%d ",i);
return 0;
OUTPUT:
98765
SPECIAL OPERATORS IN C:
Below are some of special operators that C language offers.
Example : * a where, * is
2 * pointer to the variablea.
Page 42 of 115
EXAMPLE PROGRAM FOR & AND * OPERATORS IN C
Inthisprogram,―&‖symbolisusedtogettheaddressofthevariableand―*‖symbolis used to get the
value of the variable that the pointer is pointing to. Please refer C –pointer topic to know
more aboutpointers.
#include <stdio.h>
int main()
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
OUTPUT:
50
#include <limits.h>
int main()
int a;
char b;
Page 43 of 115
float c;
doubled;
return0;
OUTPUT:
EXPRESSIONS
Arithmetic expression in C is a combination of variables, constants and operators written in a
proper syntax. C can easily handle any complex mathematical expressions but these
mathematical expressions have to be written in a proper syntax. Some examples of mathematical
expressions written in proper syntax of C are
Note: C does not have any operator for exponentiation.
C operators in order of precedence (highest to lowest). Their associativity indicates in what order
operators of equal precedence in an expression are applied.
Operator Description Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
Page 44 of 115
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
*/% Multiplication/division/modulus left-to-right
+- Addition/subtraction left-to-right
<<>> Bitwise shift left, Bitwise shift right left-to-right
<<= Relational less than/less than or equal to left-to-right
>>= Relational greater than/greater than or equal to
==!= Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+=-= Addition/subtraction assignment
*=/= Multiplication/division assignment
%=&= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<=>>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
Note1:
Parentheses are also used to group sub-expressions to force a different
precedence; such parenthetical expressions can be nested and are
evaluated from inner to outer.
Note2:
Postfix increment/decrement have high precedence, but the actual
increment or decrement of the operand is delayed (to be accomplished
sometime before the statement completes execution). So in the
statement y = x * z++; the current value of z is used to evaluate the
expression (i.e., z++ evaluates to z) and z only incremented after all else
is done.
Page 45 of 115
EVALUATION OF EXPRESSION
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the
arithmetic expression is evaluated from left to right. There are two priority levels of operators in
C.
High priority: * /%
Low priority: + -
The evaluation procedure of an arithmetic expression includes two left to right passes through
the entire expression. In the first pass, the high priority operators are applied as they are
encountered and in the second pass, low priority operations are applied as they are encountered.
Suppose, we have an arithmetic expression as:
x = 9 – 12 / 3 + 3 *2 -1
This expression is evaluated in two left to right passes as:
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets changed.
For example,
x = 9 – 12 / (3 + 3) * (2 –1)
When parentheses are present then the expression inside the parenthesis are evaluated first from
left to right. The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Page 46 of 115
Step 3:x=7
There may even arise a case where nested parentheses are present (i.e. parenthesis inside
parenthesis). In such case, the expression inside the innermost set of parentheses isevaluated
first and then the outer parentheses are evaluated.
For example, we have an expression as:
x = 9 – ((12 / 3) + 3 * 2) –1
The expression is now evaluated as:
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2
Note: The number of evaluation steps is equal to the number of operators in the arithmetic
expression.
Page 47 of 115
Else, if either of the operand is float, then others are converted to float.
Else, if either of the operand is unsigned long int, then others will be converted to unsigned long
int.
Else, if one of the operand is long int, and the other is unsigned int, then
if a long int can represent all values of an unsigned int, the unsigned int is converted to long int.
otherwise, both operands are converted to unsigned long int.
Else, if either operand is long int then other will be converted to long int.
Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on left side
of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to float
causes rounding of digits and the conversion of long int to int causes dropping of excess higher
order bits.
Page 48 of 115
FORMATTED INPUT AND OUTPUT
The C Programming Language is also called the Mother of languages. The C language was
developed by Dennis Ritchie between 1969 and 1973 and is a second and third generation of
languages. The C language provides both low and high level features it provides both the power
of low-level languages and the flexibility and simplicity of high-level languages.
C provides standard functions scanf() and printf(), for performing formatted input and output.
These functions accept, as parameters, a format specification string and a list of variables.
The format specification string is a character string that specifies the data type of each variable to
be input or output and the size or width of the input and output.
Now to discuss formatted output in functions.
Formatted Output
The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the parameters
to the printf() function.
Syntax:
printf (format,data1,data2,… ....... );
In this syntax format is the format specification string. This string contains, for each variable to
be output, a specification beginning with the symbol % followed by a character called the
conversion character.
Example:
printf (―%c‖, data1);
The character specified after % is called a conversion character because it allows one data type to
be converted to another type and printed.
See the following table conversion character and their meanings.
Conversion Meaning
Character
D The data is converted to decimal (integer)
C The data is taken as a character.
S The data is a string and character from the string , are printed until a NULL,
character is reached.
Page 49 of 115
F The data is output as float or double with a default Precision 6.
Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)
Example
printf (―%c\n‖,data1);
The format specification string may also have text.
Example
printf (―Character is:‖%c\n‖, data1);
The text "Character is:" is printed out along with the value of data1.
Example with program
#include<stdio.h>#inclu
de<conio.h> Main()
{
Char alphabh="A";
int number1= 55;
float number2=22.34;
printf(―char= %c\n‖,alphabh);
printf(―int= %d\n‖,number1);
printf(―float= %f\n‖,number2);
getch();
clrscr();
retrun 0;
}
Output Here…
char =A
int= 55
flaot=22.340000
Page 50 of 115
What is the output of the statement?
printf(―Integer is: %d; Alphabet is:%c\n‖,number1, alpha); Where
number1 contains 44 and alpha contains "Krishna Singh". Give
the answer below.
Between the character % and the conversion character, there may be:
• A minus sign: Denoting left adjustment of thedata.
• A digit: Specifying the minimum width in which the data is to be output, if the data hasa
larger number of characters then the specified width occupied by the output is larger. If
the data consists of fewer characters then the specified width, it is padded to the right or
to the left (if minus sign is not specified) with blanks. If the digit is prefixed with a zero,
the padding is done with zeros instead ofblanks.
• A period: Separating the width from the nextdigit.
• A digit following the period: specifying the precision (number of decimal placesfor
numeric data) or the maximum number of characters to beoutput.
• Letter 1: To indicate that the data item is a long integer and not anint.
Page 51 of 115
|%15.5s| ―Outputsting‖ |Output|
|%f| 87.65 |87.650000|
|%.4.1s| 87.65 |87.71|
Page 52 of 115
respectively. This is how data names are specified in a scnaf() function. In case of string type
data names, the data name is not preceded by the character &.
Example with program
Write a function to accept and display the element number and the weight of a proton. The
element number is an integer and weight is fractional.
Solve here:
#include<stdio.h>
#include<conio.h>
main()
{
Inte_num;
Floate_wt;
printf(―EntertheElementNo.andWeightofaProton\n‖);
scanf(―%d %f‖,&e_num,&e_wt);
printf (―The Element No.is:‖,e_num);
printf(―TheWeightofaProtonis:%f\n‖,e_wt);
getch();
return 0;
}
Page 53 of 115
UNIT-II
CONTROL STRUCTURES, ARRAYS AND STRINGS
DECISION STATEMENTS
If statement:
Syntax :
if(expression)
statement1;
Explanation :
• Expression is BooleanExpression
• It may have true or falsevalue
Meaning of If Statement :
• It Checks whether the given Expression is Boolean or not !!
• If Expression is True Then it executes the statement otherwise jumps tonext_instruction
Sample Program Code :
void main()
{
int a=5,b=6,c;
c=a+b;
Page 54 of 115
if (c==11)
{
printf("Execute me 1");
}
printf("Execute me 2");
}
Output :
Execute me1
If Statement:
if(conditional)
{
Statement No1
Statement No2
Statement No3
.
.
.
Statement No N
}
Note :
More than One Conditions can be Written inside If statement.
1. Opening and Closing Braces are required only when ―Code‖after if statement
occupies multiplelines.
if(conditional)
Statement No 1
Statement No2
Statement No3
In the above example only Statement 1 is a part of if Statement.
1. Code will be executed if condition statement isTrue.
2. Non-Zero Number Inside if means “TRUECondition”
if(100)
printf("True Condition");
if-else Statement :
Page 55 of 115
We can use if-else statement in c programming so that we can check any condition and
depending on the outcome of the condition we can follow appropriate path. We have true path as
well as false path.
Syntax :
if(expression)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}
next_statement;
Explanation :
If expression is True then Statement1 and Statement2 are executed
Otherwise Statement3 and Statement4 are executed.
Sample Program on if-else Statement :
void main()
{
int marks=50;
if(marks>=40)
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}
Output :
Student is Pass
Flowchart : If Else Statement
Page 56 of 115
Consider Example 1 with Explanation:
Consider Following Example –
int num = 20;
if(num ==20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True.
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}<math.h>
Res = Sqrt(x);
Page 57 of 115
Consider Example 2 with Explanation :
Page 58 of 115
More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;
if(num ==20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True.
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
Else Part executed if Condition Statement is False.
Page 59 of 115
else
{
printf("False Block");
}
More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;
Switch statement
Why we should use Switch Case?
• One of the classic problem encountered innested if-else / else-if ladderis
calledproblem ofConfusion.
• It occurs when no matching else is available for if.
• As the number ofalternatives increases the Complexity of programincreases
drastically.
• Toovercomethis,CProvideamulti-waydecisionstatementcalled‗Switch
Statement‗
See how difficult is this scenario?
if(Condition 1)
Statement 1
else
{
Statement 2
if(condition 2)
{
if(condition 3)
Page 60 of 115
statement 3
else
if(condition 4)
{
statement 4
}
}
else
{
statement 5
}
}
First Look of Switch Case
switch(expression)
{
case value1 :
body1
break;
case value2 :
body2
break;
case value3 :
body3
break;
default :
default-body
break;
}
next-statement;
Flow Diagram:
Page 61 of 115
How it works?
• Switch case checks the value of expression/variable against the list of case values and
when the match is found ,the block of statement associated with that case isexecuted
• Expression should be IntegerExpression / Character
• Break statement takescontrol out of thecase.
• Break Statement isOptional.
#include<stdio.h>
void main()
{
int roll = 3 ;
switch ( roll )
{
case 1:
printf ( " I am Pankaj ");
break;
case 2:
printf ( " I am Nikhil ");
break;
case 3:
printf ( " I am John ");
break;
default :
printf ( "No student found");
break;
}
}
As explained earlier –
3 is assigned to integer variable ‗roll‗
On line 5 switch case decides – ―We have to execute block of code specified in 3rd case―.
Switch Case executes code from top to bottom.
It will now enter into first Case [i.e case 1:]
It will validate Case numberwith variable Roll. If
no match found then it will jump to NextCase..
When it finds matching case it will execute block of code specified in that case.
Page 62 of 115
initialization;
while(condition)
{
incrementation;
}
Int i=1;
While(i<=5)
{
Printf(“warning”);
Printf(“hello”);
i = i +1;
}
Printf(“this is the end”);
Note :
For Single Line of Code – Opening and Closing braces are not needed.
while(1) is used for Infinite Loop
Initialization , Incrementation and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then
only code is executed ]
Do while:
Do-While Loop Syntax :
initialization;
do
{
Page 63 of 115
incrementation;
}while(condition);
If (m>=60)
Printf(“ist division”);
Elseif(m>=50)
{
Printf(“2nd division”);
Elseif()
Page 64 of 115
Note :
It is Exit Controlled Loop.
Initialization , Incrementation and Condition steps are on different Line.
It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute at least
once ]
For statement:
We have already seen the basics of Looping Statement in C. C Language provides us different
kind of looping statements such as For loop, while loop and do-while loop. In this chapter we
will be learning different flavors of for loop statement.
Different Ways of Using For Loop in C Programming
In order to do certain actions multiple times, we use loop control statements.
For loop can be implemented in different verities of using for loop –
• Single Statement inside For Loop
• Multiple Statements inside ForLoop
• No Statement inside For Loop
• Semicolon at the end of ForLoop
• Multiple Initialization Statement inside For
• Missing Initialization in ForLoop
• Missing Increment/DecrementStatement
• Infinite For Loop
• Condition with no ConditionalOperator.
Int x = 0;
While(x)
Page 65 of 115
Way 1 : Single Statement inside For Loop
for(i=0;i<5;i++)
printf("Hello");
Above code snippet will print Hello word 5 times.
We have single statement inside for loop body.
No need to wrap printf inside opening and closing curly block.
Curly Block is Optional.
i=i+1
Way2:MultipleStatementsinsideForLoop
i=0
for(;i<5;)
{
printf("Statement1");
printf("Statement2");
printf("Statement3");
i++;
if(condition)
{
}
}
If we have block of code that is to be executed multiple times then we can use curly braces to
wrap multiple statement in for loop.
Page 66 of 115
Way 3 : No Statement inside For Loop
for(i=0;i<5;i++)
{
}
thisis bodyless for loop. It is used to increment value of ―i‖.This verity of for loop is not used
generally.
At the end of above for loop value of i will be 5.
Way4:SemicolonattheendofForLoop
for(i=0;i<5;i++);
Generally beginners thought that , we will get compile error if we write semicolon at the end of
for loop.
This is perfectly legal statement in C Programming.
This statement is similar to bodyless for loop. (Way 3)
Way5:MultipleInitializationStatementinsideFor
for(i=0,j=0;i<5;i++)
{
statement1;
statement2;
statement3;
}
Multiple initialization statements must be seperated by Comma in for loop.
Way6:MissingIncrement/DecrementStatement
for(i=0;i<5;)
{
statement1;
statement2;
statement3;
i++;
}
however we have to explicitly alter the value i in the loop body.
Way7:MissingInitializationinForLoop i
= 0;
Page 67 of 115
for(;i<5;i++)
{
statement1;
statement2;
statement3;
}
we have to set value of ‗i‘ before entering in the loop otherwise it will take garbage value of ‗i‘.
Way8:InfiniteForLoop i
= 0;
for(;;)
{
statement1;
statement2;
statement3;
if(breaking condition)
break;
i++;
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.
Form Comment
for ( i=0 ; i < 10;i++) ; For Loop with no Body (Carefully Look at the
Semicolon)
Page 68 of 115
(i=0,j=0;i<100;i++,j++) Update Statements Separated by Comma
Statement1;
JUMP STATEMENTS:
Break statement
Break Statement Simply Terminate Loop and takes control out of the loop.
Page 69 of 115
Way 1 : Do-While Loop
Page 70 of 115
Continue statement:
loop
{
continue;
//code
}
Note :
It is used for skipping part of Loop.
Continue causes the remaining code inside a loop block to be skipped and causes execution to
jump to the top of the loop block
for
Page 71 of 115
while
do-while
Goto statement:
goto label;
label :
Whenever goto keyword encountered then it causes the program to continue on the line , so long
as it is in the scope .
Types of Goto
Forward
Backward
Page 72 of 115
ARRAYS:
What is an array?
An array is a collection of similar datatype that are used to allocate memory in
a sequential manner.
Syntax : <data type><array name>[<size of an array>]
Subscript or indexing: A subscript is property of an array that distinguishes all its stored
elements because all the elements in an array having the same name (i.e. the array name). so to
distinguish these, we use subscripting or indexing option.
e.g. int ar[20];
First element will be: int ar[0];
Second element will be: int ar[1];
Third element will be: int ar[2];
Page 73 of 115
· NOTE: An array always starts from 0indexing.
· Example: intar[20];
This above array will store 20 integer type values from 0 to 19.
Advantage of an array:
· Multiple elements are stored under a single unit.
· Searching is fast because all the elements are stored in asequence.
Types of Array
1. Static Array
2. DynamicArray.
Static Array
An array with fixed size is said to be a static array.
Types of static array:
1. One DimensionalArray
2. Two DimensionalArray.
3. Multi DimensionalArray.
1. One DimensionalArray
An Array of elements is called 1 dimensional, which stores data in column or row form.
Example: int ar[5];
This above array is called one dimensional array because it will store all the elements in
column or in row form
2. Two DimensionalArray.
An array of an array is said to be 2 dimensional array , which stores data in column androw form
Page 74 of 115
NOTE: In above example of two dimensional array, we have total of 20 elements.
Page 75 of 115
3. Multi DimensionalArray.
This array does not exist in c and c++.
Dynamic Array.
This type of array also does not exist in c and c++.
Example: Program based upon array:
WAP to store marks in 5 subjects for a student. Display marks in 2nd and 5thsubject.
#include<stdio.h>
#include<conio.h>
void main()
{
int ar[0];
int
I,x=0;
for(i=0;i<5;i++)
{
printf(“\n Entermarks “,);
scanf(―%d‖,&ar[i]);
}
For(i=1; i<=50;i+)
{
If(a[i] >= 60)
{
X = x+1;
}
Printf(“%d stufents have secured first diition”, x);
}
printf(Marks in 2ndsubject is:‖,ar[1]);
printf(―Marks in 5thsubject is:‖,ar[4]);
}
STRINGS
What is String?
· A string is a collection ofcharacters.
Page 76 of 115
· A string is also called as an array ofcharacters.
· A String must access by %s access specifier in c andc++.
· A string is always terminated with \0 (Null)character.
· Exampleof string:―Gaurav‖
· A string always recognized in doublequotes.
· A string also consider space as acharacter.
Page 77 of 115
· Example: ‖ GauravArora‖
· The above string contains 12characters.
· Example: Charar[20]
· The above example will store 19 character with I nullcharacter.
Example: Program based uponString.
WAP to accept a complete string (first name and last name) and display hello message in the
output.
# include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[20];
char str2[20];
printf(―EnterFirst
Name‖);scanf(―%s‖,&str1);
printf(―Enter last Name‖);
scanf(―%s‖,&str2);
puts(str1);
puts(str2);
}
String Functions in C:
Our c language provides us lot of string functions for manipulating the string.
All the string functions are available in string.h header file.
Page 78 of 115
5. strcat().
6. strapy().
7. strrev().
1. strlen().
This string function is basically used for the purpose of computing the ength of string.
2. strupr().
This string function is basically used for the purpose of converting the case sensitiveness of the
string i.e. it converts string case sensitiveness into uppercase.
3. strlwr().
This string function is basically used for the purpose of converting the case sensitiveness of the
string i.e it converts string case sensitiveness into lowercase.
Example: char str=―gaurav‖
strlwr(str);
printf(―TheLowercaseof thestringis:%s ‖,str);
4. strcmp().
This string function is basically used for the purpose of comparing two string.
This string function compares two strings character by characters.
Thus it gives result in three cases:
Case 1: if first string > than second string then, result will be true.
Page 79 of 115
Case 2: if first string < than second string then, result will be false.
Case 3: if first string = = to second string then, result will be zero.
Example:
char
str1=―Gaurav‖;char
str2=―Arora‖;
char str3=strcmp(str1,str2);
printf(―%s‖,str3);
5. strcat().
This string function is used for the purpose of concatenating two strings ie.(merging two or more
strings)
Example:
char str1 = ―Gaurav‖;
char str2 = ―Arora‖;
char str3[30];
str3=strcat(str1,str2);
printf(―%s‖,str3);
6. strcpy()
This string function is basically used for the purpose of copying one string into another string.
char str1= ―Gaurav‖;
char str2[20];
str2 = strcpy(str2,str1);
printf(―%s‖,str2);
6. strrev()
This string function is basically used for the purpose of reversing the string.
char str1= ―Gaurav‖;
char str2[20];
Page 80 of 115
str2= strrev(str2,str1);
printf(―%s‖,str2);
# include<stdio.h>
# include<conio.h>
#include<string.h>
void main()
{
char str[20];
char str1[20];
int opt,len;
printf(―\n MAIN MENU‖);
printf(―\n 1. Convert stringinto uppercase‖);
printf(―\n 2. Reversethestring‖);
printf(―\n 3. Copyone stringinto anotherstring‖);
printf(―\n 4.Compute length of string‖);
printf(―Enter string‖);
scanf(―%s‖, &str);
printf(―Enter your choice‖);
scanf(―%d‖,&opt);
switch(opt)
{
case1: strupr(str);
Page 81 of 115
printf(―The string in uppercase is :%s ‖,str);
break;
case2: strrev(str);
printf(―The reverse of string is : %s‖,str);
break;
case3: strcpy(str1,str);
printf(―New copied string is : %s‖,str1);
break;
case4: len=strlen(str);
printf(―The length of the string is : %s‖,len);
break;
default: printf(―Ypuhave entered awrongchoice.‖);
}
Page 82 of 115
UNIT-III
FUNCTIONS
A function is itself a block of code which can solve simple or complex task/calculations.
A function performs calculations on the data provided to it is called "parameter" or "argument".
A function always returns single value result.
Types of function:
1. Built in functions(Libraryfunctions)
a.) Inputting Functions.
b.) Outputting functions.
2. User definedfunctions.
a.)fact();
b.) sum();
Parts of a function:
1. Functiondeclaration/Prototype/Syntax.
2. FunctionCalling.
3. FunctionDefinition.
1.)Function Declaration:
Syntax: <return type ><function name>(<type of argument>)
The declaration of function name, its argument and return type is called function declaration.
Page 83 of 115
The process of writing a code for performing any specific task is called function defination.
Syntax:
<return type><function name>(<type of arguments>)
{
<statement-1>
<statement-2>
return(<vlaue>)
}
Example: program based upon function:
WAP to compute cube of a no. using function.
#include<stdio.h>
#include<conio.h>
void main()
{
int c,n;
int cube(int);
printf("Enter a no.");
scanf("%d",&n);
c=cube(n);
printf("cube of a no. is=%d",c);
}
int cube(int n)
{
c=n*n*n;
return(c);
}
Page 84 of 115
{
int n,f=1;
int fact(int)
printf("Enter a no.");
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int fact(int n)
int f=1;
{
for(int i=n;i>=n;i--)
{
f=f*i;
}
return(f);
}
Recursion
Firstly, what is nested function?
When a function invokes another function then it is called nested function.
But,
When a function invokes itself then it is called recursion.
NOTE: In recursion, we must include a terminating condition so that it won't execute to infinite
time.
Page 85 of 115
{
int n,f;
int fact(int)
printf("Enter a no.");
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int fact(int n)
int f=1;
{
if(n=0)
return(f);
else
return(n*fact(n-1));
}
Passing parameters to a function:
Firstly, what are parameters?
parameters are the values that are passed to a function for processing.
a.) ActualParameters:
These are the parameters which are used in main() function for function calling.
Syntax: <variable name>=<function name><actual argument>
Example: f=fact(n);
Page 86 of 115
Methods of parameters passing:
1.) Call by reference.
2.) Call by value.
Page 87 of 115
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
}
STORAGE CLASSES
Every Variable in a program has memory associated with it.
Memory Requirement of Variables is different for different types of variables.
In C, Memory is allocated & released at different places
Term Definition
A. Wherethevariableisstored:
Storage Classdetermines the location of variable, where it is declared. Variables declared with
auto storage classes are declared inside main memory whereas variables declared with keyword
register are stored inside the CPU Register.
Page 88 of 115
B. Scope ofVariable
Scope of Variable tells compile about the visibility of Variable in the block. Variable may have
Block Scope, Local Scope and External Scope. A scopeis the context within a computer
program in which a variable name or other identifier is valid and can be used, or within which a
declaration has effect.
C. DefaultInitialValueoftheVariable
Whenever we declare a Variable in C, garbage value is assigned to the variable. Garbage Value
may be considered as initial value of the variable. C Programming have different
storageclasseswhich has different initial values such as Global Variable have Initial Value as 0
while the Local auto variable have default initial garbage value.
D. Lifetime ofvariable
Lifetime of the = Time Of variable Declaration - Time of Variable Destruction
Suppose we have declared variable inside main function then variable will be destroyed only
when the control comes out of the main .i.e end of the program.
Storage Memory
Page 89 of 115
Page 90 of 115
Life time Exists as long as Control remains in the
block
Example
void main()
{
auto mum = 20 ;
{
auto num = 60 ;
printf("nNum : %d",num);
}
printf("nNum : %d",num);
}
Output :
Num :60
Num :20
Note :
Two variables are declared in different blocks , so they are treated as different variables
External ( extern ) storage class in C Programming
Page 91 of 115
Storage Memory
Example
int num = 75 ;
void display();
void main()
{
extern int num ;
printf("nNum : %d",num);
display();
}
void display()
{
extern int num ;
printf("nNum : %d",num);
}
Output :
Num :75
Num :75
Note :
Declaration within the function indicates that the function uses external variable
Functions belonging to same source code , does not require declaration (no need to write extern)
If variable is defined outside the source code , then declaration using extern keyword is required
Page 92 of 115
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope. Therefore, making local variables static allows them to maintain their values
between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a class data member, it causes only one copy of that
member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
main() {
while(count--) {
func();
}
return0;
}
/* function definition */
void func( void ) {
Page 93 of 115
Register Storage Class
register keyword is used to define local variable.
Local variable are stored in register instead of RAM.
As variable is stored in register, the Maximum size of variable = Maximum Size of Register
unary operator [&] is not associated with it because Value is not stored in RAM instead it is
stored in Register.
This is generally used for faster access.
Common use is ―Counter―
Syntax
{
register int count;
}
Register storage classes example
#include<stdio.h>
int main()
{
int num1,num2;
register int sum;
return(0);
}
Explanation of program
Refer below animation which depicts the register storage classes –
Page 94 of 115
In the above program we have declared two variables num1,num2. These two variables are
stored in RAM.
Another variable is declared which is stored in register variable.Register variables are stored in
the register of the microprocessor.Thus memory access will be faster than other variables.
If we try to declare more register variables then it can treat variables asAuto storage variablesas
memory of microprocessor is fixed and limited.
Why we need Register Variable ?
Whenever we declare any variable inside C Program then memory will be randomly allocated at
particular memory location.
We have to keep track of that memory location. We need to access value at that memory location
using ampersand operator/Address Operatori.e (&).
If we store same variable in the register memory then we can access that memory location
directly without using the Address operator.
Register variable will be accessed faster than the normal variable thus increasing the operation
and program execution. Generally we use register variable as Counter.
Note : It is not applicable for arrays, structures or pointers.
Summary of register Storage class
Keyword register
Page 95 of 115
Keyword register
Preprocessor directives
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with ―#‖
symbol.
Below is the list of preprocessor directives that C language offers.
Page 96 of 115
condition
#undef is used to
undefine a defined
macro variable.
#Pragma is used to
call a function before
and after main
Other function in a C
4 directives #undef, #pragma program
A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
#include <stdio.h>
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
OUTPUT:
Page 97 of 115
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return0;
}
OUTPUT:
#include <stdio.h>
#define RAJU 100
Page 98 of 115
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program‖);
#endif
return0;
}
OUTPUT:
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return0;
}
OUTPUT:
Page 99 of 115
EXAMPLE PROGRAM FOR UNDEF IN C:
This directive undefines existing macro in the program.
#include <stdio.h>
void function1( );
void function2( );
int main()
{
printf ( "\n Now we are in main function" );
return0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
}
i 5 65524
j 65524 65522
int main()
{
int *ptr, i;
i = 11;
return 0;
}
See Output and Download »
You will get value of i = 11 in the above program.
C. Pointer Declaration Tips:
1. Pointer is declared with preceding *:
int *ptr; //Here ptr is Integer Pointer Variable
int ptr; //Here ptr is Normal IntegerVariable
2. Whitespace while Writing Pointer:
pointer variable name and asterisk can contain whitespace because whitespace is ignored by
compiler.
int *ptr;
int * ptr;
int * ptr;
All the above syntax are legal and valid. We can insert any number of spaces or blanks inside
declaration. We can also split the declaration on multiple lines.
D. Key points for Pointer:
Unline ordinary variables pointer is special type of variable which stores the address of ordinary
variable.
Pointer can only store the whole or integer number because address of any type of variable is
considered as integer.
It is good to initialize the pointer immediately after declaration
& symbol is used to get address of variable
* symbol is used to get value from the address given by pointer.
E. Pointer Summary:
Pointer is Special Variable used to Reference and de-reference memory. (*Will be covered in
upcoming chapter)
int main()
{
int a = 3;
int *ptr;
ptr = &a;
return(0);
}
Explanation of Example :
int main()
{
int a =3;
int *ptr,**pptr;
ptr =&a;
pptr = &ptr;
return(0);
}
Explanation of Example
With reference to above program –
printf("\nAddressofi : %u",&i);
printf("\nValue of ptr is :%u",ptr);
return(0);
}
After declaration memory map will be like this –
int i = 5;
int *ptr;
after Assigning the address of variable to pointer , i.e after the execution of this statement –
ptr =&i;
Explanation :
Pointer Variableis nothing but a memory address which holds another address .
Intheaboveprogram―i‖isnamegivenformemorylocationforhumanunderstanding,but
compilerisunabletorecognize―i‖.Compilerknowsonlyaddress.
In the next chapter we will be learning , Memory requirement for storing pointer variable.
inta; // Step 1
int *ptr; // Step2
return(0);
}
Explanation of Above Program :
Pointer should not be used before initialization.
―ptr‖ispointervariableusedtostoretheaddressofthevariable.
Stores address of the variable„a‟.
Now ―ptr‖ will contain the address of the variable ―a‖ .
Note :
[box]Pointers are always initialized before using it in the program[/box]
Example : Initializing Integer Pointer
#include<stdio.h>
int main()
{
int a = 10;
int *ptr;
ptr =&a;
printf("\nValue of ptr : %u",ptr);
return(0);
}
Output :
Value of ptr : 4001
Pointer arithematic
Incrementing Pointer:
Incrementing Pointer is generally used in array because we have contiguous memory in array and
we know the contents of next memory location.
Incrementing Pointer Variable Depends Upon data type of the Pointer variable
Formula : ( After incrementing )
new value = current address + i * size_of(data type)
Three Rules should be used to increment pointer –
Address++ =Address
++Address =Address
Pictorial Representation :
int main(){
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
int main(){
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
New Value of ptr : 1004
Live Example 3 : Array of Pointer
#include<stdio.h>
int main(){
float var[5]={1.1f,2.2f,3.3f};
float(*ptr)[5];
ptr=&var;
printf("Value inside ptr : %u",ptr);
ptr=ptr+1;
printf("Value inside ptr : %u",ptr);
return 0;
}
Output :
Value inside ptr : 1000
Value inside ptr : 1020
Explanation:
Decrementing a pointer to an integer data will cause its value to be decremented by 2
This differs from compiler to compiler as memory required to store integer vary compiler to
compiler
Pointer Program: Difference between two integer Pointers
#include<stdio.h>
int main(){
printf("\nDifference : %d",ptr2-ptr1);
return 0;
}
Output :
Difference : 250
Explanation :
Ptr1 and Ptr2 are two pointers which holds memory address of Float Variable.
Ptr2-Ptr1 will gives us number of floating point numbers that can be stored.
ptr2 - ptr1 = (2000 - 1000) / sizeof(float)
= 1000 / 4
= 250
Live Example 2:
#include<stdio.h>
struct var{
int main(){
printf("Difference=%d",ptr2-ptr1);
return0;
}
Output:
Difference = 142
Explanation :
ptr2-ptr1 = (2000 - 1000)/Sizeof(struct var)
= 1000 / (1+2+4)
= 1000 / 7
= 142
Adding integer value with Pointer
In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable.
In order to compute the final value we need to use following formulae :
final value = (address) + (number * size of data type)
Consider the following example –
int *ptr , n;
ptr = &n ;
ptr = ptr +3;
Live Example 1 : Increment Integer Pointer
#include<stdio.h>
int main(){