Download as pdf or txt
Download as pdf or txt
You are on page 1of 172

Introduction to „C‟

 Why „C‟ language is so important :


 Worth to know about C language :
- Oracle is written in C.
- Core libraries are written in C.
- MYSQL Database is written in C.
- Almost every device drivers are written in C.
- Major parts of web browser written in C.
- UNIX operating system is developed in C.
- „C‟ is the world‟s most popular programming language.
 For Students :
- C is important to build programming skills.
- C covers basic features of all programming language.
- C is most popular language for hardware dependent programming.
 „C‟ is programming language. This is used to write program and execute them.
 There are mainly two types of languages, which are known as Low Level and
High Level languages.
 Low level language interact with the computer hardware.
 Example Assembly language interact with the machine hardware e.g. Memory.
 Machinery code is a low level language are human understandable language
like English.
 „C‟ language is high level language but sometimes it is middle level language
because it combines element of high level language with the functionalism of
assembly language.
 Code written in „C‟ language is very portable i.e. software written on one type of
computer can be work/run in another computer.
 „C‟ shows both features of low level language (as it interact with the hardware)
and high level language (as it contain English like words), it known as middle
level language.
 Also writing „C‟ program in a particular structure is followed, due to this it is
called as block structured language. „C‟ is very powerful programming language
as most of the part as UNIX (multiuser operating system) is written in „C‟.
 Programming in „C‟ is the first step if you would like to be a good programmer
and also ideal for system-level programming.

DiSHA Computer Institute, Kopargaon 1


History of „C‟ language

 Martin Richards :
 Developer of BCPL.
 Basic Combined Programming Language.
 In 1966.
 Using combination of many languages feature
The BCPL was developed by Martin Rechards.

 Ken Thompson :
 Developer of B language.
 By improving BCPL developed a „B‟ language
 In 1969.
 Work in AT&T‟s Bell Laboratories.
 Also developer of UNIX operating system.

 Dennis Ritchie :
 Developer of C language.
 In 1972.
 At AT&T‟s Bell Lab‟s, USA.
 Co-developer of UNIX operating system.

DiSHA Computer Institute, Kopargaon 2


 Introduction to Software :
The computer system is made up of two major components known as
hardware and software. The hardware is set of the physical components i.e.
physical parts called keyboard, mouse, monitor, CPU, hard-disk etc. The
second component is software which called interface between user and
hardware. In other words software can be called as Bridge between user and
computer hardware.

This means without software it is not possible to use computer hardware.


Software is set of programs and program is set of instruction given to
hardware. Software helps user to view and run the programs. It also helps
hardware to get initialized start. Computer system cannot be used without
software. So the gap between computer user and computer hardware is filled
by bridge called software.

The software is broadly classified into five main categories on the basis
of its requirement to the users.

1. System software.
2. Application software.
3. Programming languages.
4. Advanced Development Tools
5. Web based tools.

1. Operating System :
An Operating system is system software that manages computer hardware
and software resources and provides common services for computer
programs. All computer programs, excluding firmware, require an operating
system to function.
We cannot imagine a machine without operating system. Some examples of
operating system are Windows XP, Windows NT, Windows 7/8/8.1/10 MAC
etc.

2. Application Software :
Application software, or simply applications, are often called productivity
programs or end-user programs because they enable the user to complete
tasks, such as creating documents, databases and publications, doing online
research, sending email, designing graphics, and even playing games..!

DiSHA Computer Institute, Kopargaon 3


Some examples of application software are Tally, Office automation software
like Microsoft Office OR Designing tools like Page Maker, Corel-Draw or
Photoshop. User can install the application software on the basis of
operating system. User have wide range of application software in the
market.

3. Programming Languages :
The programming languages are purely computer languages. These are used
to developed system software and application software. For Example: UNIX
operating system is mostly developed in „C‟ Language. Examples of other
operating systems are C, C++, C#, JAVA etc.

4. Advanced Development Tools :


These type of software is advanced technology based. They are mainly used
in combinations. The two main categories of these software are front end
and back end. Front end design the screen and reports of the software and
back end are DBMS and RDBMS, which are used to store the data entered
by the user. Some popular front end are Visual Basic, Developer 2000,
Visual C++ etc. and back ends are Oracle, Sybase and Informix etc.

5. Web Based Tools :


These are software used for development of website for the internet,
Examples are HTML, DHTML, VB Script, Java Script, ASP, PHP, PERL
etc.

 Facts about C :
C was invented to write an operating system called UNIX. C is a successor of
B language which was introduced around the early 1970s.

The language was formalized in 1988 by the American National Standard


Institute (ANSI). The UNIX OS was totally written in C.

Today C is the most widely used and popular System Programming


Language. Most of the state-of-the-art software have been implemented
using C.

Today's most popular Linux OS and RDBMS MySQL have been written in
C.

DiSHA Computer Institute, Kopargaon 4


 Why Use C..? :
C has now become a widely used professional language for various reasons:

 Easy to learn.
 Structured language.
 It produces efficient programs.
 It can handle low-level activities.
 It can be compiled on a variety of computer platforms.

C was initially used for system development work, particularly the programs
that make-up the operating system. C was adopted as a system development
language because it produces code that runs nearly as fast as the code
written in assembly language.

Some examples of the use of C might be:


 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities

 Hello World Example :


A C program basically consists of the following parts:

 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments

DiSHA Computer Institute, Kopargaon 5


Let us look at a simple code that would print the words "Hello World":

#include <stdio.h>
void main()
{
clrscr();
printf("Hello, World..! \n");
getch();;
}

Output :
Hello World..!

Let us take a look at the various parts of the above program:

 The first line of the program #include <stdio.h> is a preprocessor


command, which tells a C compiler to include stdio.h file before going to
actual compilation.

 The next line int main() is the main function where the program
execution Begins.

 The next line /*...*/ will be ignored by the compiler and it has been put to
add additional comments in the program. So such lines are called
comments in the program.

 The next line printf(...) is another function available in C which causes


the message "Hello, World!" to be displayed on the screen. The next line
return 0; terminates the main() function and returns the value 0.

 Program and process :


 Set of instructions called program.
 Active state of program called process.

DiSHA Computer Institute, Kopargaon 6


 Execution of C program :
 Executing a C program involves a series of steps. They are :
1. Creating a program.
2. Compiling a program.
3. Run a program.
4. Check Result.

 Following figure show the steps of C program :

DiSHA Computer Institute, Kopargaon 7


 Compiling and Execution of C program :

DiSHA Computer Institute, Kopargaon 8


 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 units in a C program are known as C
tokens.

 C tokens are of six types. They are,


1. Identifiers (e.g. : main, total),
2. Constants (e.g. : 10, 20),
3. Keywords (e.g. : int, while),
4. Strings (e.g. : “total”, “hello”),
5. Special symbols (e.g. : (), {}),
6. Operators (e.g. : +, /,-,*).

 For example :

#include<stdio.h>
void main()
{
int x, y, total;
clrscr();
x = 10, y = 20;
total = x + y;
printf ("Total = %d \n", total);
getch();
}

Where,
 main – identifier.

 int – keyword.
 x, y, total – identifier.

main, {, }, (, ), int, x, y, total – tokens.

DiSHA Computer Institute, Kopargaon 9


 Identifiers :
Each program elements in a C program are given a name called identifiers. An
identifier is a name used to identify a variable, function, or any other user
defined item. An identifier starts with a letter A to Z, a to z, or an underscore
„_‟ followed by zero or more letters, underscores, and digits (0 to 9).

 Constant :
C Constants are also like normal variables. But, only difference is, their values
cannot be modified by the program once they are defined.
Constant are refer to fixed value.

 Types of constants :

 Integer constants :
-55, 33, 0, 123456789 are integer constants.
For e.g. : mobile no. : 9876543210 are also integer constant.

 Real or floating point constants :


For e.g. : 22.4, 3.56, -0.065, 2.0, 3.14142 are real or floating point
constant.

DiSHA Computer Institute, Kopargaon 10


 Character constants :
For e.g. : „a‟, „B‟, „+‟, „*‟, „ „ are character constants.
Any alphabet or symbol is in single quotation mark ( „B‟ ) are character
constant.

 String constants :
For e.g. : “Mayur”, “ABCD”, “Pune” are string constants.
String is collection of characters. Any string is in double quotation mark
( “Mayur” ) are string constants.

 Variables :
Variables are the names of memory locations where we store data. This
location is used to hold the value of the variable.
The value of the C variable may get change in the program. C variable might
be belonging to any of the data type like int, float, char etc.

 Rules for naming C variables :


- Variable name is any combination of alphabet, digit and
underscore.
- A valid variable name cannot start with digit.
- Variables are case sensitive
- No special symbols are allowed other than underscore.
- Sum, height, num_1 are some examples for variable name.

 Declaration of variable :
Declaration of variable in C can be done using following syntax :

Data_type variable_name ;
OR
Data_type variable_name1, variable_name2,… ;

Where, Data_type is any valid C data type and variable_name is any


valid identifier.

DiSHA Computer Institute, Kopargaon 11


 For e.g. :

int a ;
char variable ;
float x, y ;

 Initialization of variable :
C variables declared can be initialized with the help of assignment
operator „=‟.
 Syntax :

Data_type variable_name = constant/ literal/ expression ;


OR
Variable_name = constant/ literal/ expression ;

 For e.g. :
int a = 10 ;
char variable = „M‟ ;
float x = 33, y = 22 ;
OR
a = 10 ;
x = 33 ;
y = 22 ;

 Keywords :
 Keywords are those words whose meaning is already defined by
Compiler.
 Cannot be used as Variable Name.
 There are 32 Keywords in C.
 C Keywords are also called as reserved words.

DiSHA Computer Institute, Kopargaon 12


 Following are the list of keywords :

auto double goto signed


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

 Data types :
C data types are defined as the data storage format that a variable can store
a data to perform a specific operation.

Data types are used to define a variable before to use in a program.


Size of variable, constant and array are determined by data types.
There are four data types in C language.

They are,

Types Data Types

Basic data types int, char, float, double

Derived data type pointer, array, structure, union

Void data type void

DiSHA Computer Institute, Kopargaon 13


 Integer Types :
The following table provides the details of standard integer types with their
storage sizes and value ranges:

Type Storage Size Value Range


1 byte -128 to 127 or 0 to 255
char
0 to 255
unsigned char 1 byte
1 byte -128 to 127
signed char
2 or 4 bytes
int -32,768 to 32,767 or -2,147,483,648 to
2,147,483,647
2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
unsigned int
2 bytes -32,768 to 32,767
short
0 to 65,535
unsigned short 2 bytes
4 bytes -2,147,483,648 to 2,147,483,647
long
0 to 4,294,967,295
unsigned long 4 bytes

To get the exact size of a type or a variable on a particular platform, you can
use the sizeof operator. The expressions sizeof(type) yields the storage size of
the object or type in bytes.

 Floating-Point Types :
The following table provides the details of standard floating-point types with
storage sizes and value ranges and their precision:

Type Storage size Value range Precision


Float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

The header file float.h defines macros that allow you to use these values and
other details about the binary representation of real numbers in your programs.

DiSHA Computer Institute, Kopargaon 14


 The void Type :
The void type specifies that no value is available. It is used in three kinds of
situations :

S.N. Types and Description


1. Function returns as void :
There are various functions in C which do not return any value or
you can say they return void. A function with no return value has the
return type as void. For example, void exit (int status);

2. Function arguments as void :


There are various functions in C which do not accept any parameter.
A function with no parameter can accept a void. For example, int
rand(void);

3. Pointers to void :
A pointer of type void * represents the address of an object, but not
its type. For example, a memory allocation function
void *malloc(size_t size); returns a pointer to void which can be
casted to any data type.

 Input /Output instruction in C :


C programming has several in-built library functions to perform input and output
tasks.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard)
whereas the printf() function sends formatted output to the standard output
(screen).

 Example for printf( ) function :

#include<stdio.h>
void main()
{
printf ( “ C Programming. ” ) ;
getch();
}

DiSHA Computer Institute, Kopargaon 15


Output :
C Programming.

 Example for printf( ) function :

#include<stdio.h>
main()
{
int no = 5;
clrscr( );
printf ( “ \n Number Is : %d ”, no ) ;
return 0;
}

Output :
Number Is : 5

 Examples for printf( ) and scanf( ) function :

#include<stdio.h>
main()
{
int no;
clrscr( );
printf ( “ \n Enter Number : ” ) ;
scanf ( “ %d ”, &no ) ;
printf ( “ \n Number Is : %d ”, no ) ;
return 0;
}

Output :
Enter Number : 3322
Number Is : 3322

The format string "%d" is used to read and display formatted in case of integers.

DiSHA Computer Institute, Kopargaon 16


#include<stdio.h>
main()
{
float no;
clrscr( );

printf ( “ \n Enter Number : ” ) ;


scanf ( “ %f ”, &no ) ;
printf ( “ \n Number Is : %f ” , no ) ;
return 0;
}

Output :
Enter Number : 33.22
Number Is : 33.220000

The format string "%f" is used to read and display the real OR floating point
numbers using float data type.

#include<stdio.h>
main()
{
char chr;
clrscr( );
printf ( “ \n Enter Character : ” ) ;
scanf ( “ %c ”, &chr ) ;
printf ( “ \n Character Is : %c ”, chr ) ;
return 0;
}

Output :
Enter Character : M
Character Is : M

The format string "%c" is used to read and display alphabet using char data type.

DiSHA Computer Institute, Kopargaon 17


 Examples for C ASCII code.

#include<stdio.h>
main()
{
char chr;
printf ( “\n Enter Character” ) ;
scanf ( “ %c ”, &chr ) ;
printf ( “ \nCharacter is : %c ” , chr );
printf ( “ \n ASCII value of %c Is : %d ”, chr, chr ) ;
return 0;
}

Output :
Enter Character : g
Character Is : g
ASCII value of g Is : 103

 Escape sequence :
Escape sequence Meaning
\\ \ character
\' ' character
\” “ character
\? ? character
\a Alert Bell
\b Backspace
\f Form feed
\n New Line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits

DiSHA Computer Institute, Kopargaon 18


 Operators in C :
An operator is a symbol that tells the compiler to perform specific mathematical
or logical functions. C language is rich in built-in operators and provides the
following types of operators:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Conditional Operators
 Bitwise Operators
 Assignment Operators
 Special Operators

 Arithmetic Operators :
An arithmetic operator performs mathematical operations such as addition,
subtraction and multiplication on numerical values (constants and variables).

The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


+ Adds two operands. A + B = 30

- Subtracts second operand from the first. A - B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an B%A=0


integer division.

++ Increment operator increases the integer value by A++ = 11


one.

-- Decrement operator decreases the integer value by A-- = 9


one.

DiSHA Computer Institute, Kopargaon 19


 Example to understand all the arithmetic operators available in C :

#include <stdio.h>
void main()
{
int a = 21,b = 10, c ;

c = a + b;
printf("\nAddition is : %d", c );

c = a - b;
printf("\nSubtraction is : %d", c );

c = a * b;
printf("\nMultiplication is : %d", c );

c = a / b;
printf("\nDivision is : %d", c );

c = a % b;
printf("\nModulus is : %d", c );

c = ++a;
printf("\nIncrement of a is : %d", c );

c = - -a;
printf("\nDecrement of a is : %d", c );

getch();
}

When you compile and execute the program, it produces the following result

Addition is : 31
Subtraction is : 11
Multiplication is : 210
Division is : 2
Modulus is : 1
Increment of a is : 22
Decrement of a is : 20

DiSHA Computer Institute, Kopargaon 20


 Relational Operators :
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20, then:

Operator Description Example


== Checks if the values of two operands are equal (A == B) is not
or not. If yes, then the condition becomes true. true

!= Checks if the values of two operands are equal (A != B) is true.


or not. If the values are not equal, then the
condition becomes true.

> Checks if the value of left operand is greater (A > B) is not


than the value of right operand. If yes, then true.
the condition becomes true.

< Checks if the value of left operand is less than (A < B) is true.
the value of right operand. If yes, then the
condition becomes true.

>= Checks if the value of left operand is greater (A >= B) is not


than or equal to the value of right operand. If true.
yes, then the condition becomes true.

<= Checks if the value of left operand is less than (A <= B) is true.
or equal to the value of right operand. If yes,
then the condition becomes true.

DiSHA Computer Institute, Kopargaon 21


 Try following example to understand all the relational operators available in C:

#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
printf("\na is equal to b\n" );
}
else
{
printf("\na is not equal to b\n" );
}
if ( a < b )
{
printf("\na is less than b\n" );
}
else
{
printf("\na is not less than b\n" );
}
if ( a > b )
{
printf("\na is greater than b\n" );
}
else
{
printf("\na is not greater than b\n" );
}
a = 5;
b = 20;
if ( a <= b )
{
printf("\na is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("\nb is either greater than or equal to b\n" );
}
}

DiSHA Computer Institute, Kopargaon 22


When you compile and execute the program, it produces the following result :

a is not equal to b
a is not less than b
a is greater than b
a is either less than or equal to b
b is either greater than or equal to b

 Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −

Operator Description Example


&& Called Logical AND operator. If both the (A && B) is
operands are non-zero, then the condition false.
becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is


operands is non-zero, then the condition becomes true.
true.

! Called Logical NOT Operator. It is used to !(A && B) is


reverse the logical state of its operand. If a true.
condition is true, then Logical NOT operator will
make it false.

 Try following example to understand all the Logical operators available in C:

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) equals to %d \n", result);

result = (a == b) && (c < b);

DiSHA Computer Institute, Kopargaon 23


printf("(a == b) && (c < b) equals to %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) equals to %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) equals to %d \n", result);

result = !(a != b);


printf("!(a == b) equals to %d \n", result);

result = !(a == b);


printf("!(a == b) equals to %d \n", result);

return 0;
}

When you compile and execute the program, it produces the following result :

(a == b) && (c > b) equals to 1


(a == b) && (c < b) equals to 0
(a == b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0

Explanation of logical operator program

 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b)


is 1 (true).
 (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
 (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
 (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b)
are 0 (false).
 !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b)
is 1 (true).
 !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0
(false).

DiSHA Computer Institute, Kopargaon 24


 Conditional / Ternary Operator ( ? : ) :

A conditional operator is a ternary operator, that is, it works on 3 operands.

Conditional Operator Syntax :

conditionalExpression ? expression1 : expression2

The conditional operator works as follows:

 The first expression conditionalExpression is evaluated first. This


expression evaluates to 1 if it's true and evaluates to 0 if it's false.
 If conditionalExpression is true, expression1 is evaluated.
 If conditionalExpression is false, expression2 is evaluated.

 Following example to understand all the conditionl operators available in C:

#include <stdio.h>
void main()
{
char February;
int days;
clrscr();

printf("\nIf this year is leap year, enter 1.\n If not enter any integer: ");
scanf("%c",&February);

days = (February == '1') ? 29 : 28;

printf("\nNumber of days in February = %d",days);


getch();
}

// If test condition (February == 'l') is true, days equal to 29.


// If test condition (February =='l') is false, days equal to 28.

When you compile and execute the program, it produces the following result :

If this year is leap year, enter 1.


If not enter any integer: 1
Number of days in February = 29

DiSHA Computer Institute, Kopargaon 25


 Bitwise Operators :
Bitwise operators work on bits and perform bit-by-bit operation. The truth table
for &, |, and ^ is as follows:

p q p&q p|q p ^q
0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13; in binary format, they will be as follows:


A = 0011 1100
B = 0000 1101
-----------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

The following table lists the bitwise operators supported by C. Assume variable
„A‟ holds 60 and variable „B‟ holds 13, then:

Operator Description Example


& Binary AND Operator copies a bit to the (A & B) = 12, i.e.,
result if it exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in
(A | B) = 61, i.e.,
either operand. 0011 1101
^ Binary XOR Operator copies the bit if it is set
(A ^ B) = 49, i.e.,
in one operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary (~A ) = -61, i.e.,
and has the effect of 'flipping' bits. 1100 0011 in 2's
complement form.
<< Binary Left Shift Operator. The left operands A << 2 = 240, i.e.,
value is moved left by the number of bits 1111 0000
specified by the right operand.
>> Binary Right Shift Operator. The left A >> 2 = 15, i.e.,
operands value is moved right by the number 0000 1111
of bits specified by the right operand.

DiSHA Computer Institute, Kopargaon 26


 Example :
Try the following example to understand all the bitwise operators available in C:

#include <stdio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("\n a & b is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("a | b is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("\n a ^ b c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("\n~a is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("\nValue of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("\nValue of c is %d\n", c );
getch();
}

When you compile and execute the program, it produces the following result :

a & b is 12
a | b is 61
a ^ b is 49
~a is -61
a << 2 is 240
a >> 2 is 15

DiSHA Computer Institute, Kopargaon 27


 Assignment Operators :
The following table lists the assignment operators supported by the C language:

Operator Operator Description Example


= Simple assignment operator. Assigns C = A + B will assign
values from right side operands to left the value of A + B to C
side operand.
+= Add AND assignment operator. It adds C += A is equivalent to
the right operand to the left operand and C = C + A
assigns the result to the left operand.
-= Subtract AND assignment operator. It C -= A is equivalent to
subtracts the right operand from the left C = C - A
operand and assigns the result to the left
operand.
*= Multiply AND assignment operator. It C *= A is equivalent to
multiplies the right operand with the left C = C * A
operand and assigns the result to the left
operand.
/= Divide AND assignment operator. It C /= A is equivalent to
divides the left operand with the right C = C / A
operand and assigns the result to the left
operand.
%= Modulus AND assignment operator. It C %= A is equivalent to
takes modulus using two operands and C = C % A
assigns the result to the left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as
C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as
C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as
C=C&2
^= Bitwise exclusive OR and assignment C ^= 2 is same as
Operator. C=C^2
|= Bitwise inclusive OR and assignment C |= 2 is same as C =
Operator. C|2

DiSHA Computer Institute, Kopargaon 28


 Example :
Try the following example to understand all the assignment operators in C:

#include <stdio.h>
int main()
{
int a = 5, c;

c = a;
printf("c = %d \n", c);

c += a; // c = c + a
printf("c = %d \n", c);

c -= a; // c = c - a
printf("c = %d \n", c);

c *= a; // c = c * a
printf("c = %d \n", c);

c /= a; // c = c / a
printf("c = %d \n", c);

c %= a; // c = c % a
printf("c = %d \n", c);

return 0;
}

When you compile and execute the program, it produces the following result:

c=5
c = 10
c=5
c = 25
c=5
c=0

DiSHA Computer Institute, Kopargaon 29


 Special Operators :
 Comma (“,”)Operator :
Comma operators are used as expression saperator.

For example:

int a, b=5, c;

 Referance/Address (“&”) Operator :


It uses for assign address of the variables.
It returns the pointer address of the variable.

 Dereference/Pointer ("*") Operater :


It uses for pointer variables.
It operates on a pointer variable, and returns l-value equivalent to the
value at the pointer address. This is called "dereferencing" the pointer

For example:

int *p;
int a;
p=&a

DiSHA Computer Institute, Kopargaon 30


 Operator Precedence in C :
Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has a higher precedence
than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a


higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.

Category Operator Associativity


Postfix () [ ] -> ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

DiSHA Computer Institute, Kopargaon 31


 Example :
Try the following example to understand operator precedence in C:

#include <stdio.h>
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;

e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );

e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );

e = (a + b) * (c / d); // (30) * (15/5)


printf("Value of (a + b) * (c / d) is : %d\n", e );

e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );

return 0;
}

When you compile and execute the program, it produces the following result:

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

DiSHA Computer Institute, Kopargaon 32


Decision Making
 Introduction to controls :
After learning basics of „C‟, you can write simple „C‟ programs where no multiple
conditions and decisions are needed. To keep control on the programs some special
tools are used. These tools are known as controls the statements used to control the
program are called as control statements control statement controls the flow of
program execution.

The purpose of control statement can be three types.

1. Selection 2. Repetition 3. Sequence

Selection is the type of control which is used to select the condition from the group of
conditions. After choosing a particular condition it gets execute. The selection tool is
known as decision making if else and switch case loops are used to select a condition
at a time from the multiple choices to execute it.

Another type of control statement is Repetition and Sequence. Sometimes user may
wish to repeat the certain statement or instructions with the help of initial condition
and final condition user can repeat the statement. Repetition and sequencing start
with initial condition and terminates the final condition occurs. Sequencing is
execution of statements depending on the condition.

The control used for repetition and sequencing are for and while loops. The „C‟
statements is single line instruction terminated by semicolon (;). On other hand loop
can be set of instructions reputedly called. Loop iterates but statement alone without
loop cannot repeat automatically.

 Decision Making using if loop :


Describe if-else statement :
Decision making is used to take a particular decision regarding selection of a
particular condition simple if statement can be used to check whether condition is
true or not. In simple if statement only true part is included. The first loop for
decision making is if.

The following syntax for representing simple if :

if(condition)
{
--- statements
---
}

DiSHA Computer Institute, Kopargaon 33


For e.g. :

if(x==10)
{
y=x+5;
}

In simple if just true part of the condition is included. In above example it


checks that if x==10 the y will become x+5. This called as simple if statement. Now
here if you want to specify more conditions then again and again you have add a
condition using if. So instead of that we can use another form of if loop i.e. if else loop.

 if else loop :
The general form of if else is as follows: it includes two parts one is called true part
and another is called false part. The statement enclosed in if brackets would get
execute if the condition if true otherwise if condition becomes false then else
statements will get execute. The general form of if else is as follows:
Entry
if(condition)
{
--- statements
--- Test
False
} Expressio
else n?
{
-- statements True
--
}
Fig. if else loop condition

The above syntax indicates that the condition which generates only two results, are
checked using simple if else. The result of this type of condition can be either yes/no
or true/false etc. Following is the flow chart representation of if statement.

The Fig. shows branching of two way decisions. Decisions can be either yes/no entry
is a point from where condition is false and other is true when condition is true.

Let‟s discuss a simple example to explain simple if else. The program would check if
first number is greater than second number. If it is true then first number is
displayed as greater number otherwise the else part will get execute. Second part
indicates that second number is greater.

DiSHA Computer Institute, Kopargaon 34


Program 1 : Comparison of two numbers

/* Comparision of two numbers */


// Comp.c

#include<stdio.h>
void main()
{
int num1=0,num2=0;
clrscr();
printf(“\n Enter Two Number‟s : “);
scanf(“ %d %d”,&num1, &num2); // checking condition if num1>num2
if(num1>num2)
{
printf(“\n The Greater Number Is : %d”,num1); // Display num1
} is greater
else
{
Printf(“\n The Greater Number Is : %d”,num2); // Display num2
} is greater
getch();
}

Enter Two Number‟s : 23 45


The Greater Number Is : 45

DiSHA Computer Institute, Kopargaon 35


Program 2 : Accept number from user and find whether it is even or odd.

/* Program to find whether number is even or odd. */

#include<stdio.h>
void main()
{
int num=0;
clrscr();
printf(“\n Enter The Number : “);
scanf(“ %d ”,&num); // checking condition if num%2==0
if(num%2==0)
{
printf(“\n %d is Even Number”,num); // Display num is Even
}
else
{
Printf(“\n %d is Odd Number”,num); // Display num is Odd
}
getch();
}

Enter The Number : 22


22 is Even Number

DiSHA Computer Institute, Kopargaon 36


Program 3 : Check whether number is positive or negative.

#include<stdio.h>
void main()
{
int num=0;
clrscr();
printf(“\n Enter The Number : “); // checking condition if num>0
scanf(“ %d ”,&num);
if(num>0)
{
printf(“\n %d is Positive Number”,num); // Display num is positive
}
else
{
Printf(“\n %d is Negative Number”,num); // Display num is Negative
}
getch();
}

Enter The Number : -22


-22 is Negative Number

Program 4 : Accept age from user and display the person is adult or not.

#include<stdio.h>
void main()
{
int age=0;
clrscr();
printf(“\n Enter Age : “); // checking condition if age>=18
scanf(“ %d ”,&age);
if(age>=18)
{
printf(“\n The Person is Adult”); // Display Person is Adult
}
else
{
Printf(“\n The Person is Not Adult”); // Display Person is Not Adult
}
getch();
}

DiSHA Computer Institute, Kopargaon 37


Program 5 : Accept character from user and check whether it is vowel or consonant.
[ a, e, i, o, u are Vowels ].

#include<stdio.h>
void main()
{
char code;
clrscr();
printf(“\n Enter Character : “);
scanf(“ %c ”,&code);
if(code==‟a‟||code==‟e‟||code==‟i‟||code==‟o‟||code==‟u‟)
{ // checking for vowels
printf(“\n The %c Is Vowel”,code); // Display lt is Vowel
}
else
{
Printf(“\n The %c Is Consonant”,code); // Display lt is Consonant
}
getch();
}

Enter Character : u
The u Is Vowel

DiSHA Computer Institute, Kopargaon 38


In the above example to put the multiple conditions in the if statement „ || „ operator
is used. It will check for character to be „a‟ or „e‟ or „i‟ or „o‟ or „u‟. If character is having
any one of the value from given set then it is declared as vowel. Else it is declared as
consonant, If will get executed as true if any one of the condition is true.

 If else if Ladder :
If else if ladder is used when there are multiple conditions to be checked. So you can
put multiple if‟s with else so that checking of conditions will be in the sequence.
Following is the general form of if else ladder.

if(condition 1)
{
---
}
else if(condition 2)
{
--
}
else
{
--
}

The above general form shown only 3 conditions. One is the condition 1 if it is true,
then other is condition 2 and third is else part i.e. when condition 2 fails. In this way
user can put multiple conditions using if else if ladder. The conditions get evaluated
from top to the down.

Following fig is the representation of the if else if ladder. When first condition comes
false, another condition attached to it. Again if next condition is there then it is
attached to false part. Like this conditions are attached with each other like ladder.
The statement which are to be execute when condition become true are written with
the help of the loop.

DiSHA Computer Institute, Kopargaon 39


True

Program 6 : Using if else if ladder accept single character from user as following and
declare the designation. Display the menu of the following.

Designation character :
Manager – m
Supervisor – s
Clerk – c
Worker – w

#include<stdio.h>
void main()
{
char code;
clrscr();

DiSHA Computer Institute, Kopargaon 40


printf(“\n Designation character :”);
printf(“\n manager - m”);
printf(“\n supervisor - s”);
printf(“\n clerk - c”);
printf(“\n worker - w”);
printf(“\n enter character : “);
scanf(“ %c ”,&code);
if(code==‟m‟)
{
printf(“\n the designation is manager…”);
}
else if(code==‟s‟)
{
printf(“\n the designation is supervisor…”);
}
else if(code==‟c‟)
{
printf(“\n the designation is clerk…”);
}
else if(code==‟w‟)
{
printf(“\n the designation is worker…”);
}
else
{
printf(“\n invalid character entered…”);
}
getch();
}

Designation character :
manager – m
supervisor – s
clerk – c
worker – w
enter character : m
the designation is manager…

DiSHA Computer Institute, Kopargaon 41


Program 7 : Display the following menu and do the operation as per user‟s choice.
Square of number
Cube of number
Octal number
Hexadecimal number

/* Display menu for operation and accept choice number from user. */

#include<stdio.h>
void main()
{
int num=0, choice=0;
clrscr();
printf(“\n 1. Square of Number”);
printf(“\n 2. Cube of Number”);
printf(“\n 3. Octal Number”);
printf(“\n 4. Hexadecimal Number”);
printf(“\n Enter Your Choice : “);
scanf(“ %d ”,&choice);
if(choice==1)
{
printf(“\n The Square of Number Is : %d“,num*num);
}
else if(choice==2)
{
printf(“\n The Cube of Number is : %d”,num*num*num);
}
else if(choice==3)
{
printf(“\n The Equivalent Octal Number of %d : %o”,num,num);
}
else if(choice==4)
{
printf(“\n The Equivalent Hexadecimal Number of %d is : %x”,num,num);
}
else
{
printf(“\n Invalid Choice…”);
}
getch();
}

DiSHA Computer Institute, Kopargaon 42


Output :

Square of Number
Cube of Number
Octal Number
Hexadecimal Number

Enter Your Choice : 2


Enter Number : 5
The Cube of Number is : 125

Program 8 : Comparison of 3 numbers to find greatest number.

#include<stdio.h>
void main()
{
int no1=0,no2=0,no3=0;
clrscr();
printf(“\n Enter 3 Numbers to Compare : “);
scanf(“%d %d %d”,&no1,&no2,&no3);

if(no1>=no2 && no1>=no3)


{
printf(“\n The Greatest Number is : %d”,no1);
}
else if(no2>=no1 && no2>=no3)
{
printf(“\n The Greatest Number is : %d”,no2);
}
else if(no3>=no1 && no3>=no2)
{
printf(“\n The Greatest Number is : %d”,no3);
}
getch();
}

Enter 3 Numbers to Compare : 77 19 45


The Greatest Number is : 77

DiSHA Computer Institute, Kopargaon 43


Program 9 : Comparison of 3 numbers to find smallest number.

#include<stdio.h>
void main()
{
int no1=0,no2=0,no3=0;
clrscr();
printf(“\n Enter 3 Numbers to Compare : “);
scanf(“%d %d %d”,&no1,&no2,&no3);

if(no1<=no2 && no1<=no3)


{
printf(“\n The Smallest Number is : %d”,no1);
}
else if(no2>=no1 && no2>=no3)
{
printf(“\n The Smallest Number is : %d”,no2);
}
else if(no3>=no1 && no3>=no2)
{
printf(“\n The Smallest Number is : %d”,no3);
}
getch();
}

Output :

Enter 3 Numbers to Compare : 77 19 45


The Smallest Number is : 19

Program 10 : Accept percentage from user and declare the result of


following.

<50 Fail
50 – 55 - Pass class,
55 – 59 - Second class,
60 – 70 - First class,
71 – 80 - Distinction,
81 – 90 - Merit.

DiSHA Computer Institute, Kopargaon 44


#include<stdio.h>
void main()
{
int per=0;
clrscr();
printf(“\n Enter Percentage : “);
scanf(“%d”,&per);

if(per>0 && per<=50)


{
printf(“\n The Candidate is Failed…”);
}
else if(per>50 && per<=54)
{
printf(“\n The Candidate is Passed in Pass Class…”);
}
else if(per>54 && per<=59)
{
printf(“\n The Candidate is Passed in Secound Class…);
}
else if(per>60 && per<=69)
{
printf(“\n The Candidate is Passed in First Class…);
}
else if(per>70 && per<=79)
{
printf(“\n The Candidate is Passed in Distinction…);
}
else if(per>80 && per<=100)
{
printf(“\n The Candidate is Passed in Merit…);
}
else
{
printf(“\n Entered Percentage are Invalid…);
}
getch();
}

Enter Percentage : 70
The Candidate is Passed in Distinction…

DiSHA Computer Institute, Kopargaon 45


Program 11 : Accept year from user and check entered year is leap year or not.

#include <stdio.h>

void main()
{
int year;
clrscr();

printf("\nEnter a Year : ");


scanf("%d", &year);

if ( year%400 == 0)
printf("\n%d is a leap year.", year);

else if ( year%100 == 0)
printf("\n%d is not a leap year.", year);

else if ( year%4 == 0 )
printf("\n%d is a leap year.", year);

else
printf("\n%d is not a leap year.", year);

getch();
}

Output :

Enter a Year : 1993


1993 is not leap year.

Enter a Year : 2012


2012 is leap year.

DiSHA Computer Institute, Kopargaon 46


 Nested if :
When multiple conditions are introduce in a particular sequence, we may use nested
if else statements. The general form of nested if is as follows.

if(condition 1) ----------- Outer if loop


{
if(condition 2) ------- Inner if loop
{
---
}
else --------------------- else of inner loop
{
---
}
} ------------------------------ closing outer loop
else -------------------- else of outer loop
{
---
}

The above general form suggests that when loop enters in, the condition 1 is checked,
if it is true then it enters in the condition 2. Again condition 2 is checked, if it is true
then true block will get execute else the false block will get execute. Otherwise if the
condition 1 itself is false then directly the last else block will get execute. In this way
user can put multiple conditions. Let‟s solve some nested if programs.

Program 12 : Program to calculate the income tax. The details are as


follows :

If the person is male


Till 100,000 Rs. Of income there is no income tax.
Above 100,000 Rs. the tax is 10% on the income.

If the person is female


Till 1,35,000 Rs. Of income there is no income tax.
Above 1,35,000 Rs. The tax is 10% on the income.

DiSHA Computer Institute, Kopargaon 47


#include<stdio.h>
void main()
{
char code;
long int income=1;
clrscr();
printf(“\n Enter Gender[M/F] : “);
scanf(“%c”,&code);
printf(“\n Enter Annual Income : “);
scanf(“%d”,&income);
if(code==‟m‟)
{
if(income>=100000)
{

DiSHA Computer Institute, Kopargaon 48


income=((income-10000)*10/100);
printf(“%d is the income tax on %d income for Male”,income);
}
else
{
printf(“\n No income tax for Male…”);
}
}
else
{
if(code==‟F‟)
{
if(income>=135000)
{
income=((income-13500)*10/100);
printf(“%d is the income tax on %d income for Female”,income);
}
else
{
printf(“\n No Income tax for Female”);
}
}
}
getch();
}

Enter Gender [M/F] : F


Enter Annual Income : 150000
1500 is income tax on 150000 income foe Female

 The Switch Case Statement :


We have already seen if and its different types. If statement is very easy if there are
less number of conditions, but it look very confusing and complex when more
conditions are introduced. It‟s really difficult for new user to understand the logic of
nested if. So another to make the decision among multiple conditions is available.

This is switch case statement. It‟s very easy to understand the logic as well as the
sequence of the instruction and the branching of the condition. Switch statement
accept value and test for various conditions. If all conditions are false then default
statement are execute.

DiSHA Computer Institute, Kopargaon 49


The above diagram show the pictorial representation of execution logic of switch case
loop.

The conditions are cheaked one by one. The statement of case would be execute if the
condition is true. Else the control will be pass to the next case.

The different conditions in the switch are called as cases. Within those cases you can
write the statement written the statement to get execute. These case are break or
completed by break keyword. If any one of the case is true, the statement written in
the same case would get execute and the case will get break due to break keyword.
The form of switch statement is very easy

DiSHA Computer Institute, Kopargaon 50


Following are the general form of switch case statement.

switch(expression)
{
case value-1 :
statements;
break;
case value-2 :
statements;
break;
/* you can have any number of case statements */
default :
statements;
break;
}

Value -1 and value -2 … are portable conditions or cases which are to be checked.
They are the different option which are selected through switch case.

Following are the difference between the if and switch statement.

Table : Difference between if and switch statement.

If switch

If is used to check multiple conditions at Switch check single condition at a time.


a time.

If is complicated to understand. If Switch is easy to understand even if


number of conditions are more. number of conditions are more.

If provide facility to use the nesting of Nested switch is not popular as if else
the loop. nested loop.

If uses and, or, not operator to verify or Switch generally checks unique i.e.
check the condition. single character or single integer value
as its cases.

DiSHA Computer Institute, Kopargaon 51


Program 13 : Display the following menu and accept 2 numbers from user and do
following operation as per user‟s choice...

1. Addition
2. Subtraction
3. Multiplication
4. Division

#include<stdio.h>
void main()
{
int num1=0, num2=0, result=0 ,choice;
clrscr();
printf(“\n 1. Addition“);
printf(“\n 2. Subtraction“);
printf(“\n 3. Multiplication“);
printf(“\n 4. Division“);
printf(“\n Enter Your Choice : “);
scanf(“%c”,&choice);
printf(“\n Enter num1 and num2 : “);
scanf(“%d %d”,&num1, &num2);
switch(choice)
{
case 1:
{
result = num1 + num2;
printf(“\nAddition Is : “,result);
break;
}
case 1:
{
result = num1 + num2;
printf(“\nAddition Is : “,result);
break;
}
case 2:
{
result = num1 - num2;
printf(“\nSubtraction Is : “,result);
break;
}

DiSHA Computer Institute, Kopargaon 52


case 3:
{
result = num1 * num2;
printf(“\nMultiplication Is : “,result);
break;
}
case 4:
{
result = num1 / num2;
printf(“\nDivision Is : “,result);
break;
}
default:
{
printf(“\nInvalid Choice…”);
break;
}
}
getch();
}

Output :

1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter Your Choice : 1
Enter num1 and num2 : 33 22
Addition Is : 55

Program 14 : Write a program to select the class for the travelling and get the details
of the fare..

#include <stdio.h>
void main ()
{
char code;
printf(“\nA : Aeroplane…”);
printf(“\nB : Bus…”);
printf(“\nC : Car…”);
printf(“\nT : Train…”);
printf(“\nEnter Your Choice : “);

DiSHA Computer Institute, Kopargaon 53


scanf(“%c”,&code);
switch(code)
{
case 'A' :
printf("\nAeroplane Fare Is : 1000" );
break;
case 'B' :
printf("\nBus Fare Is : 800" );
break;
case 'C' :
printf("\nCar Fare Is : 600" );
break;
case 'T' :
printf("\nTrain Fare Is : 400" );
break;
default :
printf("\nInvalid Choice…" );
break
}
getch():
}

Output :

A : Aeroplane…
B : Bus…
C : Car…
T : Train…
Enter Your Choice : C

Car Fare Is : 600

Program 15 : Program to display the spellings of a number 1-10 when entered.

#include <stdio.h>
void main ()
{
int num;
clrscr();
printf(“\nEnter Number : “);
scanf(“%d”,&num);
switch(num)

DiSHA Computer Institute, Kopargaon 54


{
case 1 :
printf("\nOne…" );
break;
case 2 :
case 'C' :
printf(“\nTwo…" );
break;
case 3 :
printf("\nThree…" );
break;
case 4 :
printf("\nFour…" );
break;
case5 :
printf("\nFive…" );
break;
case 6 :
case 'C' :
printf(“\nSix…");
break;
case 7 :
printf("\nSeven…" );
break;
case 8 :
printf("\nEight…" );
break;
case 9 :
printf("\nNine…" );
break;
case 10 :
printf(“\nTen…" );
break;
default :
printf("\nInvalid Number…\n" );
break
}
getch():
}

Enter Number : 4
Four…

DiSHA Computer Institute, Kopargaon 55


Program 16 : Program for grad(A or B or C…) give suggestion on grad.

#include <stdio.h>
void main ()
{
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well Done…\n" );
break;
case 'D' :
printf("You Passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid Grade\n" );
break
}
printf("Your Grade Is : %c\n", grade );
getch():
}

Well Done…
Your Gread Is : B…

 Break Statement :

The break statement in C programming has the following two usages :

 When a break statement is encountered inside a loop, the loop is immediately


terminated and the program control resumes at the next statement following
the loop.
 It can be used to terminate a case in the switch statement

DiSHA Computer Institute, Kopargaon 56


The break statement is used to break the control in the loops. Or in the general
statements. It is used to break the sequence.

E.g. we have seen break in the switch case statement. In switch case the break is
used to break the control of switch itself when the selected case gets execute.

The syntax for a break statement in C is as follows:

break;

 Flow Diagram :

 Program 17 :

#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;

DiSHA Computer Institute, Kopargaon 57


/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
/* terminate the loop using break statement */
break;
}
}
getch();
}

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

 Continue Statement :
The continue statement in C programming works some what like the break
statement. Instead of forcing termination, it forces the next iteration of the loop to
take place, skipping any code in between.

For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute. For the while and do...while loops, continue
statement causes the program control to pass to the conditional tests.

The syntax for a continue statement in C is as follows:

continue;

DiSHA Computer Institute, Kopargaon 58


 Flow Diagram :

 Program 18 :

#include <stdio.h>
void main ()
{
int a = 10;
clrscr();
do
{
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
getch();
}

DiSHA Computer Institute, Kopargaon 59


When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

 goto Statement :
A goto statement in C programming provides an unconditional jump from the „goto‟
to a labeled statement in the same function.

NOTE: Use of goto statement is highly discouraged in any programming language


because it makes difficult to trace the control flow of a program, making the program
hard to understand and hard to modify. Any program that uses a goto can be
rewritten to avoid them.

The syntax for a goto statement in C is as follows:

goto label;
..
label: statement;

Here label can be any plain text except C keyword and it can be set anywhere in the
C program above or below to goto statement.

DiSHA Computer Institute, Kopargaon 60


 Flow Diagram :

 Program 19 :

#include <stdio.h>
void main ()
{
int a = 10;
LOOP:
do
{
if( a == 15)
{
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
getch();
}

DiSHA Computer Institute, Kopargaon 61


When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

 While loop :
A while loop in C programming repeatedly executes a target statement as long as a
given condition is true.

The syntax of a while loop in C programming language is:

while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The


condition may be any expression, and true is any nonzero value.

The loop iterates while the condition is true. When the condition becomes false, the
program control passes to the line immediately to the loop.

DiSHA Computer Institute, Kopargaon 62


 Flow Diagram :

Here, the key point to note is that a while loop might not execute at all. When
the condition is tested and the result is false, the loop body will be skipped and
the first statement after the while loop will be executed.

 Program 20 :

#include <stdio.h>
void main ()
{
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
getch();
}

DiSHA Computer Institute, Kopargaon 63


When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

 Do while loop :
Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time.

The syntax of a do...while loop in C programming language is:

do
{
statement(s);
}while( condition );

Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop executes once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s)
in the loop executes again. This process repeats until the given
condition becomes false.

DiSHA Computer Institute, Kopargaon 64


 Flow Diagram :

 Program 21 :

#include <stdio.h>
void main ()
{
int a = 10;
do
{
printf("value of a: %d\n", a);
a=a+1;
}while( a < 20 );
getch();
}

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

DiSHA Computer Institute, Kopargaon 65


 Difference between while and do – while loop :

While Do – while
Do – while loop check the condition at
While loop check the condition at
end of loop.
beginning of loop.
Do – while loop is not accurate as while
While loop execution is more accurate as
loop.
compared to do – while loop.
It can run false condition once, because
The false condition can be run once also.
to the condition is checked at the end of
loop.
Syntax :
Syntax :
while(condition) do
{
{
---
----
---
----
}while(condition);
}

 For loop :
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.

The syntax of a do...while loop in C programming language is:

for ( initial condition; final condition; increment / decrement )


{
Body of loop OR statements;
}

Here is the flow of control in a „for‟ loop:

1. The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement
here, as long as a semicolon appears.

2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and the flow of control jumps to
the next statement just after the „for‟ loop.

DiSHA Computer Institute, Kopargaon 66


3. After the body of the „for‟ loop exeutes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the „for‟ loop terminates.

 Flow Diagram :

 Examples of For loop :

// Program to display numbers from 10 to 20.

#include <stdio.h>
void main ()
{
int a=0;
clrscr();

/* for loop execution */


for( a = 10; a <= 20; a + + )
{
printf("value of a: %d\n", a);
}
getch();
}

DiSHA Computer Institute, Kopargaon 67


When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

// Program to display even numbers from 1 to n.

#include <stdio.h>
void main ()
{
int i=0, pos=0;
clrscr();
printf(“\nEnter Last Position : “);
scanf(“%d”,&pos);
printf(“\nEven numbers is : “);
for( i = 0; i <pos; i + + )
{
if ( i % 2 = = 0 )

{
printf("%d\t", i);
}
}
getch();
}

When the above code is compiled and executed, it produces the following result:

Enter Last Position : 20


Even numbers is :
2 4 6 8 10 12 14 16 18 20

DiSHA Computer Institute, Kopargaon 68


// Program to find factorial of given number, accept number from user.

#include <stdio.h>
void main()
{
int i, n, fact = 1;
clrscr();

printf("\nEnter a number : “);


scanf("%d", &n);

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

fact = fact * i;

printf("\nFactorial of %d is = %d", n, fact);

getch();
}

When the above code is compiled and executed, it produces the following result:

Enter a number : 7
Factorial of 7 is = 5040

// program to perform addition of 1 to 100 numbers.

#include <stdio.h>
void main ()
{
int i=0, sum=0;
clrscr();
for( i = 10; i < 100; i + + )
{
sum = sum + i;
}
printf(“\nAddition of 1 to 100 numbers is :%d “, sum);
getch();
}

DiSHA Computer Institute, Kopargaon 69


When the above code is compiled and executed, it produces the following result:

Addition of 1 to 100 numbers is : 5050

// program to find given no is prime or not.

#include<stdio.h>
void main()
{
int no,i,flag;
clrscr();

printf("\nEnter a number : ");


scanf("%d",&no);

flag=0;

for(i=2;i <= no/2;i++)


{
if(no%i == 0)
{
flag=1;
break;
}
}
if(flag==0)
printf("%d is Prime Number",no);

else
printf("%d is Not Prime Number",no);

getch();
}

When the above code is compiled and executed, it produces the following result:

Enter a number : 5
5 is Prime number

DiSHA Computer Institute, Kopargaon 70


/* program to accept 5 numbers from user and count the number of positive values,
negative values and zeros. */

#include <stdio.h>
void main ()
{
int i=0, no=0, cnt1=0, cnt2=0, cnt3=0;
clrscr();
for( i = 10; i < 5; i + + )
{
printf(“\nEnter Number : “);
scanf(“%d”,&no);
if(no==0)
{
cnt1++;
}
if(no<0)
{
cnt2++;
}
if(no<0)
{
cnt3++;
}
}
printf(“\nPositive No : %d\n Negative No : %d\nZeros : %d”, cnt2++, cnt3++,
cnt1++);
getch();
}

When the above code is compiled and executed, it produces the following result:

Enter Number : 33
Enter Number : 22
Enter Number : -33
Enter Number : -22
Enter Number : 0

Positive No : 2
Negative No : 2
Zeros : 1

DiSHA Computer Institute, Kopargaon 71


 Nested for loop :
Nested for is used to put for loop within for loop this type of loop is used for
complicated applications.

The syntax of a nested for in C programming language is:

for ( initial condition; final condition; increment/decrement )


{
for ( initial condition; final condition; increment/decrement )
{
statement(s);
}
}

DiSHA Computer Institute, Kopargaon 72


 Program to print the following pattern accept position from user.

*
**
***
****

#include<stdio.h>
void main()
{
int i=0,j=0,pos=0;
clrscr();

printf("\nEnter Position : ");


scanf("%d",&pos);

for(i=1;i<=pos;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf("*");
}
}
getch();
}

Enter Position : 4

*
**
***
****

DiSHA Computer Institute, Kopargaon 73


 Program to print the following pattern accept position from user.

1
23
456
7 8 9 10

#include<stdio.h>
void main()
{
int i=0,j=0,pos=0,cnt=1;
clrscr();
printf("\nEnter Position : ");
scanf("%d",&pos);
for(i=1;i<=pos;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf("%d ",cnt);
cnt++;
}
}
getch();
}

Enter Position : 4

1
23
456
7 8 9 10

DiSHA Computer Institute, Kopargaon 74


 Program to print the following pattern accept position from user.

1
22
333
4444
55555

#include<stdio.h>
void main()
{
int i=0,j=0,pos=0;
clrscr();
printf("\nEnter Position : ");
scanf("%d",&pos);
for(i=1;i<=pos;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf("%d”,i);
}
}
getch();
}

Enter Position : 5

1
22
333
4444
55555

DiSHA Computer Institute, Kopargaon 75


 Program to print the following half pyramid using alphabets.

A
B B
C CC
D DDD
E EE E E

#include <stdio.h>
void main()
{
int i, j;
char input, alphabet = 'A';
clrscr();
printf("Enter the uppercase character you want to print in last row: ");
scanf("%c",&input);

for(i=1; i <= (input-'A'+1); ++i)


{
for(j=1;j<=i;++j)
{
printf("%c", alphabet);
}
++alphabet;

printf("\n");
}
getch();
}

Enter the uppercase character you want to print in last row: E

A
BB
CCC
DDDD
EEEEE

DiSHA Computer Institute, Kopargaon 76


 Program to print the following pattern accept position from user.

55555
4444
333
22
1

#include<stdio.h>
void main()
{
int i=0,j=0,pos=0;
clrscr();
printf("\nEnter Position : ");
scanf("%d",&pos);
for(i=pos;i>0;i--)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf("%d",i);
}
}
getch();
}

Enter Position : 5

55555
4444
333
22
1

DiSHA Computer Institute, Kopargaon 77


 Program to print the following pattern accept position from user.

54321
4321
321
21
1

#include<stdio.h>
void main()
{
int i=0,j=0,pos=0;
clrscr();
printf("\nEnter Position : ");
scanf("%d",&pos);
for(i=pos;i>0;i--)
{
printf("\n");
for(j=i;j>0;j--)
{
printf("%d ",j);
}
}
getch();
}

Enter Position : 5

54321
4321
321
21
1

DiSHA Computer Institute, Kopargaon 78


 Program to print the following pattern.

12345
1234
123
12
1

#include <stdio.h>
void main()
{
int i, j, rows;
clrscr();
printf("Enter number of rows: ");
scanf("%d",&rows);

for(i=rows; i>=1; --i)


{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
getch();
}

Enter number of rows: 5

12345
1234
123
12
1

DiSHA Computer Institute, Kopargaon 79


 Program to print the full pyramid using „*‟.

*
***
*****
*******
*********

#include <stdio.h>
int main()
{
int i, space, rows, k=0;

printf("Enter number of rows: ");


scanf("%d",&rows);

for(i=1; i<=rows; ++i, k=0)


{
for(space=1; space<=rows-i; ++space)
{
printf(" ");
}

while(k != 2*i-1)
{
printf("* ");
++k;
}

printf("\n");
}

return 0;
}

Enter number of rows: 5

*
***
*****
*******
*********

DiSHA Computer Institute, Kopargaon 80


 Program to print the full pyramid using numbers.

1
232
34543
4567654
567898765

#include <stdio.h>
int main()
{
int i, space, rows, k=0;

printf("Enter number of rows: ");


scanf("%d",&rows);

for(i=1; i<=rows; ++i, k=0)


{
for(space=1; space<=rows-i; ++space)
{
printf(" ");
}

while(k != 2*i-1)
{
printf("* ");
++k;
}

printf("\n");
}

return 0;
}

Enter number of rows: 5

1
232
34543
4567654
567898765

DiSHA Computer Institute, Kopargaon 81


 Program for find the prime numbers from 2 to 20.

#include <stdio.h>
void main ()
{
int i, j;
for(i=2; i<100; i++)
{
for(j=2; j <= (i/j); j++)

if( ! ( i % j ))
break; // if factor found, not prime

if( j > ( i / j ))

printf("%d is prime\n", i);

}
getch()
}

Output :

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime

DiSHA Computer Institute, Kopargaon 82


Arrays
 Arrays :
Explain the need for array variable.
To know more about the data types in „C‟.
The data types are of three types.

 Derived types
 Fundamental types
 User defined types

Data Types

Derived Types Fundamental Types User Defined Types

Arrays Integer Type Structures


Functions Float Type Union
Pointers Character Type Enumerations

Fig. Data Types

 Defination :
Array is collection of variables of same data type arranged one by one in the
sequence. You can store group of data of same data type in an array. Array elements
are of same data type i.e. once array is declared as integer, then value which are
present in an array are of type integer only.

Array might be belonging to any of the data types.

Array size must be a constant value.

Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.

It is a best practice to initialize an array to zero or null while declaring, if we don‟t


assign any values to array.

DiSHA Computer Institute, Kopargaon 83


 Example for c arrays :
int a[10]; // integer array
char b[10]; // character array i.e. string

 Types of c arrays :
There are 2 types of C arrays. They are,
 One dimensional array
 Two dimensional array

 One dimensional array in c (1D) :


One dimensional array is collection of multiple elements of same data type.
Number of locations get created where we get access to all the elements one by one.

Fig. Representation of 1D array

 Array declaration, initialization and accessing of 1D Array :


 Array Declaration :
o Syntax : data_type array_name[array_size];
o Example : int roll_no[5];

 Array initialization :
o Syntax : data_type arr_name [arr_size]=(value1, value2, value3,….);
o Example : int roll_no[5]={11,22,33,44,55};

 Array Accessing :
o Syntax : arr_name[index];
o Example : roll_no[i];

DiSHA Computer Institute, Kopargaon 84


 Integer array example :
If we need an array which stores 5 integer elements, that you can declare an array
as follows :
int age [5];
int age[5]={0, 1, 2, 3, 4};

 Float array example :


float arr[5];
float arr[5]={1.0, 1.2, 1.4, 1.6, 1.8};

 Character array example :


char str[10];
char str[10]={“Hello”};

/* Program to print the contents of array. */

#include<stdio.h>
void main()
{
int i;
int arr[5] = {10,20,30,40,50};

//To initialize all array elements to 0, use int arr[5]={0};


/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */

for (i=0;i<5;i++)
{
// Accessing each variable.
printf("Value of arr[%d] is : %d \n", i, arr[i]);
}
getch();
}

 Output :

DiSHA Computer Institute, Kopargaon 85


Value of arr[0] is : 10
Value of arr[1] is : 20
Value of arr[2] is : 30
Value of arr[3] is : 40
Value of arr[4] is : 50

/* Accepting Elements From User */

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int arr[50], n;
printf("How many element you want to store in the array ? ");
scanf("%d",&n);

printf("Enter %d element to store in the array : ",n);


for(int i=0; i<n; i++)
{
scanf("%d",&arr[i]);
}
printf("The Elements in the Array is : \n");
for(i=0; i<n; i++)
{
printf("%d ",arr[i]);
}
getch();
}

 Output :

How many elements you want to store in array : 5


Enter 5 elements to store in the array : 11
22
33
44
55
The elements in the array is :
11 22 33 44 55

DiSHA Computer Institute, Kopargaon 86


// Program to accept elements from user and find its sun and average.

#include <stdio.h>
void main()
{
int marks[10], i, n, sum = 0;
float average;
printf("Enter how many numbers you want : ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number %d : ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf(“Sum Is : %d”,sum);
printf("Average Is = %f", average);
getch();
}

 Output :

Enter how many numbers you want : 5


Enter number 1 : 45
Enter number 2 : 35
Enter number 3 : 38
Enter number 4 : 31
Enter number 5 : 49
Sum Is : 198
Average is : 39.6

// Program to accept 10 elements in an array and calculate number of positive


negative numbers and zeros.

#include <stdio.h>
void main()
{
int number[5];
int i=0, cnt1=0, cnt2=0, cnt3=0;

DiSHA Computer Institute, Kopargaon 87


clrscr();
for(i=0;i<=4;i++)
{
printf("Enter number : ");
scanf("%d", &number[i]);
if(number[i]<0)
{
cnt1++;
}
if(number[i]==0)
{
cnt2++;
}
if(number[i]>0)
{
cnt3++;
}
}
printf("Number of negative numbers : “,cnt1++);
printf("Number of Positive numbers : “,cnt3++);
printf("Number of zeros : “,cnt2++);
getch();
}

 Output :

Enter numbers : 33
Enter numbers : 22
Enter numbers : 0
Enter numbers : -33
Enter numbers : -22
Number of negative numbers : 2
Number of Positive numbers : 2
Number of zeros : 1

// Program to find largest and smallest number in an array

#include<stdio.h>
void main()
{
int a[50],size,i,big,small;

DiSHA Computer Institute, Kopargaon 88


printf("\nEnter the size of the array: ");
scanf("%d",&size);
printf("\nEnter %d elements in to the array: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);

big=a[0];
for(i=1;i<size;i++)
{
if(big<a[i])
big=a[i];
}
printf("Largest element: %d",big);
small=a[0];
for(i=1;i<size;i++)
{
if(small>a[i])
small=a[i];
}
printf("Smallest element: %d",small);
getch();
}

 Output :

Enter the size of the array: 4


Enter 4 elements in to the array: 2 7 8 1
Largest element: 8
Smallest element: 1

/*C Program to accept & add value of 2 array & display the sum of arrays*/

#include<stdio.h>
void main()
{
int i,a[5],b[5],c[5];
clrscr();
printf("\nReading the 1st array\n");
for (i=0;i<5;i++)
{

DiSHA Computer Institute, Kopargaon 89


printf("Enter the value :");
scanf("%d",&a[i]);
}
printf("\nReading the 2nd array\n");
for (i=0;i<5;i++)
{
printf("Enter the value :");
scanf("%d",&b[i]);
}
printf("\nThe addition of 2 array is\n");
for(i=0;i<5;i++)
{
c[i]=a[i]+b[i];
printf("\nThe sum of %d & %d is %d",a[i],b[i],c[i]);
}
getch();
}

 Output :

Reading the 1st array


Enter the value : 2
Enter the value : 5
Enter the value : 100
Enter the value : 77
Enter the value : 53

Reading the 2nd array


Enter the value : 8
Enter the value : 90
Enter the value : 50
Enter the value : 12
Enter the value : 87

The addition of 2 array is


10 95 150 89 120

DiSHA Computer Institute, Kopargaon 90


//C program for Arranging 5 Numbers in Ascending Order.

#include<stdio.h>
void main()
{
int a[5],i,j,t;
clrscr();
printf("Enter 5 nos. : ");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
for (i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("Ascending Order is : ");
for(j=0;j<5;j++)
printf("%d\t",a[j]);
getch();
}

 Output :

Enter 5 nos : 5 8 9 1 2
Ascending order is : 1 2 5 8 9

DiSHA Computer Institute, Kopargaon 91


 Two dimensional array in c :

Two-dimensional array are those type of array, which has finite number of rows and
finite number of columns.
Two dimensional array is nothing but array of array.

 Syntax : data_type array_name[num_of_rows][num_of_column];

The following fig. shows diagrammatic structure of 2D array.

 Array declaration, initialization and accessing :

 Array declaration :

o Syntax : data_type arr_name [num_of_rows][num_of_column];

 Array initialization :

o Syntax : data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};

 Array accessing :

o Syntax : arr_name[index];

 Example :

Integer array example :

int arr[2][2];
int arr[2][2] = {1,2, 3, 4};

DiSHA Computer Institute, Kopargaon 92


// Program for 2D array.

#include<stdio.h>
void main()
{
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
}
}
getch();
}

 Output :

value of arr[0] [0] is 10


value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

#include <stdio.h>
void main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

DiSHA Computer Institute, Kopargaon 93


for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
scanf("%d", &first[c][d]);
}
}
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
scanf("%d", &second[c][d]);
}
}
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
getch();
}

 Output :

Enter the number of rows and columns of matrix


2
2
Enter the elements of first matrix
1 2
3 4
Enter the elements of second matrix
5 6
2 1
Sum of entered matrices:-
6 8
5 5

DiSHA Computer Institute, Kopargaon 94


// program for addition and subtraction of two 3x3 matrix.

#include<stdio.h>
void main()
{
int i, j, mat1[10][10], mat2[10][10], add[10][10], sub[10][10];
int row1, col1, row2, col2;

printf("\nEnter the number of Rows of Mat1 : ");


scanf("%d", &row1);
printf("\nEnter the number of Cols of Mat1 : ");
scanf("%d", &col1);

printf("\nEnter the number of Rows of Mat2 : ");


scanf("%d", &row2);
printf("\nEnter the number of Columns of Mat2 : ");
scanf("%d", &col2);
for (i = 0; i < row1; i++)
{
for (j = 0; j < col1; j++)
{
printf("Enter the Element a[%d][%d] : ", i, j);
scanf("%d", &mat1[i][j]);
}
}
for (i = 0; i < row2; i++)
{
for (j = 0; j < col2; j++)
{
printf("Enter the Element b[%d][%d] : ", i, j);
scanf("%d", &mat2[i][j]);
}
}
for (i = 0; i < row1; i++) //Addition of two matrices
{
for (j = 0; j < col1; j++)
{
add[i][j] = mat1[i][j] + mat2[i][j];
}
}
for (i = 0; i < row1; i++) //Subtraction of two matrices
{
for (j = 0; j < col1; j++)

DiSHA Computer Institute, Kopargaon 95


{
sub[i][j] = mat1[i][j] - mat2[i][j];
}
}
printf("\nThe addition of two Matrices is : \n");
for (i = 0; i < row1; i++)
{
for (j = 0; j < col1; j++)
{
printf("%d\t", add[i][j]);
}
printf("\n");
}
printf("\nThe Subtraction of two Matrices is : \n");
for (i = 0; i < row1; i++)
{
for (j = 0; j < col1; j++)
{
printf("%d\t", sub[i][j]);
}
printf("\n");
}
getch();
}

 Output :

Enter the number of Rows of Mat1 : 3


Enter the number of Columns of Mat1 : 3

Enter the number of Rows of Mat2 : 3


Enter the number of Columns of Mat2 : 3

Enter the Element a[0][0] : 15


Enter the Element a[0][1] : 17
Enter the Element a[0][2] : 12
Enter the Element a[1][0] : 11
Enter the Element a[1][1] : 5
Enter the Element a[1][2] : 10
Enter the Element a[2][0] : 57
Enter the Element a[2][1] : 74
Enter the Element a[2][2] : 90

DiSHA Computer Institute, Kopargaon 96


Enter the Element b[0][0] : 5
Enter the Element b[0][1] : 7
Enter the Element b[0][2] : 9
Enter the Element b[1][0] : 11
Enter the Element b[1][1] : 10
Enter the Element b[1][2] : 4
Enter the Element b[2][0] : 21
Enter the Element b[2][1] : 27
Enter the Element b[2][2] : 9

The addition of two Matrices is :


20 24 21
22 15 14
78 104 99

The Subtraction of two Matrices is :


10 10 3
0 -5 6
36 47 81

//C program for 2x2 matrix multiplication.

#include<stdio.h>

void main()
{
int mat1[10][10], mat2[10][10], mult[10][10];
int i, j;

clrscr();

printf("\nEnter Matrix 1 Element's : \n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&mat1[i][j]);
}
}

printf("\nEnter Matrix 2 Element's : \n");

DiSHA Computer Institute, Kopargaon 97


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&mat2[i][j]);
}
}
printf("\nElements of Matrix 1 : \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",mat1[i][j]);
}
printf("\n");
}

printf("\nElements of Matrix 2 : \n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",mat2[i][j]);
}
printf("\n");
}

mult[0][0]=mat1[0][0]*mat2[0][0] + mat1[0][1]*mat2[1][0];
mult[0][1]=mat1[0][0]*mat2[0][1] + mat1[0][1]*mat2[1][1];
mult[1][0]=mat1[1][0]*mat2[0][0] + mat1[1][1]*mat2[1][0];
mult[1][1]=mat1[1][0]*mat2[0][1] + mat1[1][1]*mat2[1][1];

printf("\nMultiplication is : \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",mult[i][j]);
}
printf("\n");
}
getch();
}

DiSHA Computer Institute, Kopargaon 98


 Output :

Enter Matrix 1 Element's :


1 2
3 4

Enter Matrix 2 Element's :


1 2
3 4

Elements of Matrix 1 :
1 2
3 4

Elements of Matrix 3 :
1 2
3 4

Multiplication is :
7 10
15 22

DiSHA Computer Institute, Kopargaon 99


 String Related Library Functions :
In previous section we have seen many programs to manipulate the strings. „C‟
library has ample of library functions. They are categorized into different
categories like console, input/output, math, etc. Among these categories one
important category is String. The file string.h is collection of string related
library functions.
The large number of string handling functions available in the standard
library "string.h".

Few commonly used string handling functions are discussed below:

 strlen( ) - String length.


 strcpy( ) - String copy
 strcat( ) - String concatenate
 strcmp( ) - String compare

Strings handling functions are defined under "string.h" header file.

#include <string.h>

 gets() and puts()


Functions gets() and puts() are two string functions to take string input from
the user and display it respectively as mentioned in the previous chapter.

#include<stdio.h>

int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}

DiSHA Computer Institute, Kopargaon 100


 C strlen() :
The strlen() function calculates the length of a given string.

For e.g. :

int a = 0;
a = strlen( “ Disha-Computers ” );
In the above example value of a would be 15.

OR

char name[5] = “Mayur”;


int len = 0;
len = strlen( name );
The len variable will store 5.

 Example: C strlen( ) function :

#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Mayur";
char b[20]={'M','a','y','u','r','\0'};
char c[20];
clrscr();
printf("Enter string : ");
gets(c);

printf("Length of string a = %d \n",strlen(a));

//calculates the length of string before null charcter.


printf("Length of string b = %d \n",strlen(b));
printf("Length of string c = %d \n",strlen(c));

return 0;
}

DiSHA Computer Institute, Kopargaon 101


Output :

\Enter string : Computer


Length of string a = 5
Length of string b = 5
Length of string c = 8

 C strcpy() :
The strcpy( ) function is to copy one string to another.

It takes two arguments.

For e.g. : strcpy(str1, str2);

 Example: C strcpy( ) Function :

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Mayur";
char str2[10] = "Disha";
clrscr();
strcpy(str1, str2);
printf("\nAfter Copying str1 is : %s",str1);
printf("\nAfter Copying str2 is : %s",str2);
return 0;
}

Output :

After Copying str1 : Disha


After Copying str2 : Disha

DiSHA Computer Institute, Kopargaon 102


 C strcat() :
The function strcat( ) concatenates two strings.

In C programming, strcat( ) concatenates ( joins ) two strings.

 Example: C strcat() function :

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Mayur";
char str2[10] = "Mayur";
clrscr();
strcat(str1, str2);
printf("\nAfter Concatenation str1 is : %s",str1);

return 0;
}

Output :
After Concatenation str1 is : MayurMayur

DiSHA Computer Institute, Kopargaon 103


 C strcmp( ) :
The strcmp( ) function compares two strings with each others. If two strings
are equal then function returns 0, else the difference between two strings

The strcmp() compares two strings character by character. If the first character
of two strings are equal, next character of two strings are compared. This
continues until the corresponding characters of two strings are different or a
null character '\0' is reached.

 Example: C strcmp( ) function :

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Mayur";
char str2[10] = "Mayur";
clrscr();
if(strcmp(str1, str2)!=0)
{
printf("\n %s & %s are not Equal",str1, str2);
}
else
{
printf("\n%s & %s are Equal",str1, str2);
}
return 0;
}

Output :
Mayur & Mayur are Equal

DiSHA Computer Institute, Kopargaon 104


 String Operation Without using String Library Functions.

//Program to find string length Without Using strlen().

#include <stdio.h>
void main()
{
char s[1000], i;
clrscr();
printf("Enter a string: ");
scanf("%s", s);
for(i = 0; s[i] != '\0'; ++i);
{
printf("Length of string: %d", i);
}
getch();
}

Output :
Enter a string: Mayur
Length of string: 5

//Program to Copy String Manually Without Using strcpy().

#include <stdio.h>
void main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("\n String s2: %s", s2);
getch();
}

DiSHA Computer Institute, Kopargaon 105


Output :
Enter String s1: Mayur
String s2: Mayur

//Program to Compare Two Strings Without using strcmp()

#include <stdio.h>
void main()
{
char str1[5],str2[5];
int i,temp = 0;
clrscr();
printf("\nEnter String1 : ");
gets(str1);
printf("\nEnter String2 : ");
gets(str2);

for(i=0; (str1[i]!='\0')||(str2[i]!='\0'); i++)


{
if(str1[i] != str2[i])
{
temp = 1;
break;
}
}
if(temp == 0)
{
printf("\nStrings %s and %s are Same...",str1, str2);
}
else
{
printf("\nStrings %s and %s are Not Same...",str1, str2);
}
getch();
}

Output :
Enter String1 : Mayur
Enter String1 : Mayur
Strings Mayur and Mayur are Same...

DiSHA Computer Institute, Kopargaon 106


//Program to Concatenates two Strings Without Using strcat().

#include <stdio.h>
void main()
{
char str1[50], str2[50], i, j;
clrscr();
printf("\nEnter first string: ");
scanf("%s",&str1);
printf("\nEnter second string: ");
scanf("%s",&str2);

for(i=0; str1[i]!='\0'; ++i);


for(j=0; str2[j]!='\0'; ++j, ++i)
{
str1[i]=str2[j];
}
str1[i]='\0';
printf("\nResult is : %s",str1);
getch();
}

Output :
Enter first string: Mayur
Enter second string:Mayur
Result is :MayurMayur

DiSHA Computer Institute, Kopargaon 107


//Program to Reverse a String.

#include <stdio.h>
#include <string.h>
void main()
{
char str[50];
int len, i;
clrscr();
printf("Enter a String: ");
scanf("%s",&str);
len = strlen(str);
printf("\nReverse String Is : ");
for(i=len-1; i>=0; i--)
{
printf("%c",str[i]);
}
getch();
}

Output :
Enter a String: Mayur
Reverse String Is : ruyaM

DiSHA Computer Institute, Kopargaon 108


Function in „C‟
„A function is a group of statements or block of code that performs a specific task.‟
Every C program has at least one function, which is main( ), and all the most trivial
programs can define additional functions. You can divide up your code into separate
functions. How you divide up your code among different functions is up to you, but
logically the division is such that each function performs a specific task.

 Types of functions in C programming :


Depending on whether a function is defined by the user or already included in C
compilers, there are two types of functions in C programming

There are two types of functions in C programming:


 Standard library functions
 User defined functions

 Standard library functions :


The standard library functions are built-in functions in C programming to handle
tasks such as mathematical computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file,
these functions are available for use.

 For example :
The printf() is a standard library function to send formatted output to the screen
(display output on the screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these
functions are available for use.
Visit this page to learn more about standard library functions in C programming.

 User-defined functions :
C allow programmers to define functions. Such functions created by the user. Or C
allows you to define functions according to your need. These functions are known as
user-defined functions.
Depending upon the complexity and requirement of the program, you can create as
many user-defined functions as you want.

The general form of a function definition in C programming language is as follows :

DiSHA Computer Institute, Kopargaon 109


return_type function_name( parameter list )
{
body of the function
}

A function definition in C programming consists of a function header and a function


body. Here are all the parts of a function :

 Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.

 Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.

 Parameters − A parameter is like a placeholder. When a function is invoked, you


pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the parameters
of a function. Parameters are optional; that is, a function may contain no parameters.

 Function Body − The function body contains a collection of statements that define
what the function does.

 How user-defined function works..?‟

#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}

int main()
{
... .. ...
... .. ...

functionName();

... .. ...
... .. ...
}

DiSHA Computer Institute, Kopargaon 110


When the compiler encounters functionName(); inside the main function, control of
the program jumps to void functionName() And, the compiler starts executing the
codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the
codes inside the function definition are executed.

 Advantages of user-defined function :


 The program will be easier to understand, maintain and debug.
 Reusable codes that can be used in other programs
 A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.

 Example :
Given below is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum value between the two
numbers :

int max(int num1, int num2)


{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

 Function Declarations :
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.

A function declaration has the following parts :

return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows :

int max(int num1, int num2);

DiSHA Computer Institute, Kopargaon 111


Parameter names are not important in function declaration only their type is
required, so the following is also a valid declaration :

int max(int, int);

Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the
top of the file calling the function.

 Calling a Function :
Control of the program is transferred to the user-defined function by calling it.
While creating a C function, you give a definition of what the function has to do. To
use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned
value.

 Syntax of function call :

functionName(argument1, argument2, ...);

 Function definition :
Function definition contains the block of code to perform a specific task i.e. in this case,
adding two numbers and returning it.

 Syntax of function definition :

returnType functionName(type1 argument1, type2 argument2, ...)


{
//body of the function
}

When a function is called, the control of the program is transferred to the function definition.
And, the compiler starts executing the codes inside the body of a function.

DiSHA Computer Institute, Kopargaon 112


 For example :

#include <stdio.h>

int max(int num1, int num2); /* function declaration */

int main ()
{
int a = 100; /* local variable definition */
int b = 200;
int ret;

ret = max(a, b); /* calling a function to get max value */

printf( "Max value is : %d\n", ret );

return 0;
}

int max(int num1, int num2) /* function returning the max between two
numbers */
{
int result; /* local variable definition */

if (num1 > num2)


result = num1;
else
result = num2;
return result;
}

 Output :

Max value is : 200

 Example :

#include<stdio.h>
void introduction(); /* function declaration */

DiSHA Computer Institute, Kopargaon 113


void introduction() /* function definition */
{
printf("Hi\n");
printf("My name is Mayur…\n");
printf("How are you?");
/* there is no return statement inside this function, since its
* return type is void */
}
int main()
{
/*calling function*/
introduction();
return 0;
}

 Output :

Hi
My name is Mayur…
How are you?

 Function Arguments
If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, There are two ways in which arguments can be passed to a
function.

S.N. Call Type & Description

1. Call by value :
This method copies the actual value of an argument into the formal parameter of
the function. In this case, changes made to the parameter inside the function
have no effect on the argument.

DiSHA Computer Institute, Kopargaon 114


2. Call by reference :
This method copies the address of an argument into the formal parameter. Inside
the function, the address is used to access the actual argument used in the call.
This means that changes made to the parameter affect the argument.

A scope in any programming is a region of the program where a defined variable can
have its existence and beyond that variable it cannot be accessed.

There are three places where variables can be declared in C programming language.
1. Inside a function or a block which is called local variables.
2. Outside of all functions which is called global variables.
3. In the definition of function parameters which are called formal parameters.

Let us understand what are local and global variables, and formal parameters.

 Local Variables :
Variables that are declared inside a function or block are called local variables. They
can be used only by statements that are inside that function or block of code. Local
variables are not known to functions outside their own. The following example shows
how local variables are used. Here all the variables a, b, and c are local to main()
function.

#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}

DiSHA Computer Institute, Kopargaon 115


 Global Variables :
Global variables are defined outside a function, usually on top of the program. Global
variables hold their values throughout the lifetime of your program and they can be
accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. The following
program show how global variables are used in a program.

#include <stdio.h>

/* global variable declaration */


int g;
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}

A program can have same name for local and global variables but the value of local
variable inside a function will take preference. Here is an example.

#include <stdio.h>

/* global variable declaration */


int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;

printf ("value of g = %d\n", g);

return 0;
}

DiSHA Computer Institute, Kopargaon 116


When the above code is compiled and executed, it produces the following result :

value of g = 10

 Function that return some value :

#include<stdio.h>
#include<conio.h>
int larger(int a,int b); // function declaration

void main()
{
int i,j,k;
clrscr();
i=99;
j=112;
k=larger(i,j); // function call
printf("largest no is : %d",k);
getch();
}

int larger(int a,int b) // function declaration


{
if(a>b)
{
return a;
}
else
{
return b;
}
}

 Output :

largest no is : 112

DiSHA Computer Institute, Kopargaon 117


 Formal Parameters :
Formal parameters, are treated as local variables with-in a function and they take
precedence over global variables. Following is an example −

#include <stdio.h>
int sum(int , int)

/* global variable declaration */


int a = 20;

int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;

printf ("value of a in main() = %d\n", a);


c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}

/* function to add two integers */


int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}

When the above code is compiled and executed, it produces the following result :

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

DiSHA Computer Institute, Kopargaon 118


 Initializing Local and Global Variables :
When a local variable is defined, it is not initialized by the system, you must initialize
it yourself. Global variables are initialized automatically by the system when you
define them as follows :

Data Type Initial Default Value


int 0
char '\0'
float 0
double 0
Pointer NULL

It is a good programming practice to initialize variables properly, otherwise your


program may produce unexpected results, because uninitialized variables will take
some garbage value already available at their memory location.

 Passing arguments to a function :


In programming, argument refers to the variable passed to the function. In the above
example, two variables n1 and n2 are passed during function call.
The parameters a and b accepts the passed arguments in the function definition.
These arguments are called formal parameters of the function.

 How to pass arguments to function :

DiSHA Computer Institute, Kopargaon 119


The type of arguments passed to a function and the formal parameters must match,
otherwise the compiler throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also
should be of float type.
A function can also be called without passing an argument.

 Return Statement :
The return statement terminates the execution of a function and returns a value to
the calling function. The program control is transferred to the calling function after
return statement.

In the above example, the value of variable result is returned to the variable sum in
the main() function.

 Syntax of return statement :

return (expression);

 For example,

return a;
return (a+b);

The type of value returned from the function and the return type specified in function
prototype and function definition must match.

DiSHA Computer Institute, Kopargaon 120


 Function prototype :
A function prototype is simply the declaration of a function that specifies function's
name, parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be
used in the program.

 Syntax of function prototype :

returnType functionName(type1 argument1, type2 argument2,...);

In the above example, int addNumbers(int a, int b); is the function prototype which
provides following information to the compiler:

1. name of the function is addNumbers()


2. return type of the function is int
3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before
the main() function.

DiSHA Computer Institute, Kopargaon 121


 Difference between Call by Value and Call by Reference :

Call by value Call by reference

In call by value, a copy of actual In call by reference, the location (address)


arguments is passed to formal arguments of actual arguments is passed to formal
of the called function and any change arguments of the called function. This
made to the formal arguments in the means by accessing the addresses of actual
called function have no effect on the arguments we can alter them within from
values of actual arguments in the calling the called function.
function.

In call by value, actual arguments will In call by reference, alteration to actual


remain safe, they cannot be modified arguments is possible within from called
accidentally. function; therefore the code must handle
arguments carefully else you get
unexpected results.

 Example call by value swapping two numbers.

#include <stdio.h>

void swapByValue(int, int); /* Prototype */

int main() /* Main function */


{
int n1 = 10, n2 = 20;

/* actual arguments will be as it is */


swapByValue(n1, n2);
printf("n1: %d, n2: %d\n", n1, n2);
getch();
}

void swapByValue(int a, int b)


{
int t;
t = a; a = b; b = t;
}

DiSHA Computer Institute, Kopargaon 122


 Output :

n1: 20, n2: 10

 Example call by reference :

#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.


* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}

 Output :

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

DiSHA Computer Institute, Kopargaon 123


 Types of User-defined Functions in C Programming :
For better understanding of arguments and return value from the function,

 user-defined functions can be categorized as :


 Function with no arguments and no return value
 Function with no arguments and a return value
 Function with arguments and no return value
 Function with arguments and a return value.

 Example #1: No arguments and no return Value

#include <stdio.h>

void checkPrimeNumber(); //function declaration


int main()
{
checkPrimeNumber(); /* function call
return 0; no argument is passed to prime() /*
}
// return type of the function is void becuase no value is returned from the
function

void checkPrimeNumber() //function defination


{
int n, i, flag=0;

printf("Enter a positive integer: ");


scanf("%d",&n);

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}

DiSHA Computer Institute, Kopargaon 124


The checkPrimeNumber() function takes input from the user, checks whether it is a
prime number or not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main() function
indicates that no argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.

 Example #2: No arguments but a return value

#include <stdio.h>
int getInteger();

int main()
{
int n, i, flag = 0;

// no argument is passed to the function


// the value returned from the function is assigned to n
n = getInteger();

for(i=2; i<=n/2; ++i)


{
if(n%i==0){
flag = 1;
break;
}
}

if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
// getInteger() function returns integer entered by the user
int getInteger()
{
int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

return n;
}

DiSHA Computer Institute, Kopargaon 125


The empty parentheses in n = getInteger(); statement indicates that no argument is
passed to the function. And, the value returned from the function is assigned to n.
Here, the getInteger() function takes input from the user and returns it. The code to
check whether a number is prime or not is inside the main() function.

 Example #3: Argument but no return value

#include <stdio.h>
void checkPrimeAndDisplay(int n);

int main()
{
int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the function


checkPrimeAndDisplay(n);

return 0;
}

// void indicates that no value is returned from the function


void checkPrimeAndDisplay(int n)
{
int i, flag = 0;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}

DiSHA Computer Institute, Kopargaon 126


The integer value entered by the user is passed to checkPrimeAndDisplay() function.
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a
prime number or not and displays the appropriate message.

Example #4: Argument and a return value

#include <stdio.h>
int checkPrimeNumber(int n);

int main()
{
int n, flag;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the checkPrimeNumber() function


// the value returned from the function is assigned to flag variable
flag = checkPrimeNumber(n);

if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);

return 0;
}

// integer is returned from the function


int checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */
int i;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
return 1;
}
return 0;
}

DiSHA Computer Institute, Kopargaon 127


 Explanation :
The input from the user is passed to checkPrimeNumber() function.
The checkPrimeNumber() function checks whether the passed argument is prime or
not. If the passed argument is a prime number, the function returns 0. If the passed
argument is a non-prime number, the function returns 1. The return value is
assigned to flag variable.
Then, the appropriate message is displayed from the main() function.
To find all prime numbers between two integers, checkPrimeNumber() function is
created. This function checks whether a number is prime or not.

 Example: Prime Numbers Between Two Integers

#include <stdio.h>

int checkPrimeNumber(int n);


int main()
{
int n1, n2, i, flag;

printf("Enter two positive integers: ");


scanf("%d %d", &n1, &n2);
printf("Prime numbers between %d and %d are: ", n1, n2);

for(i=n1+1; i<n2; ++i)


{
// i is a prime number, flag will be equal to 1
flag = checkPrimeNumber(i);

if(flag == 1)
printf("%d ",i);
}
return 0;
}

// user-defined function to check prime number


int checkPrimeNumber(int n)
{
int j, flag = 1;

for(j=2; j <= n/2; ++j)


{
if (n%j == 0)
{

DiSHA Computer Institute, Kopargaon 128


flag =0;
break;
}
}
return flag;
}

 Output :

Enter two positive integers: 12 30


Prime numbers between 12 and 30 are: 13 17 19 23 29

DiSHA Computer Institute, Kopargaon 129


 C Programming Recursion :
A function that calls itself is known as a recursive function. And, this technique is
known as recursion.

 How recursion works..?

void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}

DiSHA Computer Institute, Kopargaon 130


 The recursion continues until some condition is met to prevent it.
 To prevent infinite recursion, if...else statement (or similar approach) can be
used where one branch makes the recursive call and other doesn't.

 Example: Sum of Natural Numbers Using Recursion.

#include <stdio.h>
int sum(int n);

int main()
{
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum=%d", result);
}

int sum(int num)


{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}

 Output :

Enter a positive integer:


3
6

 Initially, the sum() is called from the main() function with number passed as an
argument.
 Suppose, the value of num is 3 initially. During next function call, 2 is passed to
the sum()function. This process continues until num is equal to 0.

DiSHA Computer Institute, Kopargaon 131


 When num is equal to 0, the if condition fails and the else part is executed returning
the sum of integers to the main() function.

 Explanation of Sum of Natural Numbers Using Recursion is as follows :

DiSHA Computer Institute, Kopargaon 132


 Example: Factorial of a Number Using Recursion.

#include <stdio.h>
long int multiplyNumbers(int n);

int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}

 Output :

Enter a positive integer: 6


Factorial of 6 = 720

 Advantages and Disadvantages of Recursion :


1. Recursion makes program elegant and cleaner. All algorithms can be defined
recursively which makes it easier to visualize and prove.

2. If the speed of the program is vital then, you should avoid using recursion. Recursions
use more memory and are generally slow. Instead, you can use loop.

DiSHA Computer Institute, Kopargaon 133


Pointers
 Introduction to pointer :
Pointers in C are easy and fun to learn. Some C programming tasks are performed
more easily with pointers, and other tasks, such as dynamic memory allocation,
cannot be performed without using pointers. So it becomes necessary to learn
pointers to become a perfect C programmer. Let's start learning them in simple and
easy steps.
The pointer is one of the powerful tools of „C‟ programming. They are very efficient.
As you know, every variable is a memory location and every memory location has its
address defined which can be accessed using ampersand (&) operator, which denotes
an address in memory.

 What are Pointers..?


A pointer is a variable used to access the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a
pointer before using it to store any variable address.
The general form of a pointer variable declaration is −

Data type *pointer_name;

Where * indicates that it is pointer declaration.

 Example :
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

Here, data type is the pointer's base type; it must be a valid C data type and pointer-
name is the name of the pointer variable. The asterisk * used to declare a pointer is
the same asterisk used for multiplication. However, in this statement the asterisk is
being used to designate a variable as a pointer.

The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory
address. The only difference between pointers of different data types is the data type
of the variable or constant that the pointer points to.

DiSHA Computer Institute, Kopargaon 134


 How to Use Pointers..?
There are a few important operations, which we will do with the help of pointers very
frequently.
 We define a pointer variable,
 Assign the address of a variable to a pointer and
 Finally access the value at the address available in the pointer variable.

This is done by using unary operator „ * ‟ that returns the value of the variable
located at the address specified by its operand. The following example makes use of
these operations.
While printing the address of any variable we can use „%u‟. & is used to store the
address of variable, we use „ * „ to print the content of the pointer i.e. the original
value stored in the variable.
Let‟s see the small example to demonstrate the declaration and access to the pointers.

 Accept a number from the user and print it with its address using pointer.

#include <stdio.h>
void main ()
{
int num=0; /* actual variable declaration */

int *ptr; /* pointer variable declaration */

clrscr();
printf("\nEnter Number : ");
scanf(“%d”,&num);

ptr=&num; /* store address of var in pointer variable*/

printf("\n%d is stored at %u”, num, ptr);


getch();
}

 When the above code is compiled and executed, it produces the following result :

Enter Number : 3322


3322 is stored at 65226

DiSHA Computer Institute, Kopargaon 135


 Print the address of the given number using pointer.

#include <stdio.h>
void main ()
{
int var = 20;
int *ip;
clrscr();
ip = &var;
printf("\nAddress of var variable : %u”, &var);

/* address stored in pointer variable */


printf("\nAddress stored in ip variable : %u”,&ip);

/* access the value using the pointer */


printf("\nValue of *ip variable : %d",&*ip );

getch();
}

 When the above code is compiled and executed, it produces the following result :

Address of var variable: 65224


Address stored in ip variable: 65224
Value of *ip variable: 20

 Find product of two numbers using pointers.

#include <stdio.h>
void main ()
{
int num1=0, num2=0;

int *ptr1, *ptr2; /* pointer variable declaration */

clrscr();
printf("\nEnter 1st Number : ");
scanf(“%d”,&num1);
printf("\nEnter 2nd Number : ");
scanf(“%d”,&num2);

DiSHA Computer Institute, Kopargaon 136


ptr1=&num1;
ptr2=&num2;

printf("\n%d * %d = %d”, *ptr1, *ptr2, (*ptr1)*(*ptr2));


getch();
}

 When the above code is compiled and executed, it produces the following result :

Enter 1st Number : 25


Enter 2nd Number : 10
25 * 10 = 250

 Pointer and Arrays :


When an array is declared, compiler allocates sufficient amount of memory to contain
all the elements of the array. Base address which gives location of the first element is
also allocated by the compiler.
Suppose we declare an array arr,

int arr[5]={ 1, 2, 3, 4, 5 };

Assuming that the base address of arr is 1000 and each integer requires two byte, the
five element will be stored as follows :

Here variable arr will give the base address, which is a constant pointer pointing to
the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.

arr is equal to &arr[0] // by default

DiSHA Computer Institute, Kopargaon 137


We can declare a pointer of type int to point to the array arr.

int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.

Now we can access every element of array arr using p++ to move from one element to
another.

 Program to accept array element and print them using pointers.

#include<stdio.h>
void main()
{
int arr[5],i=0;
int *ptr;
clrscr();
for(i=0;i<=4;i++)
{
printf(“\nEnter Number : “);
scanf(“%d”,&arr[i]);
}
ptr=&arr[0];
i=1;
while(i<=5)
{
printf(“\n%d is stored at %u”.*ptr, ptr);
ptr++;
i++;
}
getch();
}

 Output :

Enter Number : 2
Enter Number : 7
Enter Number : 9
Enter Number : 11
Enter Number : 19

DiSHA Computer Institute, Kopargaon 138


2 is stored at 65220
7 is stored at 65222
9 is stored at 65224
11 is stored at 65226
19 is stored at 65228

 Pointer and Character strings :


Pointer can also be used to create strings. Pointer variables of char type are treated
as string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The
pointer str now points to the first character of the string "Hello". Another important
thing to note that string created using char pointer can be assigned a value
at runtime.

char *str;
str = "hello";
The content of the string can be printed using printf() and puts().

printf("%s", str);
puts(str);

Notice that str is pointer to the string, it is also name of the string. Therefore we do
not need to use indirection operator *.

 Array of Pointers :
We can also have array of pointers. Pointers are very helpful in handling character
array with rows of varying length.

char *name[3]={
"Nashik",
"Mumbai",
"Pune"
};
//Now see same array without using pointer
char name[3][20]= {
"Nashik",
"Mumbai",
"Pune"
};

DiSHA Computer Institute, Kopargaon 139


Following fig. show pictorial representation of array with pointers.

 Program to demonstrate array with pointers.

#include<stdio.h>
void main()
{
char *str[5] = {“Keyboard”, “Monitor”, “CPU”, “Hard Disk“, “SMPS”};
int i=0;
clrscr();
for(i=o;i<=4;i++)
{
printf(“\n%d Element : %s”,i, str[i]);
}
getch();
}

 Output :

0 Element : Keyboard
1 Element : Monitor
2 Element : CPU
3 Element : Hard Disk
4 Element : SMPS

DiSHA Computer Institute, Kopargaon 140


 Program to compute sum of all element stored in an array.

#include<stdio.h>
void main()
{
int arr[5], sum, i=0;
int *ptr;
clrscr();
for(i=0;i<=4;i++)
{
printf(“\nEnter Array Element : “);
scanf(“%d”,&arr[i]);
ptr=&arr[i];
sum=sum+(*ptr);
}
printf(“\nSum of Array Element : %d”, sum);
getch();
}

 Output :

Enter Array Element : 1


Enter Array Element : 2
Enter Array Element : 3
Enter Array Element : 4
Enter Array Element : 5
Sum of Array Element :15

DiSHA Computer Institute, Kopargaon 141


Structure
 Introduction to structure :
We have already discussed various data types used for various purposes. If we need
to store single value at a time then we use simple data types as per our requirement.
E.g. int, char or float. Also „C‟ provides derived data types called as an array.
Array allows user to store multiple values of same data types. Here we can store
group of items and we can refer this with the single name i.e. name of array. But the
major limitation while storing data in an array is that we have to store the same type
of element in an array.
But sometime we required to store the information of one entity in the one group. But
this information may be consisting of different variables of different data types. At
this stage if we need to refer all variables with the same name, then we require to use
the data types called structure.
Structure allows to club different data types together. E.g. If user wants to store the
data related to the book, then structure can be used to store the information like
book_id, name, publication, price etc.
Structure is small body which allow user to declare different variables of different
data types and use them with the same name of structure.
Following some samples which uses structure to store the data.
 For Example :
Employee Details - Emp_ID, Emp_Name, Salary etc.
Date Details - Day, Month, and Year.
Time Details - Hours, Minutes and Secounds.
Students Details – Roll_No, Name, Percentage etc.

 Defining a Structure :
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member. The format of the struct
statement is as follows :

struct [structure tag] {

member definition;
member definition;
...
member definition;
} [one or more structure variables];

DiSHA Computer Institute, Kopargaon 142


The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end of
the structure's definition, before the final semicolon, you can specify one or more
structure variables but it is optional. Here is the way you would declare the Book
structure

struct Books // Declaration of structure


{
char title[50]; // Structure members
char author[50];
int book_id;
}book; // Structure variable declaration

 Accessing Structure Members :


To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name
and the structure member that we wish to access. You would use the
keyword struct to define variables of structure type.
The following example shows how to use a structure in a program.

struct Day // Declaration of structure


{
int day; // Structure members
char month[50];
int year;
}dt; // Structure variable declaration

To access the variable day we have to write dt.day similarly to access month we have
to write dt.month and for year dt.year
In this way we can say that the structure members can be accessed by the following
form :
structure-variable.structure-member-name;

DiSHA Computer Institute, Kopargaon 143


 Initializing Structure Members :

// Program to demonstrate structure initialization.

#include <stdio.h>
void main()
{
struct Employee
{
int id;
char name[50];
float salary;
};
struct Employee emp = {3322, ”Sanjay”, 78000};
clrscr();
printf( "Emp_ID : %d\n", emp.id);
printf( "Emp_Name : %s\n", emp.name);
printf( "Emp_Salary : %f\n\n", emp.salary);
getch();
}

 Output :

Emp_ID : 3322
Emp_name : Sanjay
Emp_Salary : 78000.000

// Program to accept Roll_No, Name and Percentage from user using structure.

#include <stdio.h>
struct Student //declaring structure
{
int roll_no;
char name[50];
float percent;
}stud; // Structure member declaration

void main( )
{
clrscr();
printf( "\nEnter Student Roll_No : “);

DiSHA Computer Institute, Kopargaon 144


scanf(“%d”, &stud.roll_no);
printf( "\nEnter Student Name : “);
scanf(“%s", &stud.name);
printf( "\nEnter Student Percentage : “);
scanf(“%f", &stud.percent);

printf( "Student Roll_No : %d\n", stud.roll_no);


printf( "Student Name : %s\n", stud.name);
printf( "Student Percentage : %f\n\n", stud.percent);
getch();
}

 Output :

Enter Student Roll_No : 123


Enter Student Name : Disha
Enter Student Percentage : 88

Student Roll_No : 123


Student Name : Disha
Student Percentage : 88.000

// Program to accept Title, Author and Book_ID of Book from user using
structure.

#include <stdio.h>

struct Books //declaring structure


{
char title[50];
char author[50];
int book_id;
}Book; // Structure member declaration

void main( )
{
clrscr();
printf( "Enter Book Title : %s\n", Book.title);
printf( "Enter Book Author : %s\n", Book.author);
printf( "Enter Book Book_ID : %d\n\n", Book.book_id);

DiSHA Computer Institute, Kopargaon 145


printf( "Book Title : %s\n", Book.title);
printf( "Book Author : %s\n", Book.author);
printf( "Book Book_id : %d\n", Book.book_id);
getch();
}

 Output :

Enter Book Title : C Programming


Enter Book Author : Nuha Ali
Enter Book Book_id : 6495407

Book Title : C Programming


Book Author : Nuha Ali
Book Book_id : 6495407

 Array of Structure :
Structure is used to store the information of One particular object but if we need to
store such 100 objects then Array of Structure is used.

 Example :

struct Bookinfo
{
char[20] bname;
int pages;
int price;
}Book[100];

 Explanation :

Here Book structure is used to Store the information of one Book.


In case if we need to store the Information of 100 books then Array of Structure is
used.
b1[0] stores the Information of 1st Book , b1[1] stores the information of
2nd Book and So on We can store the information of 100 books.

DiSHA Computer Institute, Kopargaon 146


book[3] is shown Below

// program for accepting 3 book details from user and print by using structure.

#include <stdio.h>
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}book[3];

void main()
{
int i;
for(i=0;i<2;i++)
{
printf("\n\nEnter the Name of Book : ");
scanf("%s",&book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",book[i].price);
}
printf("\n--------- Book Details ------------ ");
for(i=0;i<2;i++)
{
printf("\nName of Book : %s",book[i].bname);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f\n",book[i].price);
}
getch();
}

DiSHA Computer Institute, Kopargaon 147


 Output :

Enter the Name of Book : ABC


Enter the Number of Pages : 100
Enter the Price of Book : 200

Enter the Name of Book : EFG


Enter the Number of Pages : 200
Enter the Price of Book : 300

Enter the Name of Book : HIJ


Enter the Number of Pages : 300
Enter the Price of Book : 500

--------- Book Details ------------

Name of Book : ABC


Number of Pages : 100
Price of Book : 200

Name of Book : EFG


Number of Pages : 200
Price of Book : 300

Name of Book : HIJ


Number of Pages : 300
Price of Book : 500

 Accessing Element in Structure Array :


Array of Structure can be accessed using dot[.] operator.
Here Records of 3 Employee are Stored.
„for loop‟ is used to Enter the Record of first Employee.
Similarly „for Loop‟ is used to Display Record.

#include<stdio.h>
struct Employee
{
int id;
char ename[20];
char dept[20];

DiSHA Computer Institute, Kopargaon 148


}emp[3];

void main()
{
int i,sum;
for(i=0;i<3;i++)
{
printf("nEnter the Employee Details : ");
scanf("%d %s %s",&emp[i].id,emp[i].ename,emp[i].dept);
}
for(i=0;i<3;i++)
{
printf("nEmployee ID : %d",emp[i].id);
printf("nEmployee Name : %d",emp[i].ename);
printf("nEmployee Dept : %d",emp[i].dept);
}
getch();
}

 Output :

Enter the Employee Details : 1 Ram Testing


Employee ID : 1
Employee Name : Ram
Employee Dept : Testing

 Pointers to Structures :

You can define pointers to structures in the same way as you define pointer to any
other variable –

struct Books *struct_pointer;

Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the '&'; operator before the
structure's name as follows –

struct_pointer = &Book1;

To access the members of a structure using a pointer to that structure, you must use
the → operator as follows −

DiSHA Computer Institute, Kopargaon 149


struct_pointer->title;

Let us write the above example using structure pointer.

#include <stdio.h>
#include <string.h>

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
void main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info by passing address of Book1 */


printBook( &Book1 );

/* print Book2 info by passing address of Book2 */


printBook( &Book2 );
getch();
}

void printBook( struct Books *book )


{

DiSHA Computer Institute, Kopargaon 150


printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}

When the above code is compiled and executed, it produces the following result :

Book title : C Programming


Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407

Book title : Telecom Billing


Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

DiSHA Computer Institute, Kopargaon 151


Unions
 Introduction To Union :
Unions are quite similar to structures in C. Like structures, unions are also derived
types. A union is a special data type available in C that allows to store different data
types in the same memory location. Unions provide an efficient way of using the
same memory location for multiple-purpose.

Defining a union is as easy as replacing the keyword struct with the keyword union.

union [union tag]


{
member definition;
member definition;

member definition;
} [one or more union variables];

 Difference between Structure And Union :

Structure Union
The struct keyword is used to declare an The union keyword is used to declare
structure. an union.
All data members in a structure is active Only one data is active at a time.
at a time.
We can access all the members of Only one member of union can be
structure at a time. accessed at a time.
Memory is allocated for all variables. Allocate memory for the variable which
requires more memory.
All members of structure can be Only first member of union can be
initialized. initialized.
Syntax : Syntax :
struct structure _name Union union _name
{ {
struct element 1; union element 1;
struct element 2; union element 2;
… …
struct element n; union element n;
}struct_var_name; }union_var_name;

DiSHA Computer Institute, Kopargaon 152


Example : struct stud Example : union car
{ {
int roll_no; char car_name[10];
char name[10]; int price;
}s; }c;

 For Example :
union car
{
char name[10];
int price;
}car1,car2;

// Program to accept car_name and price froom user using union.

#include<stdio.h>
void main()
{
union car
{
char name[10];
long int price;
} car1,car2;
clrscr();
printf(“\nEnter Car Name : “);
scanf(“%s”,&car1.name);
printf(“\nEnter Car Price : “);
scanf(“%ld”,&car2.price);
printf(“\n Car Is : %s \n Price Is : %ld”,car1.name, car2.price);
getch();
}

 Output :

Enter Car Name : Swift


Enter Car Price : 780000
Car Is : Swift
Price Is : 780000

DiSHA Computer Institute, Kopargaon 153


// Program to accept car_name and price froom user using union.

// Program for
#include <stdio.h>
#include<string.h>
union stud
{
int rollno;
char name[20];
float percent;
};
void main( )
{
union stud r, n, p;
clrscr();
printf("\n Enter Roll No : ");
scanf("%d",&r.rollno);
printf("\n Enter Student Name : ");
scanf("%s",&n.name);
printf("\n Enter Percentage : ");
scanf("%f",&p.percent);
printf("\n\t Student Information \n");
printf("\n\t Roll No : %d",r.rollno);
printf("\n\t Name : %s",n.name);
printf("\n\t Percentage : %f",p.percent);
getch();
}

 Output :

Enter Roll No : 123


Enter Student Name : Mayur
Enter Percentage : 66

Student Information
Roll No : 123
Name : Mayur
Percentage : 66

DiSHA Computer Institute, Kopargaon 154


File Handling
 What Is File :
A file is collection of bytes stored on secondary device.
The collection of bytes may be interpreted,
As characters, words, lines, paragraphs and pages from textual document.
Fields and records belonging to database.
Pixel from graphics image.
There are two kind of files that programmers deals with text file and binary file.

 Text File :
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors. When you open those files, you'll see all the contents within the
file as plain text. You can easily edit or delete the contents. They take minimum
effort to maintain, are easily readable, and provide least security.

 Binary File :
A binary file is a computer file that is not a text file. The term "binary file" is often
used as a term meaning "non-text file". Binary files are mostly the .bin files in your
computer. Instead of storing data in plain text, they store it in the binary form (0's
and 1's). They can hold higher amount of data, are not readable easily and provides a
better security than text files.

 Eile Handling :
A file is sequence of bytes of a disk where a group of data is stored. File is created for
permanent storage of data. It is a readymade storage of data. It is ready made
structure in C.
When working with files, you need to declare a pointer of type file type to declare a
file. This declaration is needed for communication between the file and program.

FILE *fp;

C provides a number of functions that helps to perform basic file operations they are :
 File Operation‟s :
Following are different operation that perform on file :
 Creating a file
 Writing to a file
 Reading from file
 Appending to a file
 Closing a file

DiSHA Computer Institute, Kopargaon 155


 File Operation Function :

Function name Operation


fopen( ) Create a new file for use OR open a existing file for use.
fclose( ) Close a file which open for use.
putc( ) Write a character to file.
getc( ) Read a character from file.
fputs( ) Write a string into file.
fgets( ) Read a file line by line.
fputc( ) Write a character into file.
fgetc( ) Read character from file
putw( ) Write an integer to file.
getw( ) Read an integer to file.
fflush( ) Used to flush/clean the file or buffer.
fprintf( ) Write a set of data to file.
fscanf( ) Read a set of data values from file.
fseek ( ) Set the position to desired point in the file.
ftell( ) Gives current position to a file.
rewind( ) Set the position to the beginning of the file.

 Creating a file :

Opening a file is performed using the library function in the "stdio.h" header file:
fopen().
fopen() is the function used to create a file and if the file is already created then this
function will used to open a particular file and w is used to create a file.

The syntax for opening a file in standard I/O is:

fp = fopen(“location\file_name”,”mode”);

 For Example :

fp = fopen(“E:\\Cprogram\\newprogram.txt”,”w”); // Text File…


fp = fopen(“E:\\Cprogram\\oldprogram.bin”,”rb”); // Binary File…

DiSHA Computer Institute, Kopargaon 156


// Program to create Empty File.

#include<stdio.h>
void main()
{
FILE *fp;
clrscr();
fp = fopen("file1.txt","w");
fclose(fp);
getch();
}

This program will create Empty file. In the default location:


C:\TurboC++\Disk\TurboC3\BIN\file1.txt

 fopen( ) :

Declaration : fp = fopen(“location\file_name”,”mode”);

fopen() function is used to open a file to perform operations such as reading, writing
etc. In a C program, we declare a file pointer and use fopen() as below. fopen()
function creates a new file if the mentioned file name does not exist.

FILE *fp;
fp=fopen (“filename”, ”„mode”);

Where, fp file pointer to the data type “FILE”. filename the actual file name with full
path of the file. mode refers to the operation that will be performed on the file.
Example: r, w, a, r+, w+ and a+. Please refer below the description for these mode of
operations. The legal values of modes are shown in the following table.

File type Meaning


r Open an existing file for reading only.
w Open a new file for writing only. If a file with specified file_name
is currently exist, it will be destroyed and a new file created in its
place.
a Open an existing file for appending i.e. for addind a new
information at the end of the file.
r+ Open an existing file for both reading and writing.

DiSHA Computer Institute, Kopargaon 157


w+ Open an existing file for both reading and writing.
If a file with specified file_name is currently exist, it will be
destroyed and a new file created in its place.
a+ Open an existing file for both reading and appending.
If a file with specified file_name is currently exist, it will be
destroyed and a new file created in its place.

If you are going to handle binary files, then you will use the following access modes
instead of the above-mentioned ones:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

 fclose( ) :

To close a file, use the fclose( ) function. The prototype of this function is :

int fclose(FILE * stream);

fclose() function closes the file that is being pointed by file pointer fp. In a C program,
we close a file as below.

fclose(fp);

 putc( ) :

Declaration : int putc(int char, FILE *fp);

putc( ) function is used to display a character on standard output or is used to write


into a file. In a C program, we can use putc( ) as below.

putc(char, fp);

DiSHA Computer Institute, Kopargaon 158


 getc( ) :

Declaration : int getc(FILE *fp);

getc( ) functions is used to read a character from a file. In a C program, we read a


character as below.

getc(fp);

/* Program for putc( ) and getc( ) function. */

#include <stdio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("abc1.txt","w”);
printf("\nEnter Any Character :");
scanf(“%c”,&ch);
putc(ch, fp);
fclose(fp);
fp=fopen(“abc1.txt”,”r”);
ch=getc(fp);
printf(“\nData From File : “);
printf(“\nCharater Is : %c”,ch);
fclose(fp);
getch();
}

Output :
Enter Any Character : M
Data From File :
Character Is : M

DiSHA Computer Institute, Kopargaon 159


 fputs( ) :

Declaration : int fputs(const char *string, FILE *fp);

fputs( ) function writes string into a file pointed by fp. In a C program, we write
string into a file as below.

fputs(fp, “Some Data”);

 fgets( ) :

Declaration : char *fgets(char *string, FILE *fp);

fgets( ) function is used to read a file line by line. In a C program, we use fgets( )
function as below.

fgets(buffer, size, fp);

buffer – buffer to put the data in.


size – size of the buffer
fp – file pointer

/* Program for fputs( ) and fgets( ) function. */

#include<stdio.h>
void main()
{
FILE *fp;
char text[100];
clrscr();
printf("\nEnter a Text : ");
gets(text);
fp = fopen("abc1.txt","w");
fputs(text,fp);
fclose(fp);

DiSHA Computer Institute, Kopargaon 160


if((fp=fopen("abc1.txt","r"))==NULL)
{
printf("\nFile Opening Error...!");
exit(0);
}
fgets(text, 100, fp);
printf("\n You Entered : %s",text);
getch();
}

Output :
Enter a Text : Disha Computers Kopergoan
You Entered : Disha Computers Kopergoan

 fputc( ) :

Declaration : int fputc(int char, FILE *fp);

fputc( ) function used to write a character into a file. In a C program, we use fputc( )
function below.

fputc(ch, fp);

where,
ch – character value
fp – file pointer

 fgetc( ) :

Declaration : int *fgetc(FILE *fp);

fgetc( ) functions is used to read a character from a file. It reads single character at a
time. In a C program, we use fgetc() function as below.

fgetc(fp);

DiSHA Computer Institute, Kopargaon 161


Where,
fp – file pointer

/* Program for fputc( ) and fgetc( ) function. */

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("abc1.txt","w");
printf("\nFile is Open...\n");
printf("\nEnter a Character : ");
scanf("%c",&ch);
fputc(ch, fp);
fclose(fp);
fp = fopen("abc1.txt","r");
if(fp == NULL)
{
printf("\nFile Opening Error..!");
}
while(1)
{
ch=fgetc(fp);
if (ch==EOF)
{
break;
}
printf("\nData From File Is : %c",ch);
}
fclose(fp);
getch();
}

Output :
Enter a Character : M

Data From File Is : M

DiSHA Computer Institute, Kopargaon 162


 putw( ) :

Declaration : int putw(int number, FILE *fp);

putw( ) function is used to write an integer into a file. In a C program, we can write
integer value in a file as below.

putw(i, fp);

where
i – integer value
fp – file pointer

 getw( ) :

Declaration : int getw(FILE *fp);

getw( ) function reads an integer value from a file pointed by fp. In a C program, we
can read integer value from a file as below.

getw(fp);

/* Program for putw( ) and getw( ) function. */

#include<stdio.h>
void main()
{
FILE *fp;
int num;
clrscr();
fp = fopen("abc.txt","w");
printf("\nFile is Open...\n");
printf("\nEnter Any Number : ");
scanf("%d",&num);
putw(num, fp);

DiSHA Computer Institute, Kopargaon 163


fclose(fp);
fp = fopen("abc.txt","r");
num=getw(fp);
printf("\nData From File Is : %d",num);
fclose(fp);
getch();
}

Output :
File is Open…
Enter Any Number : 3322
Data From File Is : 3322

 fflush( ) :

Declaration : int fflush(FILE *fp);

fflush() function is a file handling function in C programming language which is used


to flush/clean the file or buffer.

fflush(buffer);

 fprintf( ) :

Declaration : int fprintf(FILE *fp, const char *format, …);

fprintf() function is used to write formatted data into a file. In a C program, we use
fprinf() as below.

fprintf(fp, “%s %d %f”, var1, var2, var3);

Where, fp is file pointer to the data type “FILE”.


var1 - String Variable
var2 - Integer Variable.
var3 – Float Variable.

DiSHA Computer Institute, Kopargaon 164


/* Program for fprintf( ) and fflush( ) function. */

#include<stdio.h>
void main()
{
FILE *fp;
int roll_no;
char name[20];
float marks;
clrscr();
printf("\n Enter Roll No : ");
scanf("%d",&roll_no);
printf("\n Enter Name : ");
fflush(stdin);
gets(name);
printf("\n Enter Marks : ");
scanf("%f",&marks);
fp=fopen("abc2.txt","w");
fprintf(fp,"%d %s %f",roll_no, name, marks);
fclose(fp);
getch();
}

Output :
Enter Roll No : 41
Enter Name : Mayur
Enter Marks : 99.000000

 fscanf( ) :

Declaration : int fscanf(FILE *fp, const char *format, …);

fscanf() function is used to read formatted data from a file. In a C program, we use
fscanf() as below.

fscanf (fp, “%d”, &age);

DiSHA Computer Institute, Kopargaon 165


Where,
fp is file pointer to the data type “FILE”.
Age – Integer variable.

/* Program for fscanf( ) function. */

#include<stdio.h>
void main()
{
FILE *fp;
int roll_no;
char name[20];
float marks;
clrscr();
if((fp=fopen("abc2.txt","r"))==NULL)
{
printf("\nOpening File Error...!");
exit(0);
}
fscanf(fp,"%d %s %f",&roll_no, &name, &marks);
printf("\nData From File Is : ");
printf("\nRoll No : %d",roll_no);
printf("\nName : %s",name);
printf("\nMarks Is : %f",marks);
fclose(fp);
getch();
}

Output :
Data From File Is :
Roll No : 41
Name : Mayur
Marks : 99.000000

 ftell( ) :

Declaration : long int ftell(FILE *fp)

DiSHA Computer Institute, Kopargaon 166


ftell( ) function is used to get current position of the file pointer. In a C program, we
use ftell( ) as below.

ftell(fp);

 rewind( ) :

Declaration : void rewind(FILE *fp)

rewind( ) function is used to move file pointer position to the beginning of the file.
In a C program, we use rewind() as below.

rewind(fp);

 fseek( ) :

Declaration : int fseek(FILE *fp, long int offset, int whence);

fseek() function is used to move file pointer position to the given location.

where,
fp – file pointer
offset – Number of bytes/characters to be offset/moved from whence/the current file
pointer position
whence – This is the current file pointer position from where offset is added. Below 3
constants are used to specify this.

SEEK_SET : SEEK_SET – It moves file pointer position to the beginning of the file.
SEEK_CUR : SEEK_CUR – It moves file pointer position to given location.
SEEK_END : SEEK_END – It moves file pointer position to the end of file.

DiSHA Computer Institute, Kopargaon 167


/* Program for fopen( ), fclose( ),fscanf( ), fprintf( ), ftell( ), rewind( ) and fseek( )
functions. */

#include <stdio.h>
void main ()
{
char name [20];
int age;
FILE *fp;
clrscr();
fp=fopen ("test.txt","w");
fprintf (fp,"%s %d","Disha Computers",3322);
ftell(fp); // Cursor position is now at the end of file.
rewind(fp); // It will move cursor position to the beginning of the file.
fscanf(fp,"%s",&name);
fscanf(fp,"%d",&age);
fclose(fp);
getch();
}
/* You can use "fseek(fp, 0, SEEK_SET);"
“fseek(fp, 0, SEEK_CUR);”
“fseek(fp, 0, SEEK_END);”
also to move the cursor to the end of the file */

Output :
In test file the data will be print…
Disha Computers 3322

 Writing to a text file :

// Program to write Numeric data in the file.

#include<stdio.h>
void main()
{
int data;
FILE *fp;
clrscr();

DiSHA Computer Institute, Kopargaon 168


fp = fopen("test.txt","w");
if(fp==NULL)
{
printf("\n Error..!\n");
exit(1);
}
printf("\n Enter No : ");
scanf("%d",&data);
fprintf(fp,"%d",data);
fclose(fp);
getch();
}

Output : This program will fill the numeric data to the file…

 Reading from a text file :

// Program to read Text From File

#include<stdio.h>
void main()
{
char data[100];
FILE *fp;
clrscr();
if((fp = fopen("test.txt","r"))==NULL)
{
printf("\n Error...Opening File..!\n");
exit(1);
}
fscanf(fp,"%s",&data);
printf("\n Data From The File Is : %s",data);
fclose(fp);
getch();
}

Output : This program will show the text data present in the text file…

DiSHA Computer Institute, Kopargaon 169


 Writing and Reading Numeric data to a text file :

// Program to write Numeric data in the file and display the data in output
window.

#include<stdio.h>
void main()
{
int data;
FILE *fp;
clrscr();
fp = fopen("test.txt","w");
if(fp==NULL)
{
printf("\n Error..!\n");
exit(1);
}
printf("\n Enter No : ");
scanf("%d",&data);
fprintf(fp,"%d",data);
fclose(fp);
fp = fopen("test.txt","w");
printf(“\n Data from the file is : %d”,data);
fclose(fp);
getch();
}

Output :

This program will fill the numeric data to the file and display the data in
output screen…

DiSHA Computer Institute, Kopargaon 170


 Writing and Reading String to a text file :

// Program to write Numeric data in the file and display the data in output
window.

#include<stdio.h>
void main()
{
char data;
FILE *fp;
clrscr();
fp = fopen("test.txt","w");
if(fp==NULL)
{
printf("\n Error..!\n");
exit(1);
}
printf("\n Enter No : ");
scanf("%s",&data);
fprintf(fp,"%s",data);
fclose(fp);
fp = fopen("test.txt","w");
printf(“\n Data from the file is : %s”,data);
fclose(fp);
getch();
}

Output :

This program will fill the string to the file and display the string in output
screen…

DiSHA Computer Institute, Kopargaon 171


 Appending to File :

// Program for appending.

#include<stdio.h>
void main()
{
FILE *fp;
int rollno, i=0, n;
char name[20];
clrscr();
printf("\nEnter No. Of Student : ");
scanf("%d",&n);
fp = fopen("student.txt","a");
if(fp==NULL)
{
printf("\n Error..!\n");
exit(1);
}
for(i=0;i<n;i++)
{
printf("\n Enter Roll No : ");
scanf("%d",&rollno);
printf("\n Enter Name : ");
scanf("%s",&name);
fprintf(fp,"\n Roll No : %d \n Name : %s",rollno,name);
}
fclose(fp);
getch();
}

Output :

Enter No. Of Student : 3


Enter Roll No : 11
Enter Name : Mayur
Enter Roll No : 22
Enter Name : Disha
Enter Roll No : 33 If we again run this program then old data are
Enter Name : Rohit present and new data added in the file.

DiSHA Computer Institute, Kopargaon 172

You might also like