0% found this document useful (0 votes)
30 views174 pages

Brief Introduction To The C Programming Language

C was designed by Dennis Ritchie in the early 1970s at Bell Labs. It was influenced by several other programming languages. C was standardized in 1989 by ANSI and updated in later standards. C is a middle-level language that provides high-level and low-level capabilities. It consists of keywords, variables, data types, statements, and other elements to write programs.

Uploaded by

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

Brief Introduction To The C Programming Language

C was designed by Dennis Ritchie in the early 1970s at Bell Labs. It was influenced by several other programming languages. C was standardized in 1989 by ANSI and updated in later standards. C is a middle-level language that provides high-level and low-level capabilities. It consists of keywords, variables, data types, statements, and other elements to write programs.

Uploaded by

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

Brief Introduction

to the
C Programming Language
HISTORY
• The C programming language was designed by Dennis Ritchie at
Bell Laboratories in the early 1970s
• Influenced by

– ALGOL 60  (ALGOrithmic Language)
(1960),
– CPL (Combined Programming Language)
(Cambridge, 1963),
– BCPL (Basic Combined Programming Language)
(Martin Richard, 1967),
– B (This was derived from BCPL)
(Ken Thompson, 1970)
– C (This was derived from B) (Dennis Ritchie, 1972)

2
Standards of C
• Standardized in 1989 by American National Standards Institute
known as ANSI C

• International standard (ISO) in 1990 which was adopted


by ANSI and is known as C89

• As part of the normal evolution process, the standard was


updated in 1995 (C95) and 1999 (C99)

3
Classification Of Language
Low Level :

Machine Language –Difficult to program, remember the instructions,


maintain and is not portable.
Assembly Language – Difficult to program, remember the instructions,
maintain and is not portable. The only difference
is that the instructions are English like words.
Example : MOV,SUB,ADD etc

High Level : This is designed keeping in mind about portability,


Machine independent and English like language
programming.
> The programmer is not concerned with CPU’s
architecture so he can pay attention on other
logics related to projects.
This High Level language is translated to low level
using tools like compilers/Interpreters.

4
Translators
Translators : It is a computer program that performs the translation of a
program written in a given programming language into a functionally
equivalent program in a different computer language,

Three Types of Translators :


1. Assemblers – Converts assembly to machine code.
2. Interpreters – Converts high level to machine code.
> Interpreter checks for errors and translates one
statement at a time.
3. Compilers - Converts high level to machine code.
> Compiles for errors and translates whole
source code (all statements) into executable code.

5
C language
C is a middle level language, It has the
power of both high level and low level
programming. This is an excellent, efficient and
general purpose language. It is used for most of
such as mathematics, scientific, business and
system software and embedded applications.

It is a small language consisting only 32


keywords. It is yet powerful with built-in library
functions provided with it. User can also create
their own lib functions and maintain them.

6
Elements of a C Program
• A C development environment includes

– System libraries and headers: a set of standard libraries and


their header files.

– Application Source: application source and header files

– Compiler: converts source to object code for a specific platform

– Linker: resolves external references and produces the


executable module

7
Compilation and Execution
Source Code

Preprocessor

Expanded Code

Compiler

Assembly Code

Assembler

Object Code

Linker (Combines the object files)

Executable Code
(Object Code)

8
RULES OF C

Every language has some basic elements, The


same is applicable for even C. It is must to know the basic
rules of C language for writing programs. This basic
elements are char set, variable, data types, constants,
keywords (Reserve words), variable declaration,
expression, statements etc. All these are used to construct
a program.

9
RULES OF C

C KEYWORDS – TOTAL OF 32

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

10
RULES OF C
CHARACTER SET :

Characters : Upper Case (A to Z), Lower Case (a to z),


Digits (0 to 9), graphical characters,
White Space : Space, Newline, Horizontal Tab, Vertical Tab,
Form feed.
Other Characters : Alt, Back space, Carriage Return, Null char.

DE’LIMETERS : A delimiter is a unique character or series of


characters that indicates the beginning or end of a specific statement, string or
function body set.
: Colon
; Semicolon
() Braces
{} Curly/flower Braces
[] Square Braces
# Ash
, Comma

11
RULES OF C
ESCAPE SEQUENCE

Escape Sequence Effect


\a Beep sound
\b Backspace
\f Formfeed (for printing)
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\\ Backslash
\” “ sign
\o Octal decimal
\x Hexadecimal
\O NULL

12
RULES OF C

All words that we will use in C programs will be either keywords or identifiers.

Keywords : Key words are predefined and cannot be used as


identifiers.

Identifiers : Identifiers are user defined words and are used for naming
entities like variables, arrays, functions, structures etc. Rules for naming
identifiers are as follows.
(i) First Character should start with only either lower, upper
case or underscore.
(ii) The name can be combination of lower, upper case
characters, numerical and underscore.
(iii) The name should not be a keyword.
(iv) C is a case sensitive, to the upper case and lower case
letters are considered different. Eg – CASE, Case, case
are three different identifiers.

13
RULES OF C
Data types : There are 4 basic data
types

14
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double

15
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
Qualifiers / Modifiers :

16
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
Qualifiers / Modifiers :
Size qualifier - short.
long.

17
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
Qualifiers / Modifiers :
Size qualifier - short.
long.
Sign qualifier - signed.
unsigned.

18
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
Qualifiers / Modifiers :
Size qualifier - short.
long.
Sign qualifier - signed.
unsigned.
Type qualifier - const.
19
RULES OF C
int
– used to declare numeric program variables of integer type, size in
the memory is 2 or 4 bytes.
– whole numbers, positive and negative
– Keyword : int
– Example : int number; number = 12;

char
– equivalent to ‘letters’ in English language
– Example of characters:
• Numeric digits: 0 - 9
• Lowercase/uppercase letters: a - z and A - Z
• Space (blank)
• Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
– single character
– Size in the memory is 1 byte
– Keyword : char
– Example : char my_letter; my_letter = 'U';

20
RULES OF C

• float
– fractional parts, positive and negative
– keyword: float, size is of 4 bytes.
float height;
height = 1.72;
• double
– used to declare floating point variable of higher precision
or higher range of numbers
– exponential numbers, positive and negative
– keyword: double, size is of 8 or 10 bytes
double value_big;
value_big = 12E-3;

21
RULES OF C
Basic Data Data Types with Size
Range
Type type qualifiers (bytes)
char signed char 1 -128 to 127
Unsigned char 1 0 to 255
int int or signed int 2 -32768 to +32767
unsigned int 2 0 to 65535
short int or
1 -128 to 127
signed short int
Unsigned short int 1 0 to 255
Long int or
4 -2147483648 to 2147483647
Signed long int
Unsigned long int 4 0 to 4294967295
Float Float 4 3.4E -38 to 3.4E +38
Double Double 8 1.7E -308 to 1.7E +308
Long Double 10 3.4E -4932 to 1.1E +4932
22
RULES OF C

Constants

Numerical -- Char -- String

Int --- Real

Decimal -- Oct-Decimal -- Hex-Decimal

23
RULES OF C
CONSTANTS
Char Constant : Character is enclosed in single quotes eg ‘a’
This refers to ASCII Character Set which
contains 256 characters
i.e numbered from 0 to 255.
Example : A-Z (65 – 90), a-z (97 - 122)
0-9 (48 - 57)

String Constant : A String constant is enclosed within double


quotes (“”). At the end of string, the null
character ‘\0’ is automatically placed by the
compiler.
Example : “Kumar”, “2345”, “8”.

Numerical Constant : It is either +ve or –ve.


No space is allowed between digits.
It should have at least one digit.
It may contain decimal or may not.
24
RULES OF C

Numerical Constant

Integer Constant : Three different categories.


Dec – 0-9 (base 10) Eg – 10, 123, 8967
Oct – 0-7 (base 8) Eg – 05,077, 037
Hex – 0-F (base 16) Eg – 0x23,0x2cf,0xff

Real Constant : These contains decimal place values.


Eg : 2.5e9 i.e 2.5x10^9
By default the floating point constant is
double.

25
RULES OF C

Integer Constant

Dec - Base 10

Oct - Base 8

Hex - Base 16

26
RULES OF C

Variables : Associating a data-type to an Identifier is called


variables, It can take different values but one at a time. This values
can be changed during execution time. The data type associated with
variables will decide what type of values can be stored in variable.

Declaration of variable : Associating a data-type to an identifier and


telling compiler to allocate memory is called declaration of variable.
Eg : int a, char name, float percentage

Initialization of variable : At the time of declaration if the variable has


been assigned with a value then it is known as Initialization.
Eg int a = 5;

Expression : a=x+y;

27
RULES OF C

Statements : In a C program, Instructions are written in the form of


statements. A statement is an executable part of the program and causes the
computer to carry out some action. This statement s can categorized as

(a) Selection Statement (if, if..else, switch)


(b) Iterative Statement (for, while, do..while)
(c) Jump Statement (goto, continue, break, return)
(d) Label Statement (case, default, label used for goto)
(e) Expression (x=5, a=b+c, ;)
(f) Compound Statement

Compound Statement : {
Statement 1;
a=b+c;
;
….
Statement n;
}

28
QUESTIONS
Define
Data-type?

Identifier?

Variable?

Initialization?

Name
Size qualifiers?

Type qualifiers?

Signed qualifiers?
29
SAMPLE PROGRAM

#include<stdio.h>

main(void)
{
int sum = 100;
printf(“Hello World \n”);
printf(“The value of sum is : %d”, sum);
}

30
INPUT AND OUTPUT EXAMPLE

#include<stdio.h>

main(void)
{
int a=0, b=0, c=20;
printf(“INPUT A VALUE : ”);
scanf(“%d”,&b); // & simbol is called address operator
a=b+c;
printf(“The sum of b and c is : %d\n”, a);
}

31
Format Specifier for Printf()
%c - Single Char

%d, %i - Decimal integer

%u - Unsigned decimal integer

%o - unsigned Octal

%x - Unsigned Hexadecimal (Lowercase – a,b,c,d,e,f)

%X - Unsigned Hexadecimal (Uppercase – A,B,C,D,E,F)

%f - Floating Point (by default 6 digits after decimal)

%s - String

%p - Pointer in hexadecimal(generally used for displaying


address of variables)
%e - Floating Pointer in exponential format.
32
Format Specifier for Scanf()
%c - Reads a single Char
%d - Reads a signed Decimal integer
%i - Reads a signed integer, base is decided by the prefix of the input number
Reads a signed hexadecimal integer if prefix is 0x
Reads a signed octal integer if prefix is 0
If not prefixed reads a signed decimal integer.
%u - Reads an unsigned decimal integer.
%o - Reads unsigned Octal integer.
%x - Reads unsigned Hexadecimal (Lowercase – a,b,c,d,e,f)
%X - Reads unsigned Hexadecimal (Uppercase – A,B,C,D,E,F)
%f - Reads Floating Point (by default 6 digits after decimal)
%e, %E - Floating Pointer in exponential format.
%g, %G
%s - Reads String

33
Formatted Input and Output
Formatted Integer Input

%wd

Eg : scanf(“%2d %3d”, &a,&b);

Case 1
When input data length is less than or equal to the given field width, the input
values are unaltered and stored in given variables.
Input : 6 394
Output : 6 is stored in a and 394 is stored in b

Case 2
When input data length is more than the given field width, the input values are
altered and stored in the variable as -
Input : 639 456
Output : 63 is stored in a and 9 is stored in b, rest is ignored.

34
Formatted Input and Output
Formatted Integer Output
%wd

Eg : printf(“The variable’s values are %3d %4d”, a, b);

Case 1: When the length of variable is less than the width specified
Value of variables are a = 78, b= 9;
Output is a=_ 78, b=_ _ _ 9 ( underscore symbol are spaces).

Case 2: When the length of variable is equal to the width specified


Value of variables are a = 783, b= 9876;
Output is a=783, b=9876

Case 3: When the length of variable is more then the width specified
Value of variables are a = 7832, b= 987634;
Output is a=7832, b=987634.

35
Formatted Input and Output
Formatted Floating Point Numeric Input

%wf

Eg : scanf(“%3f %4f”, &a, &b);


Here w is the integer number specifying the total width of the data (including
the digits before and after decimal and the decimal itself)

Case 1 When input data length is less than or equal to the given width, values
are unaltered and stored in the variables
Input : 5_5.92 note : underscore is a space.
Output : 5.0 is stored in a and 5.92 is stored in b.

Case 2 When input data length is more than the given width, the entered
values are altered and stored in the given variables.
Input : 5.93_65.875
Output : 5.9 is stored in a and 3.00 is stored in b.

36
Formatted Input and Output
Formatted Floating Point Numeric Output
%wnf
Eg : printf(“a=%4.1f, b= %7.2f”, a, b);
Here w is the integer number specifying the total width of the input data and n
is the number of digits to be pointed after decimal point. By default 6 digits are
printed after the decimal.
If the total length of the variable is less than the specified width w, then the
value is right justified with leading blanks. If the number of digits after decimal
is more than n, the digits are rounded off.
Value of variables : 8 5.9
Output : a=8.0, b=_ _ _5.90
Value of variables : 25.3 1635.92
Output : a=25.3, b=1635.92
Value of variables : 15.231 65.875948
Output : a=15.2, b=_ _65.88

37
Formatted Input and Output
Formatted string input

%ws

Here w specifies the total number of characters that will be stored in the string.
char str[8];
Scanf(“%3s”,str);

Input : Srivastava
Output : ‘s’,’r’,’i‘,’\0’. The null char ‘\0’ is automatically stored at the end

38
Formatted Input and Output
Formatted string output

%w.ns

Here w specifies field width, Decimal point and n, are optional. If present then n
specifies that only first n characters of the string will be displayed and (wn)
leading blanks are displayed before string.

Printf(“%3s”,”sureshkumar”); output : sureshkumar

Printf(“%10s”,”suresh”); output : _ _ _ _suresh

Printf(“%.3s”,”sureshkumar”); output : sur

Printf(“%8.3s”,”sureshkumar”); output : _ _ _ _ _ sur

39
QUESTIONS
What is / Define Name

Data-type Data Types

Identifier Size qualifiers

Variable Type qualifiers

Initialization Signed qualifiers

Keyword

function

main()

printf()

scanf()
40
OPERATORS AND EXPRESSION
An operator specifies an expression to be performed that yields a
value. An operand is a data item on which on operator acts.

Total 9 Operators

1. Arithmetic Operator
2. Assignment Operator
3. Increment and Decrement Operator
4. Relational Operator
5. Logical / Boolean Operator
6. Conditional Operator
7. Comma Operator
8. Size of Operator
9. Bitwise Operator

41
OPERATORS AND EXPRESSION
Arithmetic Operator

(i) Unary arithmetic operator


eg : +x, -y

(ii) Binary arithmetic operator

+ addition
- subtraction
* multiplication
/ division
% modular (gives the reminder in integer division.
This cannot be applied with floating point operators)

42
OPERATORS AND EXPRESSION
Assignment Operator

The value can be stored in a variable using assignment operator :

Eg : a = 5, a = b + c, a=c

Note : Right values has high priority


In case of expression on right, it evaluates first
Right values are stored in left values
Left Value always should be a variable

43
OPERATORS AND EXPRESSION
Increment and Decrement Operator
Increment - ++
Decrement - --
Operator will increment / decrement by 1
They can be used with only variables
Eg : a++, b++
Wrong Eg : 5++, (a+b+5)++
There are two types
Prefix Increment (Pre Increment) - ++a
Prefix Decrement(Pre Decrement) - --a
Postfix Increment (Post Increment) - a++
Postfix Decrement(Post Decrement)- a--
Prefix Postfix
y=++a y=a++
y=--a y=a--

44
OPERATORS AND EXPRESSION
Relational Operator
< less than
<= less than equal to
> Greater than
>= Greater than equal to
== Equal to (Compares two expression)
!= Not equal to
Eg : a=9, b=5
Expression Relation Value of Expression
a<b False 0
a<=b False 0
a==b False 0
a!=b True 1
a>b True 1
a>=b True 1
a==0 False 0
b!=0 True 1
a>8 True 1
2>4 False 0

45
OPERATORS AND EXPRESSION
Logical Operator
&& AND (Binary Operator)
|| OR (Binary Operator)
! NOT (Unary Operator)

Truth Table

AND OR NOT

A B C A B C A !A
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1

46
OPERATORS AND EXPRESSION
Conditional Operator / Ternary Operator

(? and :) which requires three expression as operands.


Syntax : Test Expression ? Expression 1 : Expression 2

First Test Expression is evaluated and then


If Test Expression is true (non zero), then Expression 1 is
executed (or) evaluated and it becomes the value of the overall
conditional expression.

Else Test Expression is false (zero), then Expression 2 is


executed (or) evaluated and it becomes the value of the overall
conditional expression.

eg : a<b ? printf(“a is smaller”) : printf(“b is smaller”);

47
Assignments

1. Print if a is grater or b is greater

2. SUM = (a = 8, b = 7, c = 9, a+b+c)

3. Swapping values of two variables using temp variable


Before swapping : a = 5, b = 10, temp = 0;
After swapping : a = 10, b = 5

4. Check if the num is Even or Odd using modular and ternary operator.

5. Sum and Average of 5 numbers.

48
OPERATORS AND EXPRESSION
Comma Operator
The comma operator is used to permit different expressions to appear
in situations. The expressions are separated by comma operator. The
separated expressions are evaluated from left to right.
Eg int a=5, b=2, c=a+b;

Size of Operator
Size of is an Unary Operator that gives the size of it operator in terms
of bytes. The operand can be a variable, constant or any data type.

Eg : int a
sizeof(a) or sizeof(int);
Generally sizeof() operator is used to make programs as portable.

49
OPERATORS AND EXPRESSION
Bitwise Operator

C has ability to support manipulation of data at the bit level. Bitwise


operation operates integers only and they are used for operation on individual
bits. The bit wise operators are

& Bitwise AND

| Bitwise OR

~ One’s Complement

<< Bitwise Left Shift

>> Bitwise Right Shift

^ Bitwise XOR

50
OPERATORS AND EXPRESSION
Bitwise Operator

~ One’s Complement
Eg : 76543210 76543210
~0==-1 0 0 0 0 0 0 0 0  1 1 1 1 1 1 1 1
~1==-2 0 0 0 0 0 0 0 1  1 1 1 1 1 1 1 0
~3==-4 0 0 0 0 0 1 1 1  1 1 1 1 1 0 0 0
<< Bitwise Left Shift
Eg : 76543210 76543210
1<<3 0000000100001000
4<<3 0000010000100000
7<<3 0000011100111000
>> Bitwise Right Shift
Eg : 76543210 76543210
1>>3 0000000100000000
4>>1 0000010000000010
7>>1 0000011100000011
7>>3 0000011100000000
51
Advanced
Bitwise
Operator

52
Advanced Bitwise Operation
Four advanced bitwise operation.
(i) To check the status of a particular bit.

(ii) Setting a particular bit.

(iii) Clearing a particular bit.

(iv) Toggling a particular bit.

53
Advanced Bitwise Operator
(i) To check the status of a bit :

Eg : (num & (1<<bit_position) == 0) ? printf(“0”) : printf(“1”);

54
Advanced Bitwise Operator
(ii) Setting a particular bit : num = num | (1 << bit_position)
num |=(1<<bit_position)

Eg : a =10 (assume 4th bit is to be set.)


Bit Position :7 6 5 4 3 2 10
1st method : a=10 :00001010
mask value :00011010
00011010
Bit Position :7 6 5 4 3 2 10
2nd method : a=10 :00001010
(1<<4) :00010000
00011010

55
Advanced Bitwise Operator
(iii) Clearing a particular bit : num = num & (~(1 << bit_position))
num &=~(1<<bit_position)

Eg : a =10 (assume 3rd bit is to be clear.)


Bit Position :7 6 5 4 3 2 10
1st method : a=10 :00001010
mask value :11110111
00000010
Bit Position :7 6 5 43 2 1 0
2nd method : a=10 :00001010
~(1<<3) :11110111
00000010

56
Advanced Bitwise Operator
(iv) Toggling a bit : num = num ^ (1<<bit_position)
num ^=(1<<bit_position)

Eg : a =10 (assume 3rd bit is to be clear.)


Bit Position :7 6 5 4 3 2 1 0
1st method : a=10 :00001010
mask value :00001000
00000010
Bit Position :7 6 5 4 3 2 1 0 7 6 5 4 3 2
1 0
2nd method : a=10 :00001010 000000
10
(1<<3) :00001000 000010
00
00000010 000010
10

57
Type Conversions
1. Type Conversion in Assignment Implicit Type

2. Arithmetic Conversion Implicit Type

3. Type Casting Explicit Type

Implicit Type

Highest Rank long double


double
float
long int
int
Lowest Rank char, short int

58
Type Conversions
Implicit Type Conversion in Assignment :

Eg : char C1, C2;


int i1, i2;
float f1, f2;

i1 = 80.56 /* float value is converted to int. only 80 value


is stored in i1 */
c2 = i1 /* int value is converted to char */
f1 = 12.6
i2 = f1 /* only 12 is stored in i2, 0.6 is truncated */

59
Type Conversions
Implicit Type Arithmetic Conversion : When a type conversion is
performed automatically by the compiler without programmer intervention, such
type of conversion is known as implicit type conversion or type promotion.
The compiler converts all operands to type of variable on left side of
assignment operator before assigning value to it.
Eg : int a=5
float b = 6.32
char c = 3
a = b+c
b is float = 6.32
c is char which is converted to float i.e c = 3.000000
result is 9.320000
a is int, so the result is converted to int (i.e 0.320000 is truncated)
Final result a = 9.

60
Type Conversions
Explicit Type Conversion – TYPE CASTING : Type casting in c is done
as follows

Syntax : (data type) expression / operand;

Eg : {
int x=5, y=3;
float p,q;
p = x/y;
printf(“p = %f\n”, p);
q = (float) x/y;
printf(“q = %f\n”, q);
return0;
}

61
C - PRECEDENCE
Eg : a=8, b=4, c=2, d=1,e=5, f=20;

expression = a + b – (c + d) * 3 % e + f / 9
5th : 12 1st : 3 4th : 2

2nd : 9

3rd : 4

6th : 8

7th : 10

62
CONTROL
STATEMENTS

63
CONTROL STATEMENTS

Selection Statements

(i) if . . . . . else
(ii) switch . . . . case

Iterative Statements

(i) for loop


(ii) while loop
(iii) do . . . . . while loop

Jump Statements

(i) break
(ii) continue
(iii) goto

64
if . . . . else statement
This is a selection control statement, which is used to take either one or
more than one possible actions.
Syntax for
Only if if . . . . else Nesting if . . . else
if(expression) if(expression) if(expression-1)
statement-1; statement-1; statement-1;
else else if(expression-2)
statement-2; statement-2
next statement; next statement; else if(expression-3)
statement-3
else
statement-4
next statement;
The expression inside the parentheses is evaluated and if it is true (has
a non-zero value), then the statement-1 is executed and if the expression is false
(zero) then statement-2 is executed

65
if . . . . else Assignment
Write a Program

1. To find Even / Odd of an given value.

2. For analyzing students total marks and display relevant grading.

66
switch . . . . case
This is a selection control statement, which is used to take one of the ‘n’
possible actions.
Syntax for
switch (expression)
{
case constant 1 : statement 1; . . . . statement n;
case constant 2 :
.......
case constant n : statement 1 ; . . . . statement n;
default : statement 1 ; . . . . Statement n;
}
The expression inside the parentheses is evaluated and if it is true (has
a non-zero value), then the statement-1 is executed and if the expression is false
(zero) then statement-2 is executed

67
for loop
This is a control flow statement for specifying iteration, which allows
code to be executed repeatedly for specified number of times.
Syntax for
for(init of exp ; conditional expression ; updating expression)

Eg : int i =0;
for (i=0;i<10;i++)
{
statement-1; statement-2;. . . . . statement-n;
}

68
do . . . while loop
This is a control flow statement for specifying iteration, which allows
code to be executed repeatedly for specified number of times.
Syntax for
do
{
statement-1;
.....
statement-2;
} while(expression);

Eg : int i =0;
do
{
statement-1; statement-2;. . . . . statement-n;
i++;
} while(i<10);

69
while loop
This is a control flow statement for specifying iteration, which allows
code to be executed repeatedly for specified number of times.
Syntax for
While(expression)
{
statement-1;
.....
statement-2;
};

Eg : int i =0;
while(i<10)
{
statement-1; statement-2;. . . . . statement-n;
i++;
};

70
nesting loop
Eg : int i =0, j=0;
do
{
statement-1; statement-2;. . . . . statement-n;
do
{
statement-1; statement-2;. . . . . statement-n;
j++;
}while(j<10);
i++;
} while(i<10);

Eg : int i=0, j=0;


while(i<10)
{
statement-1; statement-2;. . . . . statement-n;
while(j<10);
{
statement-1; statement-2;. . . . . statement-n;
j++;
};
i++;
};

71
nesting loop
Eg : int i =0, j=0;
for(i=0 ; i<10 ; i++)
{
statement-1; statement-2;. . . . . statement-n;
for(j=0 ; j<10 ; j++)
{
statement-1; statement-2;. . . . . statement-n;
}
}

Example of Infinite Loop

for(i=0 ; i<=5 ; i--)


printf(“%d\n”, i);

72
break, continue statement
Break statement is used inside the loops and switch statement. Some
time it becomes necessary to come out of the loop even before the loop
condition becomes false. In such situations, break statement is used to
terminate the loop. This statement causes an immediate exit from the loop.

The continue statement is used when we want to go to the next


iteration of the loop after skipping some statements of the loop. i.e when
continue statement is encountered all the remaining statements (statements
after continue) in the current iteration are not executed and the loop continues
with the next iteration.

Difference : break terminates the loop, continue will transfer the control to
next iteration bypassing the statements after continue in that particular iteration.

73
Assignment
Write a Program
Using only Switch…. Case
1. To find Even / Odd of an given value.

2. For analyzing students total marks and display relevant grading.

3. Check the character for vowel and print “The character is vowel” else print
“The character is not a vowel”.

Using Only Loop (for, while, do…while)


1. Find status of bit using if…else and for loop

2. Product of NUM without using multiplication operator.

3. Print the numbers in reverse order - 10 9 8 7 . . . 0

More on Exercise.docx

74
goto statement
Syntax : goto label ;
--------
--------
label : statement-1;
-------
-------
This is called as forward jump. When encountered goto label, control
jumps to label and starts execution of statements after the label. By passing the
statements after goto and before label.

label : statement-1;
--------
--------
goto label ;
--------
--------
This is called as backward jump. When encountered got label, control
jumps to label and starts execution of statements after the label.
goto label will work only in same function
75
FUNCTIONS

76
FUNCTIONS
Functions is self contained subprogram that performs some specific,
well defined task. Any C program consists of one or more functions. If a
program has only one function then it must be the main() function. It is the first
function to be executed when the program starts, all other functions are called
directly or indirectly from main().

Advantages of using functions.

1. Generally a difficult problem is divided into sub problem and then


solved. This divide and conquer technique is implemented in c using
functions.
2. When some specific code is to be used more than once and at
different
places in the program. The use of functions avoids repetition of that code.
3. The programs becomes easy to understand, modify and debug.
4. Functions can be stored in library and reused.

Two types of functions :


1. Library Functions
2. User-Defined Functions
77
FUNCTIONS

main()
{
1.--------
2.--------
3. function_1(); void function_1()
4 -------- {
5.-------- 1.--------
} 2.--------
3. --------
4 --------
5.--------
}

78
LOCAL, GLOBAL AND STATIC VARIABLES
Local Variable : The variables that are defined within the body of a function or a block are local
to that function or block only and are called local variables. These variables are created when function
is entered and are destroyed when the function is exited.
Global Variable : The variables that are defined outside any function are called global variables.
All functions in the programmer can access and modify global variables. It is useful to declare a
variable global if it is to be used by many functions in the program, Global variables are automatically
initialized to 0 at the time of declaration.

79
LOCAL, GLOBAL AND STATIC VARIABLES
Local Variable : The variables that are defined within the body of a function or a block are local
to that function or block only and are called local variables. These variables are created when function
is entered and are destroyed when the function is exited.
Global Variable : The variables that are defined outside any function are called global variables.
All functions in the programmer can access and modify global variables. It is useful to declare a
variable global if it is to be used by many functions in the program, Global variables are automatically
initialized to 0 at the time of declaration.
Static Variable : Static variables are declared by writing keyword static in front of the
declaration. If a static variable is not initialized then it is automatically initialized to 0. The variables
value will not get destroyed even when calling function comes out of the function.
Eg : #include<stdio.h> Here b is a static variable. First time when the function is
void function(void); called b is initialized to 10. Inside the function, value of b
int main(void) becomes 11. This value is retained and when next
time the
{ function is called, value of b is 11 and the initialization is
func(); neglected. Similarly when third time function is called, value
func(); of b is 12. Note that the variable a which is not static is
func(); initialized on each call and its value is not retained.
return 0;
}
void function(void)
{
int a=10;
static int b=10;
printf(“a=%d, b=%d\n”,a,b);
a++, b++;
}
80
FUNCTIONS
Library Functions The library functions are formally not a part of the C
language, but they are supplied with every C compiler. The source code of the library
functions is not given to the user. These functions are precompiled and the user gets only
the object code. This object code is linked to the object code of your program by the
linker.
User-Defined Functions : This functions are defined by Users

In both cases library and user defined , the function definition, declaration and call of
library functions :
(i) Function Declaration – In header file (files with a .h extension)
(ii) Function Definition – Predefined, precompiled and present in the library
(iii) Function Call - By the programmer

To use a library function in our program we should know :


(i) Name of the function and its purpose.
(ii) Type and number of arguments it accepts.
(iii) Type of the value it returns.
(iv) Name of the header file to be included.

81
FUNCTIONS
1. Function Declaration : Function declaration is used to give specific information to
the compiler about the functions so that it can check the functions calls. The calling
function needs information about the called function. If definition of the called is placed
before the calling function, then declaration is not needed.
2. Function Definition : Function definition consists of the whole description and
code of a function. It tells what the function is doing and what is its input and output. A
function definition consists of two parts – a function header and a function body.
Eg : void function(void)
function is nether receiving nor returning the value
int function(int a , int b);
passing parameters to functions and returning a value
3. Function Call : The function definition describes what a function can do,
but to actually use it in the program the function should be called somewhere. A function
is called by simply writing its name followed by the argument list inside the parentheses.
Function name is the called function while the function in which this function call is placed
is known as the calling function. For example in the program main() is the calling function,
sum() is the called function.

82
FUNCTIONS
User-Defined Functions
4. Return statements : The return statement is used for immediate exit (hand over
control) from the called function to the calling function and to return a value to the calling
function. This statement can appear any where inside the body of the function. There are
two ways in which it can be used : return ; (or) return (expression);

Eg : return 0, return 1.
return ++x, return (x+y*z), return (3*sum(a,b)).

83
FUNCTIONS
Function Returns Control to Calling Function Function Returns Control to Calling Function

main() main()
{ {
1.-------- 1.--------
2.-------- 2.--------
3. function_1(); void function_1(void) 3. function_1(); void function_1(void)
4 -------- { 4 -------- {
5.-------- 1.-------- 5.-------- 1.--------
} 2.-------- } 2.--------
3. -------- 3. return
4 -------- 4 --------
5.return 5.return
} }

Function Returns Control with a value Function Returns Control with a processed value

main() main()
{ {
1.-------- 1.--------
2.-------- 2.--------
3. function_1(); void function_1(void) 3. function_1(); void function_1(void)
4 -------- { 4 -------- {
5.-------- 1.-------- 5.-------- 1.int a=100+30;
} 2.-------- } 2.--------
3. return 0 3. return a;
4 -------- 4 --------
5.return 5.return
} }
84
FUNCTIONS
User-Defined Functions
5. Function Parameters and arguments : Parameters are mentioned in the
function definition and they are used to hold the values that are sent by the calling
function. These parameters are like other local variables of the function which are created
when the function call starts and are destroyed when the function ends.

However there are two differences.

First difference is that parameters are declared inside parentheses while other local
variables are declared at the beginning of the function block.

Second difference is that parameters are automatically initialized with the values of the
corresponding arguments provided in the function call while other local variables are
assigned values through the statements written inside the function body.

Any changes made to the parameters inside the function do not affect the
actual arguments. This mechanism of passing arguments is called call-by-value.
The other mechanism where arguments passed to the called function can
change the original parameters of calling function is called call-by reference(used in
pointers concept).

85
FUNCTIONS
Function Call By Value
Function returns control along with a Value (OR) Processed Value

int function_1(int c, int d)

main()
{
1.int a=5,b=6;
2.--------
3. function_1(a,b); int function_1(int c, int d)
4 -------- {
5.-------- 1.int a;
} 2. a = c + d;

3.return a
}

86
FUNCTIONS
User-Defined Functions
6. Order of evaluation of function arguments : The order of evaluation of arguments and
sub-expressions within the arguments is unspecified. This order of evaluation is not important in
function calls like mul(m,n) or mul(m+n, m-n). But let us take a case where int m=3, k; and k=mul(m,
m++). Here the first value is evaluated first then the value of k is 9, and if second value is evaluated
first then the k will result in 12.The order of evaluation of arguments is unspecified in C and depends
on compiler.
7. main () function: Execution of every C program always begins with the function main(). Each
function is called directly or indirectly in main() and after all functions have done their operations,
control returns back to main(). There can be only one main() function in a program. The main() is a
user defined function but the name, number and type of arguments are predefined in the language.
The operating system calls the main function and main() returns a value of integer type to the
operating system. If the value returned zero, it implies that the function has terminated successfully
and any nonzero return value indicates an error. If no return value is specified in main() then any
garbage value will be returned automatically.
Function Declaration – By the C compiler
Function Definition – By the programmer
Function Call – By the Operating System.
Classification of functions into four types depending on the return value and arguments.
1. Functions with no arguments and no return value Eg : void function(void), function()
2. Functions with no arguments but a return value Eg : int function(void), int function()
3. Functions with arguments and no return value Eg : void function(int a, char b)
4. Functions with arguments and return value Eg : int function (int a, char b)

87
Recursive Functions
Recursive Function is a function that calls itself.
Flow Control in simple function call
main()
{
1.--------
2.--------
3. function_1();
void function_1()
4 --------
{
5.--------
1.--------
}
2.--------
3. function_2(); void function_2()
4 -------- {
5.-------- 1.--------
} 2.--------
3. function_3(); void function_3()
4 -------- {
5.--------- 1.--------
} 2.--------
3.--------
4 --------
5.--------
}

88
Recursive Functions
Recursive Function is a function that calls itself.
Flow Control in Recursive Function i.e function calling itself.

main()
{
1.--------
2.--------
3. function(5); void function(int n)
4 -------- {
5.-------- 1.if(n==1)
} 2. return;
3. function(n-2); void function(int n)
4 -------- {
5.-------- 1.if(n==1)
} Here n is 5 2. return;
3. function(n-2); void function(int n)
4 -------- {
5.-------- 1.if(n==1)
} Here n is 3 2. return;
3.function(n-2);
4 --------
5.--------
} Here n is 0

89
Recursive Functions
Factorial Example : n=3, factorial of n is 3*2*1;

int main(void)
{
-----
f = fact(3); long fact(int n)
----- {
} if(n==0)
return1;
3*2=6 return(n*fact(n-1); long fact(int n)
}n=3 {
if(n==0)
return1;
#include<stdio.h> 2*1=2
return(n*fact(n-1); long fact(int n)
long int fact(int n);
}n=2 {
int main(void)
if(n==0)
{
return1;
int num=3; 1*1=1
return(n*fact(n-1); long fact(int n)
printf(“factorial = %d”, fact(num));
}n=1 {
}
if(n==0)
long int fact(int n) 1
return1;
{
return(n*fact(n-1);
if(n==0)
}n=0
return 1;
return(n*fact(n-1));
}

90
FUNCTIONS ASSIGNMENTS
Write a program for following.

1. Student Grading System :


if per is between 70 and 85 jump to a function and print grade as B
if per is between 55 and 70 jump to a function and print grade as C
if per is between 40 and 55 jump to a function and print grade as D
if per is less than 40 jump to a function and grade as E

2. Menu driven program using functions and switch-case, Main Menu containing
options, when selected an option, control has to jump to that function, clear
screen, display sub menu with relevant options, With suitable option perform an
action, go back to main menu. Also manage error messages if options are not
with in limit.

91
STORAGE CLASSES

92
STORAGE CLASSES
There are four storage classes in C :

(a) Automatic Storage Class


(b) External Storage Class
(c) Static Storage Class
(d) Register Storage Class

93
STORAGE CLASSES
There are four storage classes in C :

(a) Automatic Storage Class


(b) External Storage Class
(c) Static Storage Class
(d) Register Storage Class

Each storage class is expressed as

(i) Scope of variable : availability and usage of a variable


(ii) Initialization : initial value (by default) after declaration.
(iii) Life Time : variable creation/declaration and collapse
of a variable
(iv) Storage : Memory Location
(v) Linkage : The variable is linked with other files or not.

94
Key Place of Life Initial Place of
Scope Linkage Initialize
Word Declaration Time Value Storage

auto Inside Function Function Garbage Memory Constant/


Function block None
(Local) block block Value (stack) Variable

Through Through
auto -Out Side Memory Constant/
out out Zero None
(global) Function block (data area) Variable
Program Program

static Inside Function Memory


Program Function block Zero None Constant
(local) block (data area)

Cant be shared in other


Static Outside Memory
Program files using extern Zero Internal Constant
(global) Function block (data area)
declaration

Inside Function Function Garbage Constant/


Register block block
Function block
Value
Register None
Variable

-Function block for same


Outside or
file. Memory Cant be
Extern Inside Program
-Through out the
-
(data area)
External
initialized
Function block
program for another file. 95
STORAGE CLASSES
Memory During Program Execution :
CODE SIGMENT PROGRAM CODE

INITIALIZED DATA Initialized static Variables


Initialized global Variables

UNINITIALIZED DATA Uninitialized static Variables


Uninitialized global variables

HEAP Dynamically Allocated Memory

STACK Initialized and uninitialized automatic Variables

96
ARRAYS

97
ARRAYS
An array is a collection of similar type of data items and each data item
is called an element of array. The data type of the elements may be any valid
data type like char, int or float. The elements of array share the same variable
name but each element has a different index number known as subscript.
- If your index number is greater than of size of array then it will show a run time
error or it will results in garbage values.
- If you define array size as ‘n’ and you initialize a value to a single array
Element, The rest of the elements holds garbage or zero values.
- If variable declaration is global then the value stored by default is zero.
- If variable declaration is local then the value stored by default is garbage
values
Types of Arrays : Single Dimensional Arrays, Two Dimensional Arrays,
Three Dimensional Arrays.
The processing elements we generally use loops.
The size of array depends on data type declared multiplied by number of
subscripts.
For example char name[10], the size of array is calculated as
1byte x 10 subscripts = 10 bytes.

98
ARRAYS
Syntax : 1D Array - int age[100],
2D Array - char student_name[100][20],
3D Array - char class_student_name [10][50][20]

Example on how to print array’s subscript value and its address.

printf(“address of each element = %p”, a+i);

printf(“address of each element = %p”, &a[i]);

printf(“value of each element = %p”, *(a+i));

printf(“value of each element in hex = %p”, a[i]);

99
ARRAYS
Array to Functions
1. Passing the whole array to the function. 2. Passing the array element to the function.

#include<stdio.h> #include<stdio.h>
void function(int arr[]); void function(int n);
int main(void) int main(void)
{ {
int arr[5] = {5, 10, 15, 20, 25}; int arr[5] = {5, 10, 15, 20, 25};
function(arr); for(i=0 ; i<5 ; i++)
return 0; function(arr[i]);
} return 0;
void function(int arr[]) }
{ void function(int n)
int i=0; {
for(i=0 ; i<5 ; i++) if(n%2==0)
{ printf(“%d is Even”, n);
if(arr[i]%2==0) else printf(“%d is Odd”, n);
printf(“%d is Even”, arr[i]); }
else printf(“%d is Odd” , arr[i]);
}
}

100
ARRAYS ASSIGNMENTS
Write a program for following.

1. Find Larger and Smaller Number in an array.

2. Store a name in array and reverse that array elements,


and print.

3. Addition of 2x2 Matrices using 2D arrays.

4. Subtraction of 2x2 Matrices using 2D arrays.

5. Multiplication of 2x2 Matrices using 2D arrays.

101
STRINGS

102
STRINGS
Introduction to Strings
Def : String is collection of more than one character.
In c strings are treated as arrays of type char and are terminated by a null
character (‘\0’). This null character has ASCII value zero.
There are two forms of initialization of a string variables.
char str[10] = {‘I’,’N’,’D’,’I’,’A’,’\0’};
char str[10] = “INDIA”;
char str[] = “INDIA”;

Method 1 for printing the string :


while(str[i] !=‘\0’)
{
printf(“%c”, str[i])
}
Method 2 for printing the string :
printf(“%s”,str);
Difference between char constant and string constant : Character constant is
always enclosed with single quots and consists of single character. String
constant is always enclosed with double quots and consists of one or more
characters. Compiler will add a null character at the end of the string.

103
STRINGS
Introduction to Strings

Input Method for Strings :


(i) scanf(“%s”, string_name);
* if scanf() encounters spaces in a string, it will terminates / will not
store that character into a array variable.
(ii) gets(string_name)
*any number of spaces are allowed in between a string. gets()will
allow space character and stores in a string.
Output Methods for Strings :
(i) printf(“%s”, string_name);
(ii) puts(string_name);

void main(void) void main(void)


{ {
char str[20]; char str[20];
scanf(“%s”, str); gets(str);
printf(“%s”, str); puts(str);
} }

104
POINTERS

105
POINTERS
Pointer : Pointers are user defined variables which can hold address of
another variable.

Syntax : data_type *pointer_variable_name;


eg : int *a ;

Advantages : We can assesses address of another variable.


Pointers are used in data structures.
We can allocate memory dynamically.
Execution time of program will be reduced.
Optimization of memory can be achieved
pointer ( * ) is called as dereferencing operator.

Types of pointer : Single pointer Eg : *a;


Double pointer Eg : **a;
Triple Pointer Eg : ***a;

106
POINTERS
Single Pointer :

void main(void) a
{ 5
int a = 5; 500
int *p;
p = &a; p
printf(“value of a is %d”, a); 500
printf(“address of a is %d”, &a); 700
printf(“value of p is %d”, p);
printf(“address of p is %d”, &p);
printf(“value of *p is %d”, *p);
}
Output : value of a is 5
address of a is 500
value of p is 500
address of p is 700
value of *p is 5

107
POINTERS
Double Pointer : It is a user defined variables which can hold the address of
another pointer variable (single pointer variable)

Eg : int **p; a
5
Eg : int a = 5; 500
int *p; // single pointer
int **q; // double pointer p
p = &a; 500
q = &p; 700
Printf(“%d\n%d\n”, *p,*q);
q
Ouput: 700
*p = 5; 600
*q = address value of 700 (garbage value)

108
POINTERS
Triple Pointer : It is a user defined variables which can hold the address of
pointer variable (single pointer variable)

Eg : int ***p; a
5

Eg : int a = 5; 500
int *p; // single pointer
int **q; // double pointer p
500
int ***r; // Triple pointer
p = &a; 700
q = &p;
r = &q; q
700
600

r
600
800

109
POINTERS
Pointer Arthmetic
for example we take two pointer variables i.e p1 and p2

Rule 1 : 1) p2-p1 subtraction is permitted


2) p2+p1 addition is permitted
3) p2*p1 multiplication is not permitted
4) p2/p1 division is not permitted
5) p2%p1 modular operation is not permitted

Rule 2 : Increment and decrement operator can be used with pointer.


Eg : int a = 15
int *p = &a; a
p++, p--, ++p, --p 15
*p=15; 500
*(p++); increasing the value of p i.e address.
(*p)++; increasing the value of pointer p i.e a p
*p++; 500
++*p 700
*++p

110
POINTERS
Example : int a =5, *p1 = &a;
char b = ‘A’, *p2 = &b; a
15
float c = 20.5, *p3 = & c;
500
p1++, p2++, p3++;
b
A
Output :
600
p1++  p1=p1+1  p1 = 500 + (1x4bytes) = 504
p1=p1+2  p1 = 500 + (2x4bytes) = 508 c
(because int is of 4 bytes) 20.5
700
p2++  p2=p2+1  p2 = 600 + (1x1byte) = 601 p1
p2=p2+2  p2 = 600 + (2x1bytes) = 602 500
(because char is of 1 bytes) 800

P2
p3++  p3=p3+1  p3 = 700 + (1x4byte) = 704 600
p3=p3+2  p3 = 700 + (2x4bytes) = 708 900
(because float is of 4 bytes)
P3
700
1000

111
POINTERS
Rule 3 : Relation operator can be used between two pointers.
Eg : int a = 10, b = 10;
int *p1, *p2;
if(*p1>*p2)
printf(“even”);
else printf(“odd”);
Rule 4 : sizeof operator can be used to find out size of a pointer variable.
Here p1, p2 and p3 holds the address of variables, address will be always 4 bytes.
void pointer
Definition : void pointer can hold the address of any data type variable.
Eg :
void main(void)
{
int a = 10;
float b = 10.5;
void *p;
p=&a;
printf(“%p”, (int *)p);
printf(“%p”, *(int *)p);
P=&b;
printf(“%p”, (float *)p);
printf(“%f”, * (float *)p);
}
112
POINTERS AND ARRAYS
#include<stdio.h>

int main(void)
{
int arr[5] = {5,10,15,20,25};
int i;
for(i=0; i<2; i++)
{
printf("arr[%d] = %d\t",i,arr[i]);
printf("&arr[%d] = %p\n",i,&arr[i]);
}
printf("\n\n");

for(i=0; i<2; i++)


{
printf("arr[%d] = %d\t",i,*(arr+i));
printf("&arr[%d] = %p\n",i,arr+i);
}
return 0;
}
113
POINTERS AND ARRAYS
#include<stdio.h>
int main(void)
{
int arr[3]={5,10,15,20,25};
int i,*p;
p=arr;
for(i=0; i<3; i++)
{
printf("address of arr[%d]= %p\n",i,&arr[i]);
printf("address of arr[%d]= %p\n",i,arr+i);
printf("address of arr[%d]= %p\n",i,p+i);
printf("address of arr[%d]= %p\n",i,&p[i]);

printf("Value of arr[%d]= %d\n",i, arr[i]);


printf("Value of arr[%d]= %d\n",i, *(arr+i));
printf("Value of arr[%d]= %d\n",i, *(p+i));
printf("Value of arr[%d]= %d\n",i, p[i]);
printf("\n\n");
}
return 0;
} 114
POINTERS AND FUNCTIONS
In call by value, only the values of arguments are sent to the function and
any changes made to the formal parameters do not effects the actual arguments.
In call by reference, addresses of arguments are sent to the function and
any changes made to the formal parameters will take effect to the actual arguments.

Function Call by value

int function_1(int c, int d)

main()
{
1.int a=5,b=6,c;
2.;
3. c= function_1(a,b); int function_1(int c, int d)
4 .printf(“%d”,c); {
5.; 1. ;
} 2. ;
3. ;
4. ;
5. return c+d;
}
115
POINTERS AND FUNCTIONS
In call by value, only the values of arguments are sent to the function and
any changes made to the formal parameters do not effects the actual arguments.
In call by reference, addresses of arguments are sent to the function and
any changes made to the formal parameters will take effect to the actual arguments.

Function Call by Reference

void function_1(int *d, int *e, int *f)

main()
{
1.int a=5,b=6,c;
2.;
3. function_1(&a,&b,&c); void function_1(int *d, int *e, int *f)
4 .printf(“%d%d%d”,a,b,c); {
5.; 1 ;
} 2 ;
3 ;
4 *f = *d + *e;
5. return;
}
116
POINTERS AND FUNCTIONS
Function Returning Pointer

int *function_1(void)

main()
{
1.int *a;
2.;
3. a = function_1(void); int *function_1(void)
4 .printf(“%d - %d”,a,b); {
5.; 1. int a=10;
} 2. int *p=&a;
3. ;
4. ;
5. return p;
}

117
POINTERS TO STRINGS
Syntax : Char *p = “Hello”;
- p is holding base address.
- *p is pointing to first element of declaration.
- p++ is incrementing the value in side the p.
So incrementing base address by one.

Write Operation cannot be performed on STRING which is assigned to


a pointer variable (char *p = “HELLO”).

Eg : void main(void)
{
char *p = “Hello”;
int i =0;
for(i=0; i<5; i++)
{
printf(“%p \t”, (p+i));
printf(“%c \n”,*(p+i));
}
}

118
STRING
LIBRARY

119
STRING LIBRARY
String Library

Predefined functions

1. strlen() : For finding the length of a string.

2. strcmp() : For comparing two strings.

3. strcpy() : To copy a string from one location to another.

4. strcat() : For Joining two strings.

120
STRING LIBRARY
Example for strlen() (Using Predefined Function)
#include<stdio.h>
#include<strlib.h>
void main(void)
{
char str[20] = “Hello”;
int length;
length = strlen(str);
printf(“%d”, length);
}

121
STRING LIBRARY
Example for strlen() (using user defined function with arrays)
#include<stdio.h>
int str_len(char str[]);
void main(void)
{
char str[20] = “hello”;
int length;
length = str_len(str);
printf(“length of string = %d”, length);
}
int str_len(char str[ ])
{
int i=0;
while( str[i] != ‘\0’ )
{
i++;
}
return i;
}
122
STRING LIBRARY
Example for strlen() (using user defined function with pointers)
#include<stdio.h>
Int str_len(char *p);
void main(void)
{
char str[20] = “hello”;
int length;
length = str_len(str);
printf(“length of string = %d”, length);
}
int str_len(char *p)
{
int i=0;
while( *p != ‘\0’ )
{
i++, p++;
}
return i;
}
123
STRING LIBRARY
Example for strcmp() (Using Predefined Function)
#include<stdio.h>
#include<strlib.h>
void main(void)
{
char str_1[20], str_2[20];
printf(“str_one : “);
gets(str1);
printf(“str_two : “);
gets(str2);
if(strcmp(str1, str2) == 0)
printf(“strings are matching”);
else printf(“strings not matching”);
}

124
STRING LIBRARY
Example for strcmp() (using user defined function with arrays)
#include<stdio.h> int str_cmp(char str_1[], char str_2[])
int str_cmp(char str_1[], char str_2[]); {
void main(void) int i = 0;
{ if(str_len(str_1) != str_len(str_2))
char str_1[20], str_2[20]; return 1;
printf("str_one : "); else
gets(str_1); {
printf("str_two : "); while(str_1[i] != '\0‘ && str_2[i] != '\0')
gets(str_2); {
if(str_cmp(str_1, str_2) == 0) if(str_1[i] != str_2[i])
printf("strings are matching"); return 1;
else printf("strings not matching"); i++;
} }
return 0;
}
}

125
STRING LIBRARY
Example for strcmp() (using user defined function with pointers)
#include<stdio.h> int str_cmp(char *str_1, char *str_2)
int str_cmp(char *str_1, char *str_2); {
void main(void) int i = 0;
{ if(str_len(str_1) != str_len(str_2))
char str_1[20], str_2[20]; return 1; // Consider 1 as not matching
printf("str_one : "); else
gets(str_1); {
printf("str_two : "); while(*str_1 != '\0‘ && *str_2 != '\0')
gets(str_2); {
if(str_cmp(str_1, str_2) == 0) if(*str_1 != *str_2)
printf("strings are matching"); return 1;
else printf("strings not matching"); str_1++, str_2++;
} }
return 0; // Consider 0 as matching
}
}

126
STRING LIBRARY
Example for strcpy() (Using Predefined Function)
#include<stdio.h>
#include<stdlib.h>
void main(void)
{
char str_1[20], str_2[20];
printf(“str_one : “);
gets(str_1);
printf(“str_two : “);
gets(str_2);
strcpy(str_1, str_2);
puts(str_1);
puts(str_2);
}

127
STRING LIBRARY
Example for strcpy() (using user defined function with arrays)
#include<stdio.h> int str_cpy(char str_1[], char str_2[])
int str_cpy(char str_1[], char str_2[]); {
void main(void) int i = 0;
{ {
char str_1[20], str_2[20]; while(str_2[i]!='\0’ || str_1[i]!=‘\0’)
printf("str_one : "); {
gets(str_1); str_1[i] = str_2[i];
printf("str_two : ");
gets(str_2); i++;
str_cpy(str_1, str_2); }
puts(str_1); str_1[i] = ‘\0’;
puts(str_2); }
} }

128
STRING LIBRARY
Example for strcmp() (using user defined function with pointers)
#include<stdio.h> int str_cpy(char *str_1, char *str_2)
int str_cpy(char *str_1, char *str_2); {
void main(void) int i = 0;
{ {
char str_1[20], str_2[20]; while(*str_2 != '\0’ || *str_1 != ‘\0’)
printf("str_one : "); {
gets(str_1); *str_1 = *str_2;
printf("str_two : ");
gets(str_2); str_1++, str_2++;
str_cpy(str_1, str_2); }
puts(str_1); *str_1 = ‘\0’;
puts(str_2); }
} }

129
STRING LIBRARY
Example for strcat() (Using Predefined Function)
#include<stdio.h>
#include<strlib.h>
void main(void)
{
char str_1[20], str_2[20];
printf(“str_one : “);
gets(str_1);
printf(“str_two : “);
gets(str_2);
strcat(str_1, str_2);
puts(str_1);
puts(str_2);
}

130
STRING LIBRARY
Example for strcat() (using user defined function with arrays)
int str_cat(char str_1[], char str_2[])
#include<stdio.h>
{
int str_cat(char str_1[], char str_2[])
int i = 0,j = 0;
void main(void)
while(str_1[i]!=‘\0’)
{
i++;
char str_1[20], str_2[20];
str_1[i] = ‘ ‘;
printf(“str_one : “);
i++;
gets(str_1);
printf(“str_two : “);
while(str_2[i]!='\0’)
gets(str_2);
{
str_cat(str_1, str_2);
str_1[i] = str_2[j];
puts(str_1);
puts(str_2);
i++,j++;
}
}
str_1[i] = ‘\0’;
}

131
STRING LIBRARY
Example for strcat() (using user defined function with pointers)
int str_cat(char *str_1, char *str_2)
#include<stdio.h>
{
int str_cat(char *str_1, char *str_2)
int i = 0,j = 0;
void main(void)
while(*str_1!=‘\0’)
{
str_1++;
char str_1[20], str_2[20];
*str_1 = ‘ ‘;
printf(“str_one : “);
str_1++;
gets(str_1);
printf(“str_two : “);
while(*str_2!='\0’)
gets(str_2);
{
str_cat(str_1, str_2);
*str_1 = *str_2;
puts(str_1);
puts(str_2);
str_1++, str_2++;
}
}
*str_1 = ‘\0’;
}

132
STRUCTURES

133
STRUCTURES
Structures : Structure is a collection of different elements with different
datatypes.

Syntax : struct structure_name


{
data_type member1_name;
data_type member2_name;
----
} structure_variable;

Eg : struct student
{
char name[15];
int roll;
float marks;
} stu1;

Note : By using . (dot operator) we can assess the member of a structure.

134
STRUCTURES
Different methods for initialization of members of a structure
1st method : stu1 = { “name”, 123, 80.33};
2nd method : strcpy (stu1.name, “name”);
stu1.roll = 123;
stu1.marks = 80.33;
3rd method : scanf(“%s”, &stu1.name) (or) scanf(“%s”, stu1.name);
scanf(“%d”,&stu1.roll);
Note : (i) By defining a structure, memory is not allocated by the computer. Only after
declaration of structure variable memory is being allotted by the computer.
(ii) Structure can be declared as global or local. If structure is declared as
global then any user defined function can assess the structure. If structure is
declared as local in a particular user defined function then it can be assessed
only by that function.
(iii) Inside the structure definition we cannot initialize the members of
structures.
WRONG WAY OF INITIALIZATION
struct student
{
int roll = 1234;
char name[15] = “name”;
float marks = 45.02;
{

135
STRUCTURES
Types of Structures

(i) Array of Structures

(ii) Function of Structures

136
STRUCTURES
Array of Structures :

#include <stdio.h>
struct student
{
char Name[10];
int rollno;
float marks;
};

int main()
{

int i;
struct student stu[10];
for(i =0;i<10;i++)
{
printf("Enter Name, rollNo, Marks: ");
scanf("%S%d%f",&stu[i].Name, &stu[i].rollno, &stu[i].marks);
}
for(i=0;i<10;i++)
{
printf("%s %d %f\n",stu[i].Name, stu[i].rollno, stu[i].marks);
return 0;
}
}

137
struct student
{
char Name[10];
int rollno;

float marks[2];
};

int main()
{

int i,j;
struct student stu[3];
for(i =0;i<2;i++)
{
printf("Enter the data for student%d\n", i+1);
printf("Enter the name: ");
scanf("%s", stu[i].Name);
printf("Enter rollno :");
scanf("%d", &stu[i].rollno);
for(j=0;j<3;j++)
{
printf("Enter marks for subject %d: ", j+1);
scanf("%d", &stu[i].marks[j]);
for(i=0;i<2;i++)
{

printf("Data of student %d\n", i+1);


printf("Name:%s, roll no:%d\n marks:", stu[i].Name, stu[i].rollno);
for(j=0;j<2;j++)
{

printf("%d", stu[i].marks[j]);
printf("\n");
}
return 0;
138
} }}}
STRUCTURES
Structures To Functions :
struct student struct student
{ {
char name[15]; char name[15];
int roll; int roll;
float marks; float marks;
}; };

void function(char name[ ], int roll, float marks); void function(struct student std2);

void main(void) void main(void)


{ {
struct student std1={“Ravi”, 10, 10.50}; struct student std1={“Ravi”, 10, 10.50};
function(std1.name, std1.roll,std1.marks); function(std1);
} }

void function(char name[ ], int roll, float marks) void function(struct student std2)
{ {
printf(“name %s\n”,name); printf(“name %s\n”,std2.name);
printf(“roll %d\n”, roll); printf(“roll %d\n”, std2.roll);
printf(“marks %f\n”, marks); printf(“marks %f\n”, std2.marks);
} }

139
STRUCTURES
Size of Structure :
By using size of operator we can find out the size of sturcture.
Syntax : sizeof(structure tag); (or) sizeof(structure variable);
Eg : sizeof(structure student) (or) sizeo(std1);
Structure padding :
In gcc compiler structure padding is happening as.
struct student
Internal memory is allocated as given below
{
char a; // 1bytes char – -0-x-x-x-
char name[5]; // 1byte x 5 = 5bytes char – -0-1-2-3-4-x-x-x-
int roll; int – -0-1-2-3-
float marks; Float – -0-1-2-3-
}; In the above structure the data type which holds
more bytes, that is being considered for allocating
the memory for each single variable or element.

140
NESTED STRUCTURES
Nested structures (structures within structures) :
struct tag1
{
member1;
member2;

struct tag2
{
member1;
member2;
------
memeber m;
}var1;
------
member n;
}var2;

for accessing member1 of inner structure : var2.var1.member1

141
Example:
struct student
{
char name[10];
int rollno;
struct date
{
int day;
int month;
int year;
}birthdate;
float marks;
}stu1,stu2;

Example:
stu1.birthdate.day
stu2.birthdate.year

142
UNIONS
Syntax : Similar to structure declaration and initialization.
union union_tag
{
data_type member;
.....
data_type member;
};
union union_tag variable_name;
Example :
union student
{
char name[20];
int Roll;
float marks;
};
union student std_1;

143
UNIONS
Example :
void main(void)
{
strcpy(std.name, ”surya”);
printf(“%s”,std.name);
std.roll=65;
printf(“%s”,std.name);
printf(“%d”,std.roll);
}
OUTPUT: surya
A
65

Note :
- Members of unions, internally they are sharing single memory location.
- Compiler allocates highest data_types, bytes in the memory.
- One member can be assessed at a time.

144
struct stag
{
char c;
int i;
float f;
};

union utag
{
char c;
int i;
float f;
};

int main(void)
{
union utag uvar;
struct stag svar;
printf("size of svar = %u\n", sizeof(svar));
printf("Address of svar: %p\t",&svar);
printf("Address of members : %p %p %p\n", &svar.c, &svar.i, &svar.f);
printf("size of uvar = %u\n", sizeof(uvar));
printf("Address of svar: %p\t",&uvar);
printf("Address of members : %p %p %p\n", &uvar.c, &uvar.i, &uvar.f);
}
#pragma pack(value);
Packing and padding
BIT FIELDS
Example :
struct student
{
unsigned int roll : 3;
} std_1;
void main(void)
{
std.roll = 1; printf(“%d \n”, std.roll);
std.roll = 4; printf(“%d\n”, std.roll);
std.roll = 7; printf(“%d\n”,std.roll);
std.roll = 8; printf(“%d\n”,std.roll);
}
OUTPUT: 1 0-0-1
4 1-0-0
7 1-1-1
0 0-0-0

Note : In the example given above, int is of 4 bytes, but by specifying bitfield to compiler as
unsigned int roll : 3, you are specifying compiler that only 3 bits of lower nibble is to be assessed.

146
typedef
typedef : It is a key word. By using typedef, we can replace user defined tags
in the place of data_type keyword.
Eg:
Eg : typedef int integer;
#include<stdio.h>
- int is a keyword which is replaced by integer;
void main(void)
eg : integer a = 5; {
integer roll; typedef int integer;
integer a=6, b=8;
typedef for structures : printf(“%d %d \n”, a,b);
Eg : }
typedef struct student
{
int roll;
char grade[5];
} abcd;
void main(void)
{
// struct student std_1; // need not to declare in this manner
abcd std_1 = {153, “A”};
printf(“%d %s”, std_1.roll, std_1.grade);
}

147
FILES

148
FILES
Files is a collection of data or information that has a name, called the
filename. Almost all information stored in a computer must be in a file. There
are many different types of files: data files, text files , program files,
directory files, and so on.
Operation on Files :
(i) Write Operation
(ii) Read Operation
(iii) Modification (appending)
Steps for file operations in C programming :
- Open a file
- Read data from the file or Write data to the file
- Close the file
Steps for Creating a File :
fopen(); - Opening a file
fwrite(); - writing to the file
fread(); - reading from the file
fclose(); - Closing the file

149
FILES
Text and Binary streams :
In C Input and output stream of data-operation on file is performed with the
help of library functions. File management is done by the execution environment, and
streams are channels through which data can flow from program to environment and
from environment to program. When file is opened, a stream is associated with a file and
when file is closed the same stream is disassociated with the file. There are two types of
stream – text stream and binary streams. Text stream is a stream of characters and
binary stream is a stream of unprocessed bytes.
Buffer :
Buffer is an area in memory where the data is temporarily stored before being
written to the file. When we open a file, a buffer is automatically associated with its file
pointer. Whatever data we send to the file is not immediately written to the file. First it is
sent is sent to the buffer and when the buffer is full, its contents are written to the file.

WRITE OPERATION READ OPERATION


BUFFER FILE.TXT BUFFER FILE.TXT
INPUT ABC ABC OUTPUT ABC ABC

EOF EOF

150
Types of buffers:

Fully Buffered Stream: The data is transferred only when the buffer is full.

Line Buffered Stream: the data is transferred either when buffer is full or when a
newline character is written to the buffer.

Unbuffered Stream: the data is transferred as quickly as possible.

When file is opened, a fully buffered stream is attached to it.

151
FILES
Opening a File :
File must be opened before any I/O operations can be performed on that file.
The process of establishing a connection between the program and file is called opening
the file. When a file is opened, a stream is associated with that file, a buffer is created in
the main memory for transferring data to and from the file.
A structure named FILE is defined in the header file <stdio.h> that contains all
information about the file like name, status(read, write etc), buffer location, current
position in the buffer, end of file status, error status etc.
A file pointer(stream pointer) is a pointer to a structure of type FILE. The
function fopen() is used to open a file. fopen() function takes two strings as arguments,
the first one is the name of the file to be opened and second one is the mode that
decides which operations (read, write, append etc) are to be performed on the file.
Error Handling : On error, fopen() returns NULL and On success, fopen() returns a
pointer of type FILE. The return value of fopen is assigned to a FILE pointer declared
previously.

Declaration : FILE * fopen(const char *filename, const char *mode);

Example : FILE *fp1, *fp2;


fp1=fopen(“myfile.txt”, “w”);
fp2=fopen(“yourfile”, “r”);
152
FILES
Modes while Opening a File :
1. “w” (write) : If the file doesn’t exist then this mode creates a new file for writing,
and if the file already exists then the previous data is erased and the new data entered is
written to the file.

2. “a” (append) : If the file doesn’t exist then this mode creates a new file, and if the
file already exists then the new data entered is appended at the end of existing dat. In
this mode, the data existing in the file is not erased as in “w” (write) mode.

3. “r” (read) : This mode is used for opening an existing file for reading purpose
only. The file to be opened must exist and the previous data of file is not erased.

153
FILES
Closing a File :
The file which was opened using fopen() function must be closed when no
more operations are to be performed on it. After closing the file, connection between file
pointer and file is broken. Now the file pointer fptr is there to connect some other file. On
closing the file, the buffer associated with it is flushed i.e all the data that is in the buffer
is written to the file and the buffers allocated by the system for the file are freed after the
file is closed, so that these buffers can be available for other files.
Error Handling : On error fclose() returns EOF and On success fclose() returns 0 (EOF
is a constant defined in stdio.h and its value is -1)
Declaration : int fclose(FILE *fptr);
If more than one files are opened, then we can close all the files by calling
fclose() for each file.
fclose(fptr1);
fclose(fptr2);
---------
We can also close multiple files by calling a single function fcloseall(); It closes
all the opened files.
Declaration : int fcloseall(void);
Error Handling : On error, fcloseall() returns EOF and On success it returns the
number of files closed.
154
FILES
End of File :
The file reading functions need to know the end of file so that they can stop
reading. When the end of file reached, the operating system sends an end-of-file signal to
the program. When the program receives the signal, the file reading functions return
EOF, which is a constant defined in the file stdio.h and its value is -1.
Standard streams :
When the program starts executing, the operating system opens three
standard text streams automatically and provides constant file pointers for them.
File pointer Stream Buffering
stdin Standard input Line-buffered
stdout Standard output Line-buffered
stderr Standard error Unbuffered
Functions used for file I/O are :
Read Operation Write Operation
Character I/O : fgetc() fputc()
String I/O: fgets() fputs()
Formatted I/O : fscanf() fprintf()
Record I/O : fread() fwrite()

155
Structure of a File Program

Int main()
{
FILE *fp;
fp = fopen(“filename”, mode);
-----------------------
-----------------------
fclose(fp);
return0;
}

156
fputc()
Declaration: int fputc(int c, FILE *fptr);

fgetc()
Declaration: int fgetc(FILE *fptr);

157
158
FILES
Some of Errors on File Operation :
- If you create a file with write mode but if you try to read the file then it will show error.

- If you create a file with read mode but if you try to write on file then it will show error.

- If you try to access a file without proper permission modes then it will show error.

- If you try to create a file and there is no space in disk, then it will show error.

159
DYNAMIC
MEMORY
ALLOCATION

160
DYNAMIC MEMORY ALLOCATION
DMA : Allocating of memory at the runtime is called Dynamic Memory Allocation.

Static Memory Allocation Dynamic Memory Allocation

1. Static memory allocation is 1. Memory allocation at run time.


done at compilation timer

2. Wastage of memory will result 2. No wastage of memory


when allocated memory is not
used at run time.

3. When in need of more 3. Memory allocation is done at


memory than allocated, cant run time as required
allocate memory at run time.

4. Unused memory cant be 4. Memory is de-allocated if not


made free at run time. used

161
DYNAMIC MEMORY ALLOCATION
There are 4 predefined functions (defined in stdlib.h)
1.malloc(); 2. calloc(); 3. realloc(); 4. free();

1. malloc() : It is a predefined function, used to allocate block of memory


dynamically. syntax : ptr=(Datatype *) malloc (sizeof block);
eg : int *ptr;
ptr=(int *)malloc(n*sizeof(int));
ptr = (int *)malloc(12);
2. calloc() : It is a predefined function, used to allocate multiple blocks of memory
dynamically. syntax : ptr=(Datatype *) calloc (n,sizeof block);
eg : int *ptr;
ptr=(int *)calloc(5,sizeof(int));
3. realloc() : It is a predefined function which is used to change the size of the
memory block. It alters the size of the memory block without losing the data. This
is known as reallocation of memory.
syntax : ptr=(Datatype *) realloc(void *ptr, sizeof block);
eg : int *ptr;
ptr=(int *) realloc(ptr, n*sizeof(int));
4. free() : The dynamically allocated memory is not automatically released, It will
exist till the end of program, It is user responsibility to release the memory.
syntax : void free(void *ptr)
eg : free(ptr);
162
DYNAMIC MEMORY ALLOCATION
malloc() takes a single argument (memory required in bytes),
while calloc() needs two arguments. Secondly, malloc() does not initialize the
memory allocated, while calloc() initializes the allocated memory to
ZERO. calloc() allocates a memory area, the length will be the product of its
parameters.

163
PRE PROCESSOR DIRECTIVE

164
PRE PROCESSOR DIRECTIVE
Definition : If any statement will start with # symbol, it is called a preprocessor
directive. They are invoked by the compiler to process some programs before
compilation.
Advantages :
(i) Readability of program will becomes easy.
(ii) Debugging & testing of a program becomes easy.
(iii) Execution time is less
(iv) Code density will decrease.
Features:
(i) Preprocessor directive will start with # symbol
(ii) Expression replacement is very easy
(iii) Semicolon (;) will not be used to terminate preprocessor directive statements
(iv) Preprocessor directive is generally is a one line statement, but if you want to
continue with next line, we place a backslash (\)
The function of Preprocessor Directives :
(i) Simple Macro replacement
(ii) Macro with expression replacement
(iii) Conditional Compilation.

165
PRE PROCESSOR DIRECTIVE
(i) Simple Macro replacement :
Example_One Example_Two Example_Two
#include <stdio.h> #include <stdio.h> #include <stdio.h>
#define size 10
void main(void) #define marks 10 #define Hi printf(“Hi”)
{ #define size marks #define scan_i scanf(“%d”,&i);
int arr_one[size];
int arr_two[size-3]; void main(void) void main(void)
} { {
if(size>30) int I;
printf(“Hi”) scan_i;
else printf(“Hello”); printf(“%d”, i);
} Hi;
}

166
PRE PROCESSOR DIRECTIVE
(ii) Conditional Compilation Preprocessor :

By using conditional compilation we can check the condition, If the condition is


true then the block will be compiled by compiler. If condition is false then that block will
be removed from source code.

Preprocessor Directives :
#define Test 5
# if void main(void)
# else {
# elif - else if printf(“HELLO\n”);
# endif #if Test > 2
# ifdef - if define. printf(“Hi”);
# ifndef - if not define. #endif
# undif - undefine. printf(“Bye”);
}

167
enum - Enumeration Constants
 enum is another user-defined data type consisting of a set of
named constants called enumerators.
> Using a keyword enum, it is a set of integer constants represented
by identifiers.
> The values in an enum start with 0, unless specified otherwise, and
are incremented by 1.  For example, the following enumeration,
enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

> Creates a new data type, enum days, in which the identifiers are
set automatically to the integers 0 to 6.
> To number the days 1 to 7, use the following enumeration,
enum days {Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};

> Or we can re-arrange the order,


enum days {Mon, Tue, Wed, Thu = 7, Fri, Sat, Sun};

168
Command Line Arguments

169
Command Line Arguments
• When executing a program in either C or C++ there is a
way to pass arguments to the program at command
prompt (called as Command Line Arguments).

• Each parameter is considered as an character array and


separated by a space

• At command line ‘n’ number of arguments can be


passed.

• Comes into the program as two arguments


– argc – Number of parameters
– argv – Parameter list
170
Command Line Arguments
#include <stdio.h>

int main(int argc, char *argv[])


{
for (int i=0; i<argc; i++)
{
printf(“\tTHIS IS ARGUMENT NUMBER %d”, i);
printf(“\t%d”, argv[i]);
}
return 0;
}

171
Command Line Arguments
#include <stdio.h> // SAVED AS add

int main(int argc, char *argv[])


{
int i=0,add=0;

for (i=1; i<argc; i++)


add = add + (argv[i][0]-48);

printf("\t\t%d", add);
return 0;

172
C Program as Command
#include <stdio.h> // Saved as LIST
void main(void)
{
system("cls");
system(“dir”);
system(“c:”);
}

#include <stdio.h> // Saved as WIPE


int main(void)
{
system("cls");
}

173
*****
*******
*************
******************

174

You might also like