C Programming Notes For Students Third Edition

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

lOMoARcPSD|29400031

C Programming Notes FOR Students Third Edition

Programming (University of Northampton)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Diya Rajput (diyamin930@gmail.com)
lOMoARcPSD|29400031

INTRODUCTION C PROGRAMMING

C is a powerful general purpose and most popular computer programming language. It


was developed in the 1972’s by Dennis M. Ritche at Bell Telephone laboratories (AT& T
Bell Labs). C was extensively used in its development C is an outgrowth of BCPL (Basic
combined Programming Language) developed by Martin Richards University.

C is often called a middle-level computer language, because it has the features of both
high-level languages, such as BASIC, PASCAL etc., and low-level languages such as
assembly language.

C is highly portable i.e., Software written for one computer can be run on another
computer. C language is well suited for structured programming. An important feature of
‘C’ is its ability to extend itself. A C program is basically a collection of functions. It
encourages us to write out own functions and add to the C library. Also C is modular, i.e.,
a unit of task can be performed by a single function and this unit of task can be reutilized
when needed. The large number of functions makes programming task simple.

STRUTURE OF A ‘C’ PROGRAM:

C programs consist of one or more functions. Each function performs a specific task. A
function is a group of sequences of statements that are together. And it is similar to
subprograms (or subroutines) in other high-level languages like Pascal.

Every C program starts with a function called main(). This is the place where program
execution begins. Hence, there should be main() function in every program. The
functions are building blocks of C program. Each function has a name and a list of
parameters ( or arguments).

1
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Documentation section
Linkage section
Definition section optional
Global declaration section

main ()
{
Declaration part
Execution part / statement part
}
Sub program section
Or optional
User defined section

Documentation section:
This section group of comments that explains about program name, purpose of the
program, program logic, programmer name, date of written program etc. Comments can
be included anywhere into the program. Comments are enclosed between /* and */.
Linkage Section:
It is the pre -processing directive operation section under this we can include the header
files with the # include <header file name. h>
Or
# include “header file name. h”
Whenever we are using standard functions into the main program those are referred into
the header files. When we included header file. Otherwise it gives error message header
file inclusion error
# include < stdio. h> or # include < graphic. h>
Definition section:
It is also the pre-processing directive operation. Under this we can define the symbolic
constant with the # define identifier data.
Example: #define

2
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

These symbolic constant calls as macros. These macros are global.


Global declaration section:
Under this section we can declared the global variables. These variables can be used in
main program or other user defined function without declaration.
main():
main is a standard function to every program. Without main function program could not
process. It is compulsory for every program.
{ (left brace):
It indicates the beginning of the main. It is also compulsory.
Declaration part:
Whatever the variables, constants, array etc. we are going to be used into the statement
part those thing should be declared along with their storage class and type and identifier
name.
The syntax follows:

Storage Class data type variables


(identifiers)
Separate by a comma.
Example: auto int a,b,c;
Extern int x,y,z;
} (right brace):
It indicates the ending of the program it is also compulsory.
Subprograms:
Here we can write the user define sub-programs when ever we are facing repetitive task
then we can write user defined function. We can write any number of sub programs there
is no limit.

The following is a simple C program that prints a message on the screen.


# include <stdio.h>
/* A simple program for printing a message */
main()

3
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

{
printf( “ hello , this is a C program.”);
}

The first line

# include <stdio.h>
Tells the compiler to read the file stdio.h and include its contents in this file. stdio.h, one
of header files, contain the information about input output functions. The next line is a
comment line Comments in the C program are optional and may appear anywhere in a C
program. Comments are enclosed between /* and */.
main() is the start of the main program. The word main is followed by a pair of ordinary
parenthesis (), which indicates that main is also a function. The left brace { represents the
beginning of the function where as the right brace } represents the end of the function. It
means, the braces enclose the body of function. In this program, the body consists of only
one statement, the one beginning with printf. The printf() function is causes its
arguments to printed on the computer screen. The closing (right) brace of the main
function is the logical end of the program.
The following are some of rules to write C programs.

i. All C statements must end with semicolon.


ii. C is case-sensitive. That is upper case and lower case characters are different.
Generally the statements are typed in lower case.
iii. A C statement can be written in one line or it can split into multiple lines.
iv. Braces must always match upon pairs, i.e., every opening brace { must have a
matching closing brace }.
v. No restriction in using blank spaces or blank lines that separates different words
or different parts of program. Blank spaces improve the readability of the
statements. But blank spaces are not allowed within a variable, constant or
keyword.
vi. Comments cannot be nested. For example,
/* A simple ‘C’ program, /* it prints a message */ */
is not valid.

4
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

vii. A comment can be split into more than one line.


Execution of C program:
Steps to be followed in writing and running a C program
i. Creation of Source Program
ii. Compilation of the Program (Alt + F9).
iii. Program Execution (ctrl + F9).
iv. Output or Console Screen ( Alt +f5).
FUNDAMENTALS OF C PROGRAM
C Tokens
A C program must be syntactically valid sequences of characters of the language. In
every C program, the most basic element recognized by the compiler is single character
or group of characters called C tokens.
Steps in learning C language are…
i. Character Set – Alphabets, Digits and Special Symbols
ii. Datatypes, Constants, Variables and Keywords
iii. Instructions
iv. Functions, Program
The C character set
The C character set includes the upper case letters A to Z, the lower case a to z, the
decimal digits 0 to 9 and certain special characters/symbols. The character set is given
bellow.
Alphabets A, B, C, …….Z
a, b, c,. ……. Z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special characters/Symbols~, . : ; ? ‘ “ ! ( ) [ ] { } / \ < > = + - $ # & * % ^
Keywords:
Key words are predefined tokens in C. these are also called as reserved words. Key words
have special meaning to the C compiler. These key words can be only for their intended
action. They cannot be used for any other purposes. The standard key words are:
auto break case char const continue
default do double else enum extern

5
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

float for goto if int long


register return short signed sizeof static
struct switch typedef union unsigned void
volatile while
Data types and Sizes
A data type a set of values and the operations that can be performed on them. Every data
type item (constant, variable etc.) in a C program has a data type associated with it.
The memory requirements for each data type will determine the permissible range of
values for that type. These requirements may vary from one compiler to another.
Generally the following rule is true for any complier to specify the size of data types:
char ≤ sizeof(short int)≤ sizeof(int) ≤ sizeof(long int) ≤ sizeof(float) ≤ sizeof(double)
Data type Format Specifier

int %d
unsigned int %u
long int %ld
unsigned long int %lu
char %c
float %f
double %lf
long double %Lf

6
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Datatype Description Size Range


in Bytes
Signed char/char Character 1 -128 to +127

Unsigned char Unsigned character 1 0 to 255

Short signed int Short signed integer 2 -32768 to +32767

Short unsigned int Short unsigned integer 2 0 to 65535

Long signed int Long signed integer 4 -2,147,483,648 to


2,147,483,648
Long unsigned int Long signed integer 4 0 to 4,294,967,295

Float Floating point 4 -3.4 e38 to +3.4 e38

Double Double floating point 8 -1.7 e 308 to +1.7 e 308

Long double Long double floating 10 -1.7 e 4932 to + 1.7 e 4932


point

Signed:
It indicates all the bits are positive. Means that it takes only positive values as well as
negative values.
Unsigned:
It indicates all the bits are positive only (all values are positive).

C Datatypes

Basic data types Derived data types

Char integer float double void array structure union pointer

7
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Constants and variables


A constant is a literal, which remain unchanged during the execution of a program. A
variable is a name that is used to store data value and is allowed to vary the value during
the program execution.
Constants
A constant is a fixed value that cannot be altered during the execution of a program.
C Constants can be classified into two categories.
i. Primary constants.
ii. Secondary constants.
Constants

Primary constants Secondary constants

Numeric character logical Array structure union pointer…etc

Integer float
Single char string
Integer constants
An integer constant is an integer-valued number consisting of a sequence of digits. The
following are the rules for constructing integer constants.
1) An integer constant must have at least one digit.
2) It should not contain either a decimal point or exponent.
3) If a constant is positive, it may not be preceded by a plus sign. If it is a negative, it
must be preceded by a minus sign.
4) Commas, blanks and non digit-characters are not allowed in integer constants.
5) The valid range is –32768 to +32767.
These range my larger for 32 bit computers.

8
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Real constants
Real constants are often called floating-point constants. These are two ways to represent a
real constant decimal form and exponential form.
Real constants expressed in decimal form must have at least one digit and one decimal
point. As in the case of integers, the real constants can be either positive or negative.
Commas, blanks, and non-digit characters are not allowed with in a real constant.
In exponential form, a real constant is expressed as an integer number or a decimal
number multiplied by an integral power of 10. This simplifies the writing of very large
and very small numbers. In this representation, letter e is written instead of 10, the power
is written just to the right of e. generally, the part appearing before e is called mantissa,
whereas the part following e is called exponent.
Rules for constructing real constants are:
i. The mantissa part and the exponential part should be separated by a letter e.
ii. The mantissa part may have a positive or negative sign. Default sign of mantissa
part is positive.
iii. Commas, blanks and non-digit characters are not allowed with in a real constant.
iv. The exponent part must be an integer.
v. The mantissa part must have at least one digit.
vi. Range of real constants expressed in exponential form is –3.4e38 to +3.4e38
String constants
A string constant is a sequence of characters enclosed in double quote. The
characters may be letters, numbers, blank space or special characters.
Example: “welcome”
“this is a sting”
“a+b=8”
““
“a”
Note that ““ is a null string or empty string. And the single string constant “a” is not
equivalent to the single character constant ‘a’.
Each sting constant must end with a special character ‘\0’. This character is called null
character and used to terminate the string. The compiler automatically places a null ‘\0’

9
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

character at the end of every string constant. This constant is not visible when the string
is displayed. The null character is very much useful in finding the end of a string.
Variables
A variable can be considered as a name given to the location in memory. The term
variable is used to denote any value that is referred to a name instead of explicit value. A
variable is able to hold different values during execution of a program.
For example, in the equation 2x+3y=10; since x and y can change, they are variables,
whereas 2,3 and 10 cannot change, hence they are constants.
Rules for constructing variable names:
i. The name of a variable is composed of one to several characters; the first of
which must be a letter.
ii. No special characters other than letters, digits, and underscore can be used in
variable name. some compilers permit underscore as the first character.
iii. Commas, or blanks are not allowed with in a variable name.
iv. Upper case and lower case letters are significant (different).
v. The variable name should not be a C key word. Also it should not have the same
name as a function.
Examples: income, name, rate, marks, sno, etc.
Operators in C
There are 9 types of operators in C. They are
i. Arithmetic operators
ii. Relational operators
iii. Logical operators
iv. Assignment operators
v. Compound assignment operators
vi. Increment and Decrement operators
vii. Bit wise operators
viii. Conditional operators (ternary operator)
ix. Special operators
1). Arithmetic Operators
These are used for the mathematical operations.

10
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Operator Meaning
+ addition
- subtraction
* multiplication
/ division
% modulus
 The division operator ( / ) gives the quotient of the division.
 The modulus operator ( % ) gives the remainder of the division.
Note:- All operators must works only with two operands. so these are also called as the
"Binary operators". Example:
main()
{
int a =10,b=20,c; /* variable declaration part */
c=a+b;
printf(“%d”, c); /* it displays addition of c value */
c= a-b;
printf(“%d”, c);
c= a*b;
printf(“%d”, c);
c= a/b;
printf(“%d”, c);
c= a%b;
printf(“%d”, c);
getch();
}
Note:
- Compilation of the Program (Alt + F9).
- Program Execution (ctrl + F9).
- Output or Console Screen ( Alt +f5).
Output:
30

11
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

-10
200
0
10
2). Relational operators
These are the operators, which tell the relation between the values or operands. In C
language all relational and logical operators returns 1 or zero. If the expression is true
then it will gives 1 other wise 0.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equals to
!= Not equals
Examples on relational operators:-
- a=3<4; 1
- a=3>2; 1
- a=2>=3; 0
- a= 5<=5; 1
- a= 5==5; 1
- a= 5!=8; 1
3). Logical operator:-
The logical operators are used to compare more than one condition
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Truth table for AND (&&) operator:

12
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Expression1 Expression2 Result


T T T
T F F
F T F
F F F

Truth table for OR (||) operator:


Expression1 Expression2 Result
T T T
T F T
F T T
F F F

Truth table for NOT (!) operator:


Expression1 Result
T F
F T

examples:-
1. a = 1&&1; 1
2. a = 7&&5; 1
3. a = 5>4 && 4>10; 0
4. a = 5>4 || 4>10; 1
5. a = 1 || 0 1
6. a = !1 0
7. a = 1 && 4>3 1
8. a = ! (5>5); 1
4). Assignment operator (=)
The assignment operator can be used to store the data into the identifier (variable). The
nature of storage is that right side of the data stored into left side of identifier. Ex: a=10;
5). Assignment operators (+=, - =, * =, / =, % =):

13
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

The compound assignment operator can be used to minimize the arithmetic operations.
Example:
a+= 1; it is equal to a= a+1;
b+=a; it is equal to b= b + a;
c-=a; it is equal to c= c-a;
d*= a ; it is equal to d= d*a;
a/=b; it is equal to a=a/b;
b%=a; it is equal to b=b%a;
6). Increment and Decrement operators
Increment (++)
Always it increment only one value to the existing identifier. They are two types.
++a pre-increment.
a++ post-increment

pre- increment:
When ever the pre-increment operators using into the arithmetic expressions then it is
increasing the one value to the adjusting identifier and participating into the expressions.
This can be written ++identifier.
Ex: ++a;
Post- increment:
When ever the post incrimination operators including into the arithmetic operators then
the identifier values directly participating into the arithmetic expressions. After that the
identifier value incrementing by one only.
Syntax:
identifier ++ ;
Ex: a++;
Decrement operator (- - )
It is always decreased by one value and result stored into the same identifier. We have
two types of decrement operators.
Pre – decrement ex: --a;
Post – decrement ex: a--;

14
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Pre – decrement
When ever pre – decrement operators using into the arithmetic expressions then it is
decreasing the one value to the adjusting identifier and processing into the expressions.
This can be written as -- identifier.
Ex: --a;
Post decrement
When ever the post decrement operators including into the arithmetic operations then the
identifier values directly participating into the arithmetic expressions. After that the
identifier values decrement by one only.
Syntax:
Identifier --;
7). Bitwise operators:
Operator meaning
& Bitwise And
| Bitwise OR
^ Bitwise Exclusive OR (XOR)
<< Left Shift
>> Right shift
~ One’s Complement
The bit wise operators can be used to do the binary operation (binary manipulations).
Like addition sub multiplication etc. C allows the programmer to interact directly with
the hardware of a particular system through bitwise operators and expression. These
operators work only with int and char datatypes and cannot be used with float or double
type.
Bitwise Exclusive OR (XOR) Operator:
An exclusive OR set the 0 bit 1, if both bits that are compared are different. The truth-
values for XOR are.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1

15
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

1 ^ 1 = 0
for example 127 ^ 120 is
01111111 127 in binary
01111000 120 in binary
XOR result= 00000111
Bitwise complement operator:
The bitwise complement (or one’s complement) operator ~ (called tilde) changes each 1
bit in its operand to 0 and changes 0 bit to 1, ~0= 1, ~1= 0.
For example:
Consider that , the int variable has the value 5.
The binary number is 0000000000000101
The bitwise complement ~ is 1111111111111010
Shift Operators >> and <<
The shift operators move all the bits in a variable to the right or left as specified. The
general form of the shift right statement is
Variable >> number of bit positions.
The general form of the shift left statement is
Variable << number of bit positions,
As bit are shifted out to one end, the zeros are entered from the other end. The bits which
are shifted out are lost. The shifting of bit is not a rotation of bits.
Consider the following operations where the initial value of x is 9
X=9 00001001 9
X << 1 00010010 18
X << 1 00100100 36
X << 2 10010000 144
X >> 1 01001000 72
X >> 1 00100100 36
X >> 2 00001001 9
It can be noted from the above operations that the left shift by one place is nothing but
multiplications of a number with 2, and the right shift by one place is nothing but division
of a number by 2 .

16
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

8). Conditional operator (?:)


C provides a peculiar operator ?: which is useful in reducing the code. It is ternary
operator requiring three operands.
The general format is
Exp1 ? Exp2 : Exp3 ;
Where exp1, exp2 and exp3 are expressions. The constituents of conditional operator are
separated in conditional expressions and the order should not be changed, that is should
be in between the first two expressions and : should be between the second and third
expressions.
In the above conditional expression, exp1 is evaluated first. If the value of exp1 is non
zero (true), then the value returned will be exp2. if the value of exp1 is zero (false). Then
the value returned will be exp3.
Example:
#include < stdio.h>
main()
{
int option;
printf(“Enter any number “);
scanf(“%d”, &option);
option ? printf(“Entered non-zero number”): printf(“entered zero”);
}
example 2: z= (x>10 ? 8: -3);

9). Special operators:


1. Comma operator
The comma operator allows two or more different expressions to appear when only one
expression is expected. The expressions are separated by the comma operator.
The general form is
Exp1,exp2, exp3,…expn

2. Size of operator

17
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

The sizeof operator in c will determine the size of variables storage in bytes. The
sizeof operator is a unary operator and can be used to know the size of any variable,
constant, etc. the sizeof operator is very useful in writing machine- independent
program.
INPUT AND OUTPUT STATEMENTS
printf() function: Writing Output Data
The printf() function is used to write information to standard output (normally monitor
screen). The structure of this function is
printf(“ format specifiers “, var1,var2,var3,…….var n);
Example:
printf(“%d”, a);
scanf() function: getting user input
The real power of a technical C program is its ability to interact with the program user.
This means that the program gets input values for variables from users.
The scanf() function is a built-in C function that allows a program to get user input from
the keyboard.
Syntax: scanf(“format specifiers”, &var1,&var2,……&var n);
CONTROL STRUCTURES
C supports the following three control structures:
i. Sequence structure
ii. Selection structure
a. -if statement, if/else statement and switch statement. These statements are
known as conditional statements
iii. Repetition (loop) structure
- for statement, while statement and do-while statement. These statements are
known as iterative statements.

1. Sequence Structure:
Sequence means executing one statement after another, in the order in which they occur
in the program. This is the default action in C language.

18
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

2. Selection Structure
Selection means executing different section of code depending on a condition or the
value of a variable. This allows a program to take different actions depending on different
circumstances. C provides three selection structures:
i. The if selection structure
ii. The iflese selection structure
iii. The switch selection structure
3. Repetition Structures:
Repetition means executing the same section of code (a single statement or a set of
statements) more than once. Here, a section of code is either executed while some
condition is true or a fixed number of times. C provides three repetition structures:
I. while
II. do- while
III. for
if statement:
The if selection structure allows the programmer to specify that a section of code should
only be executed if a certain condition is true. The syntax for this statement is
Syntax: If (condition)
Statement;
Where condition is an expression that has a true or false value and statement is the
statement that should only be executed if the expression is true. For example:
if (number1 > number 2)
printf(“number1 is greater than number2 \n”);
if more than one statement should be executed when the condition is true, then these may
be grouped together inside braces. For example:

if (number1 > number2)


{
printf(“ %d is greater than %d\n”, number1, number2);
printf(“ %d is less than %d\n”, number2, number1);
}

19
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

/* Write a program to check the given value is positive or negative */


main()
{
int number; /* variable declaration part */
clrscr();
printf("Enter any number");
scanf("%d",&number); /*reading value from keyboard */
if(number>0) /* to check number is > 0 or not */
printf("number is positive ");
if(number<0)
printf("number is negative ");
getch();
}
Output:
Enter any number
6
Number is positive
/*write a program to check the given no is even or odd using if statement */
main()
{
int number, rem;
clrscr();
printf("Enter any number");
scanf("%d",&number);
rem= number %2;
if(rem==0)
printf("number is even");
if(rem!=0)
printf("number is odd");
getch();

20
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

}
Output:
Enter any number
5
number is odd
if else statement:
The if/else statement extends the idea of the if statement by specifying another section of
code that should be executed only if the condition is false.
Syntax:
If (condition)
Statement 1;
else
statement 2 ;
where condition is an expression which evaluates to true or false value, statement 1 is the
statement to be executed only if the condition is true, and statement 2 is the statement to
be executed only if the condition is false. For example:
if ( number1 > number2 )
printf(“%d is greater than %d \n”, number1, number2);
else
printf(“%d is not greater than %d \n”, number1, number2);

start

false
Condition
False statements

true
True statements
Nested IF- ELSE Statement:
When a series of conditions are involved, we can use more than one if-else
statement in nested form.

21
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

If(condition1)
{
statements
}
else
if(condition )
{
statements
}
else
{
statements
}

example: If( number 1> number 2)


printf(“%d is greater than %d\n”, number1, number2);
else
if(number1>number2)
printf(“%d is less than %d\n”, number1, number2);
else
printf(“ %d is equal to %d\n”, nubmer1, number2);
Assignments
Program1:
/* Write a program to check the given value is positive or negative using if-else
statement */

Program2:
/*Write a program to check the given no is even or odd using if-else statement */

Program 3:

22
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

/* Write a program to read student roll number, name and 6 subjects marks and
find the student result, total, average and division. If student is pass then you
display total, average and division other wise no need. */
main()
{
int roll_no,total,s1,s2,s3,s4,s5,s6;
char name[30];
float avg;
clrscr();
printf("enter student roll no:");
scanf("%d",&roll_no);
printf("enter student name:");
scanf("%s",&name);
printf("enter 6 subjects marks");
scanf("%d%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5,&s6);
if( s1>35 && s2>35&&s3>35&& s4>35&&s5>35&&s6>35)
{
printf(" result =pass\n");
total=s1+s2+s3+s4+s5+s6;
avg=total/6;
printf("total=%d",total);
printf("avg=%f",avg);
if(avg>=60)
printf("First division");
else
if(avg>50)
printf("Second division");
else
printf("Third division");
}
else

23
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

printf("Result =Fail");
getch();
}
out put:
Enter student roll no 101
Enter student name: kumar
Enter 6 subjects marks: 55 65 85 75 95 44
Result : pass
Total =419 , avg=69.000000
First division.

Program 4:
/* Write a program to read 3 number and find the biggest number */

Program 5:
Write a program to check the given year is leap year or not?
The switch statement
The switch statement is an extension of the if-else statement. The switch makes one
selection when there are several choices to be made. The direction of the branch taken by
the switch statement is based on the value of any int(or int compatible) variable or
expression.
The general form of switch statement is shown bellow.

switch(integer expression)
{
case constant1 : statement1 ; break;
case constant2 : statement2 ; break;
case constant3 : statement3 ; break;
case constant4 : statement4 ; break;
“ “ “ “ “ “
“ “ “ “ “ “
“ “ “ “ “ “

24
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

case constant n : statement n ; break;


default : statement;
}
The integer expression following the key word switch is any C expression that will result
an integer value. I.e. is, it could be an integer constant or an expression that evaluates to
an integer. The key word case is followed by an integer or a character constant .the break
statement used inside each case of the switch, causes an intermediate exit from the switch
statement: and continued onto the next statement outside the switch statement.
When we execute this form of switch statement, first the integer expression is evaluated.
The value of expression is then compared one by one, with constant1,
constant2…constant n. when a match is found, the program executes the statements
following that case. The execution continues from that point till either a break statement
is found or the switch statement is completed. The break causes an immediate exit from
the switch construct. Normally, in every case, all statements following the default are
executed.

Note: if the break statement is not included, all of the statements below the match will
be executed.

Program 1:
Write a program to read any digit and print in words using switch statement.
main()
{
int digit;
clrscr();
printf("Enter any digit");
scanf("%d",&digit);
switch(digit)
{
case 0 : printf("zero");break;
case 1: printf("one"); break;
case 2: printf("two"); break;

25
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

case 3: printf("three"); break;


case 4: printf("four");break;
case 5 :printf("five");break;
case 6: printf("six");break;
case 7: printf("seven");break;
case 8:printf("eight");break;
case 9: printf("nine");break;
default: printf("not a digit");
}
getch();
}

Output:
Enter any digit 3
Three
Program 2:
Write a program to read 2 numbers and find the result based on the user choice.

Choice operation
1---------------------addition
2--------------------subtraction
3--------------------multiplication
4--------------------division
5-------------------modulo division

LOOPS
A potion of program that is executed repeatedly is called a loop. The C programming
language contains three different program statements for program looping. They are
while loop.
do-while loop

26
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

for loop
WHILE LOOP
The while loop is best suited to repeat a statement or a set of statements as long as some
condition is satisfied.
The general form of while loop is

While (expression)
{
Statement;
}
Where the statement (body of the loop) may be a single statement or a compound
statement. The expression (text condition) must results zero or non-zero.
First of all, the expression in the while loop is evaluated. If the result is true (non-zero),
then the statement is executed and the expression is evaluated again. The statement
continues to execute until the expression evaluates to false (zero). Then the loop is
finished and the program execution continues with the statement that follows the body of
while loop.
Flow chart:
Start

Initilization

False
Condition
True
true

Loop statements Stop

Loop counter update

27
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Program 1
Write a program to display 1 to 10 natural numbers
main()
{
int number=1;
clrscr();
while(number<=10)
{
printf("%d\t", number);
number++;
}
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10

Program 2
/* To print the even numbers between 1 to 100 using while loop */
main()
{
int num=1;
clrscr();
while(num<=100)
{
if(num%2==0)
{
printf("%d\t",num);
}
num++;
}
getch();

28
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Assignments
Program 3: Write a program to read any number and find the factorial of the given
number.
Program 4:
Write a program to print the multiplication table of the given number
Program 5:
Write a program to read (accept) any number and print the reverse of the given
number.
main()
{
long int number, reverse=0,rem;
clrscr();
printf(“Enter any number”);
scanf(“%ld”,&number);
while(number>0)
{
rem=number%10;
reverse=reverse*10+rem;
number=number/10;
}
printf(“reverse of the given no=%ld”,reverse);
getch();
}
output:
Enter any number 123
Reverse of the given no =321
Program 6:
Write a program to read any number and check weather it is prime number or not?
Program 7:

29
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Write a program to read any number and check weather it is a polindrom number
or not?
Program 8: Print the prime numbers between 1 to 100
Do-WHILE LOOP
The structure of do-while loop is similar to while loop. The difference is that in case of
do-while loop the expression is evaluated after the body of loop is executed. In case of
while loop the expression is evaluated before executing body of loop.
The general form of do-while statement is
do
{
Statements;
}
while(expression);
where statement is a single statement of compound statement. In contrast to while loop
statement (body of loop), do-while loop is executed one or more times.
In do-while loop, first the statement is executed and then the expression is tested. If the
expression evaluates to false (zero), the loop terminates and the execution control transfer
to the next statement that fallows it. Otherwise, if expression evaluates to true (non-zero),
execution of the statement is repeated and the iterative process continues.

30
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Flow chart of do-while:


Start

Initilization

Loop statements

Loop counter update

True Condition false

Stop
Program 1:
Write a program to display 1 to 10 natural numbers using do-while.
main()
{
int number=1;
clrscr();
do
{
printf("%d\t", number);
number++;
} while(number<=10); /* to check the condition is true or false
getch();
}

Output:
1 2 3 4 5 6 7 8 9 10

31
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Program 2:
/* To print the even numbers between 1 to 100 using do-while*/
program 3:
Write a program to read (accept) any number and print the sum of the digits. (123 =
1+2+3)
Program 4:
Wap to print multiplication tables from 1 to 10 using do-while loop
Program 5:
To check whether the given no is prime or not using do-while

FOR LOOP
The for loop is most common in major programming languages. The for loop in C
language is very flexible and very powerful. Generally, the for loop is used to repeat the
execution of a statement for some fixed number of times.
The general form of for loop is
for (initial-expression; conditional-expression; increment-expression)
Statement;
Where the statement is single or compound statement.
Initial-expression is the initialization expression, usually an assignment to the loop-
control variable. This is performed once before the loop actually begins execution.
Conditional –expression is the test expression. Which is evaluated before each iteration
of the loop, which determines when the loop will exist.
Increment-expression is the modifier expression, which changes the value of loop control
variable. This expression is executed at the end of each loop.
These three sections are separated by semi colons. The for loop repeats the execution of
the statement as long as the conditional expression evaluates to true (1). Once this test
condition becomes false, the for loop will terminate and control resumes to the statement
that immediately following for loop.

32
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Program 1:
Write a program to print the multiplication tables from 1 to 10 using for loop.
main()
{
int tableno, c, i;
clrscr();
for(tn=1;tableno<=10;tableno++) /* incrementing table no number */
{
for(i=1;i<=10;i++) /* printing multiplication table */
{
printf("%d * %d =%d\n",tableno,i,tableno*i);
}
getch();
}
}
Program 2:
/* wap to print ASCII values of characters */
main()
{
int i;
clrscr();
for(i=0;i<256; i++)
{
printf("%c-----------> %d\n",i,i);
getch();
}
getch();
}

33
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Program 3:
/* wap to print following format */
1
12
123
main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++) /* outer loop */
{
for(j=1;j<=i;j++) /* inner loop */
{
printf(" %d",j);
}
printf("\n");
}
getch();
}

Program 4: wap to print following format


A
BB
CCC

main()
{
int i,j;
clrscr();
for(i=65;i<=68;i++) /* outer loop */
{
for(j=65;j<=i;j++) /* inner loop */

34
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

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

Program 5: wap to print following format


333
22
1
Program 6: wap to print following format
CCC
BB
A
Program 7: wap to print the following format
*
**
***
Program 8:
/* To print the even numbers between 1 to 100 using for loop */
program 9:
Write a program to read (accept) any number and print the sum of the digits. (123 =
1+2+3)
Program 10:
Wap to print multiplication tables from 1 to 10 using for loop
Program 11:
To check whether the given no is prime or not using for loop

break and continue statement

35
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

C provides the break and continue statements to stop a particular iteration of a loop/block
early, for instance if an abnormal condition occurs. A break statement inside the body of
a loop (or block) breaks completely out of the loop (or break). No more instructions in
the loop( or block) are executed. And the next statement after the loop (or block) will be
executed.
The continue statement just skips any instructions after it on that iteration of the loop.
The current iteration of the loop is terminated, and the loop statement is executed again as
if the last instruction of the loop body has been reached.
Example:
main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5) /* if i value is 5 immediately control increments the loop counter
with out executing loop */
{
continue;
}
printf("i=%d\t",i);
}
getch();
}
Output:
1 2 3 4 6 7 8 9 10
goto statement:
A goto statement is an unconditional jump statement. It jumps to a position
indicated by label.
Example:
/* goto statement */

36
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

main()
{
clrscr();
printf("line 1\n");
goto last;
printf("line 2\n");
printf("line 3\n");
printf("line 4\n");
printf("line 5\n");
last:
printf("line 6\n");
printf("This is last statement");
getch();
}

Output:
Line 1
Line 6
This is last statement
In the above example, last is the label and when the goto statement is executed, the
execution control transfers to the statement indicated by last followed by colon ( : )

37
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

ARRAYS
An array is a collection of elements of same type. The elements of an array referred by a
common name and are differentiate from one another by their position with in an array.
The elements of an array can be of any data type but all elements in an array must be of
the same type. (or) An array is a group of memory location of same type. Arrays are two
types they are
1. one dimensional array (single dimensional array)
2. two dimensional array
One dimensional array:
Elements arranged in the form of single row or column is called one-dimensional array.
The general form of declaring a one-dimensional array is
Datatype array-name[size];
Where datatype means basic datatypes (int ,float, char, double). Array-name is the name
of the array and size is the number of elements that array-name contains.
The individual elements of an array can be referenced by means of its subscript
(or index). Suppose A is an array of 20 elements, we can reference each element as
Array name Subscript (index)

A[0] 1st element


A[1] 2nd element
A[2] 3rd element
.
.
.
A[19] 20th element
Sub script enclosed within parenthesis
In C-lang supports starts from zero. That is, if we declare an array of size n, then we can
refer the elements from 0 to (n-1) th element.
Example:
int b[15], marks[20];
float rates[50];

38
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

char name[30];
Initialization of one-dimensional array
Int a[5]= { 10,3,45,65,-90};
Float b[3]= { 33.4,45.5,5.5};
Two-dimensional array:
Elements arranged in the form of rows and column. That means just like table form
where each element is identified by unique row and unique column number. The general
declaration of two-dimensional array is
Datatype array-name[row size][column size];
Where row size referred as the number of rows and column size referred as the number of
columns.
Initialization of two-dimensional array
Int a[3][3] = { 1,2 ,33,454,65,54,55,5,32};
Or
Int a[3][3] = { {1,2,33},{454,65,54},{55,5,32}};
Example 1: /* to initialize 5 array elements and display */
main()
{
int a[5]={10,5,-90,100,30},i; /* array initialization */
clrscr();
printf("The array elements are\n");
for(i=0;i<5;i++)
{
printf("a[%d]=%d\n" ,i,a[i]);
}
getch();
}
Output
A[0]=10
A[1]=5
A[2]=-90

39
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

A[3]=100
A[4]=30
Example 2: /* to read n array elements from the keyboard and display */
main()
{
int a[200],i,n; /* array declaration */
clrscr();
printf("Enter how many elements u want to store \n");
scanf("%d",&n);
printf("Enter %d elements into array\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("The array elements are\n");
for(i=0;i<n;i++)
printf("a[%d]=%d\n",i,a[i]);
getch();
}
Output:
Enter how many elements u want to store 5
Enter 5 elements into array 10 4 88 9 3
The array elements are
A[0]=10
A[1]=4
A[2]=88
A[3]=9
A[4]=3
Example 3: /* to read 5 array elements and display */
main()
{
int a[5],i; /* int array, one variable declaration */
clrscr();

40
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

printf("Enter 5 integer elements");


for(i=0;i<5;i++)
{
scanf("%d",&a[i]); /* takes single value from keyboard */
}
printf("The array elements are\n");
for(i=0;i<5;i++)
printf("a[%d]=%d\n",i,a[i]);
getch();
}
Output:
Enter 5 integer elements
10 4 88 9 3
The array elements are
A[0]=10
A[1]=4
A[2]=88
A[3]=9
A[4]=3

Example 4: To initialize 5 array elements and display, print the sum of elements .
Example 5: To accept n elements from keyboard and find maximum, minimum
elements
Example 6:To read n elements and find searching element is found or not.
Example 1: /* to initialize 2 *2 matrix elements and display */
main()
{
int a[2][2] = { 2, 6, 5, 8 }, i,j;
clrscr();
printf("The given 2 * 2 matrix elements are \n");
for(i=0;i<2;i++)

41
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

{
for(j=0;j<2;j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
getch();
}
Output:
The given 2 * 2 matrix elements are
2 6
5 8
Example 2: /* wap to read 2*2 matrix elements and display */
main()
{
int a[2][2],i,j;
clrscr();
printf("enter elements of 2*2 matrix\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("The given elements of 2*2 matrix\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}

42
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

getch();
}
Output:
enter elements of 2*2 matrix
22 45 3 6
The given elements of 2*2 matrix
22 45
3 6
Example 3 : /* To read m*n matrix elements and display */

Example 4: * Addition of two m*n matrix */


main()
{
int a[10][10],b[10][10],c[10][10],r1,c1,r2,c2,i,j;
clrscr();
printf("Enter the size of first matrix");
scanf("%d%d",&r1,&c1);
printf("Enter the size of second matrix");
scanf("%d%d",&r2,&c2);
if(r1==r2&&c1==c2)
{
printf(“ matrix addition possible\n”);
printf("Enter elements of first matrix %d * %d\n",r1,c1);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
printf("\n");
}

43
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

printf("Enter elements of second matrix %d * %d\n",r2,c2);


for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]); /* reading second matrix elements */
}
}
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
c[i][j]=a[i][j]+b[i][j]; /* matrix addition here */
printf("After adding\n");

for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
else printf("Matrix addition not possible");
getch();
}
Output:
Enter the size of first matrix 2 3
Enter the size of second matrix 2 3
matrix addition possible
Enter elements of first matrix 2 6 3 5 8 9
Enter elements of second matrix 6 8 3 9 1 0

44
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

After adding
8 14 6
14 9 9

Example 5 : /*Find the Multiplication of two m*n matrix */

STRINGS:
String is a special kind of an array. String can be represented as an array of characters. A
string is a one-dimensional array of characters terminated by a null character (\0). The
ASCII value of null character is 0. A string constant can be represented in C by enclosing
its characters inside double quotes without null character.
For Example, the string “computer” is stored in memory as

‘c’ ‘o’ ‘m’ ‘p’ ‘u’ ‘t’ ‘e’ ‘r’ ‘\0’

String constant should be enclosed with in double quotes. C inserts null character
automatically at the end. A string can be read or print using format specifier %s, in scanf
and printf functions. The scanf function reads all the characters up to blank, Hence %s is
used only to read a single word at a time. To over come this limitation the function gets()
can be used.

INITIALIZATION OF STRING ARRAYS DURING DECLARATION


Char s1[20]=”welcome”;
Char s2[20]={‘w’,’e’,’l’,’c’,’o’,’m’,’e’};
Char s3[]=”welcome;
Char s4[]={‘w’,’e’,’l’,’c’,’o’,’m’,’e’,’\0’};
Example 1: /* initialization of strings during declaration */
main()
{
char str1[20]="welcome to";
char str2[20]={'w','e','l','c','o','m','e'};

45
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

char str3[]="welcome";
char str4[]={'w','e','l','c','o','m','e','\0'};
clrscr();
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
printf("str3=%s\n",str3);
printf("str4=%s\n",str4);
getch();
}
Output:
Welcome to
Welcome
Welcome
Welcome
Example 2: /* Accept one string from key board using gets function */
main()
{
char s[100];
clrscr();
printf("Enter one string");
gets(s);
printf("After reading\n");
puts(s);
getch();
}

Output:
Enter one string Welcome to strings topic
After reading
Welcome to strings topic

46
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Example 3: To read any string from the keyboard using getchar function.
#include<stdio.h>
main()
{
char str[100],c; /* char array, variable declaration */
int i=0;
clrscr();
printf("Enter any string:");
do
{
c=getchar(); /* it takes single charecter from keyboard */
str[i] =c;
i++;
}while(c!='\n');
str[i]='\0';
printf("The given string is=\n");
puts(str); /* display string */
getch();
}
Output:
Enter any string: welcome to strings topic
The given string is=
welcome to strings topic

47
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

String handling functions


Every C compiler provides a large set of string handling library functions, which are
contained in the header file string.h
The following table shows some of the functions available string.h header file.
Function Meaning
strcat() String concatenate. Append one string to another. First character of string2
overwrites null character of string1.
Strlen() Returns the length of the string not counting the null character.
Strlwr() Converts a string to lower case.
Strupr() Converts a string to upper case
Strncat() Appends first n characters of a string at the end of another.
Strcpy() Copies a string into another.
Strncpy() Copies first n characters of one string into another.
Strcmp() Compares two strings
Strncmp() Compares first n characters of two strings.
Strcmpi() Compares two strings without case sensitivity.
Strdup() Copies a string into a newly created location.
Strrev() Reverse a string.

Note: The statement, which are starting with ‘#’ are called preprocessor commands.
These commands are processed before compilation of the program.
Example 4: To add 2 given strings using strcat function.
main()
{
char str1[300],str2[300];
clrscr();
printf("Enter first string:);
gets(str1);
printf("Enter second string:);
gets(str2);

48
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

strcat(str1,str2); /* combine 2 strings and stored in str1 */

printf("After adding 2 strings:\n");


puts(str1); /* display str1 */
getch();
}
Output:
Enter first string: welcome to hyd
Enter second string: computer
After adding 2 strings:
Welcome to hydcomputer
Example 5: To find the length of the given string.

Example 6: To convert the given string to lowercase.


Example 7: To convert the given string to uppercase
Example 8: To concatenate (add) given 2 strings
Example 9: string copy from one array to another array.
Example 10: To compare 2 given strings
Example 11: To compare first n characters of the 2 strings
#include<string.h>
main()
{
char str1[30],str2[30];
int c,n;
clrscr();
printf("Enter first string");
gets(str1);
printf("Enter second string");
gets(str2);
printf("Enter how many characters u want to compare\n");
scanf("%d",&n);

49
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

c=strncmp(str1,str2,n);
if(c==0)
printf("first n characters r equal\n");
else
printf("first n characters r not equal");
getch();
}
Output:
Enter first string:
Welcome
Enter second string:
Computer
Enter how many characters u want to compare
5
first n characters r not equal
Example 11: To compare 2 given strings without case sensitive.
#include<string.h>
main()
{
char s1[100],s2[100];
int c;
clrscr();
printf("Enter first string:\n);
gets(s1);
printf("Enter second string:\n);
gets(s2);
c=strcmpi(s1,s2); /* it returns difference value */
if(c==0) /* c value is 0 or not */
printf("both are equal");
else
printf("both are not equal");

50
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

getch();
}
Output:
Enter first string:
Welcome
Enter second string:
WELCOME
both are equal
Example 12: Find the reverse of the given string.
Example 13: read any string and display given string, find null position.

getchar()
The getchar() function allows us to read a character from the standard input. Using the
getchar() only one character can be read at time but a string cannot be read. To read
strings using the getchar, we have to use getchar function within a loop by reading a
single character in each iteration. However, the null character (‘\0’) at the end of the loop
to recognize that the input value is string.
Example 14: write a program to read 5 strings and display 5 strings.
#include<string.h>
main()
{
char str1[5][15];
int i;
clrscr();
printf("Enter 5 strings");
for(i=0;i<5;i++)
gets(str1[i]);
puts("The given 5 strings are");
for(i=0;i<5;i++)
puts(str1[i]);
getch();

51
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

FUNCTIONS
Functions are building blocks of C. functions are self-contained sub programs of main
program and function contains set of instructions. Each function performs a specific task.
Functions support the concept of top-down modular programming design technique. Each
function in C consists of a name, a return type and a possible parameter list. Variables
declared in functions are called local variables, global variables can be accessed by any
function.
Functions are two types. They are
1. Pre-defined functions or library functions
2. User-defined functions
Example for pre-defined functions are scanf(), printf(), clrscr(), getch(), etc.
Example for user-defined functions are sum(), display(), welcome(), address(), etc.
The general form of C function is
Return-type function-name(parameter list)
Parameter declaration;
{

body of function;
}
If there are no parameters, the parameter declaration part is not needed. Note that main
function also having similar type of structure as shown above. The body of the function
contain local declarations (if any) and statements.
Every function calling from main function and every function returns a value. But in C,
the values returned by many functions are ignored. We can declare functions of type
void, which means that they don’t return any value.
In general, C can return any basic data type such as char, int, float, void etc.,
Function calling four types they are
i. Function calling without parameters and without return statement.
ii. Function calling with parameters and without return statement.

52
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

iii. Function calling without parameters and with return statement.


iv. Function calling with parameters and with return statement.
1. Programs on function calling without parameters and without return statement.
void hello(); /* function prototype or fun declaration */
main()
{
hello(); /* function calling */
printf(“this is main function\n”);
printf("\n end of the main function");
getch(); /* pre defined function calling */
}
void hello() /* fun definition or called function */
{
clrscr(); /* pre defined function calling */
printf("This is hello function");
printf("\n this is user-defined function ");
}
Output:
This is hello function
This is user-defined function
This is main function
End of the main function
Program 2: Find the given number is prime or not.
void prime(); /* function prototype */
main()
{
clrscr();
prime(); /* function calling */
getch();
}
void prime() /* calling function or called function */

53
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

{
int i, count=0,n; /* local variable */
clrscr();
printf("Enter any number:");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
{
count++;
break;
}
}
if(count==0)
printf("\n The given no is prime no");
else
printf("\n the given no not a prime no");
}
Output:
Enter any number: 5
The given no is prime no
2. Programs on function calling with parameters and without return statement.

Program 1: Find the given number is prime or not.

void prime(int); /* function prototype */


main()
{
int n; /* local variable */
clrscr();
printf("Enter any number");

54
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

scanf("%d",&n);
prime(n); /* function calling with parameter or argument */
getch();

void prime(int n) /* called function */


{
int i,count=0; /* local variables */
for(i=2;i<n;i++)
{
if(n%i==0)
{
count++;
break;
}
}
if(count==0)
printf("The given no is prime no");
else
printf("the given no not a prime no");
}
Output:
Enter any number: 4
The given no is not a prime no
Program 2: Find the sum, sub and mul of two given numbers.
void sum(int,int);
void sub(int, int);
void mul(int, int);
main()
{

55
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

int a,b ; /* local variables */


clrscr();
printf("Enter any 2 values:");
scanf("%d%d",&a,&b);
sum(a,b); /* fun calling with a,b values */
sub(a,b); /* fun calling with a,b values */
mul(a,b); /* fun calling with a,b values */
getch();
}
void sum(int x, int y) /* called function and here x, y variables are local*/
{
printf("this is sum function\n");
printf("sum of 2 values=%d\n",x+y);
}
vod sub(int p, int q) /* called function and here p, q variables are local*/
{
printf("this is sub function\n");
printf("subtraction of 2 values=%d\n",p-q);
}
void mul(int m,int n) /* called function and here m, n variables are local*/
{
printf("this is mul function\n");
printf("multiplication of 2 values=%d\n",m*n);
}
Output:
Enter any 2 values: 10 6
this is sum function
sum of 2 values= 16
this is sub function
subtraction of 2 values= 4
this is mul function

56
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

multiplication of 2 values=60

Program 3: Find the reverse of the given number.


3. Programs on function calling without parameters and with return statement.
Program 1: /* fun without parameters and with return statement */
int sum(); /* fun prototype */
void main()
{ int s; /* local variable */
clrscr();
s=sum(); /* fun calling without arg and take return statement */
printf("return value is %d\n",s);
getch();
}
int sum() /* called function */
{
int a,b; /* a,b are local variables */
printf("Enter a, b values:");
scanf("%d%d",&a,&b);
return (a+b); /* value return to calling function */
}
Output:
Enter a, b values: 10 30
return value is 40

4. Programs on function calling with parameters and with return statement.

Program 1: To find the given no is even or odd.

int number(int); /*fun prototype */


void main()
{

57
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

int r,num; /* local variables */


clrscr();
printf("Enter any number:");
scanf("%d",&num);
r=number(num); /* function calling with arg and take return val*/
if(r==0)
printf("the given no is even");
else
printf(" the given no is odd");
getch();
}
int number(int n) /* called function */
{
if(n%2==0)
return 0;
else
return 1;
}
Output:
Enter any number: 5
the given no is even
Program 2: To find the factorial of the given no.
RECURSION
Recursion is a technique to be used to call itself. In C it is possible for the functions to
call themselves. A function is called recursive if a statement with in the body of a
function calls the same function itself.
Consider a simple example which finds the factorial of a number. A factorial of a number
is the product of all the integers between and that number.
For example 5 factorial is 5*4*3*2*1.
Program 1: write a program to find the factorial of the given number using
recursive function.

58
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

long int factorial(int); /* fun prototype */


void main()
{
int n;
long int f;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
f=factorial(n); /* fun calling in main function */
printf("factorial of given no=%ld",f);
getch();
}
long int factorial(int n)
{
if(n==1)
return 1;
else
return n*factorial(n-1); /* fun calling itself */
}
Output:
Enter any number: 10
factorial of given no =3628800
Passing Arrays into functions:
Program 1: Write a program to read 5 array elements and display those elements
using function with passing arguments.
void display(int [],int);
main()
{
int a[5],i;
clrscr();
printf("Enter 5 elements \n");

59
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

for(i=0;i<5;i++)
scanf("%d",&a[i]);
display(a,5); /* fun calling with passing array*/
getch();
}
void display(int a[],int size) /* fun definition */
{
int i;
printf(“the given 5 array elements are\n”);
for(i=0;i<size;i++)
printf("%d\t",a[i]);
}
Output:
Enter 5 elements
10 5 30 6 55
the given 5 array elements are
10 5 30 6 55
Program 2: write a program to display list of array elements using fun with
argument without return value.
void display(int []);
void main()
{
int a[5]={10,3,4,55,-90};
clrscr();
display(a); /* fun calling */
getch();
}
void display(int b[])
{ int i;
printf("Array elements are\n");
for(i=0;i<=4;i++)

60
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

printf("%d\t", b[i]);
}

Program 3
/* print the sum of array elements using fun with arg and with return state*/

POINTERS

Pointer is a derived data type and is used to store address of another variable. A pointer
variable in C is declared as follows:
Data-type *pointer-variable-name;
Examples:
Int *ptr; /* pointer- to- int */
float *fptr; /* pointer-to-float */

In the declaration, the asterisk (*) indicates that the pointer-variable and data-type
indicates the type the pointer is pointing to. Thus, when a pointer is declared, the type of
variable the pointer will address has to be specified. If a pointer is declared address of a
floating point number (or address of any type other than integer).
There are two important operators in C to work with pointers: asterisk (*) and ampersand
(&).
In case of array, once the size of the array is declared, it is not possible to increase
or decrease its size during program execution. But by using pointer, the memory can be
allocated or de-allocated dynamically. Pointers allow to pass variables, arrays, functions,
strings and structures as function arguments.
Program1: Demonstration on pointers.
main()
{
int a=20;
int *ptr1=&a; /* address of a is assigned to ptr1 */
int **ptr2=&ptr1; /* address of ptr1 is assigned to ptr2 */

61
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

clrscr();
printf("value of a=%d\n",a); /*display value in a */
printf("address of a=%u\n",&a); /*display address of a */
printf("address in ptr1=%u\n",ptr1); /* display content in ptr1 */
printf("value in that address =%d\n",*ptr1); /* value in that content */
printf("Address of ptr1=%u\n",&ptr1);
printf("address in ptr2=%u\n",ptr2 );
printf("element in **ptr2=%d",**ptr2);
getch();
}
Output:
Value of a = 20
address of a= 65494
address in ptr1= 65494
value in that address = 20
Address of ptr1= 65496
element in **ptr2= 20
Program 2: Addition of two given numbers.
main()
{
int a,b,c, *ptr1,*ptr2,*ptr3;
ptr1=&a,ptr2=&b,ptr3=&c;
clrscr();
printf("Enter values for a,b");
scanf("%d%d",&a,&b);
*ptr3 = (*ptr1) +(*ptr2);
printf("After sum\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
getch();

62
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

}
Output:
Enter values for a,b: 10 33
After sum
a= 10
b= 33
c= 43

Program 3: To find the factorial of the given number.


main()
{
int num,*p=&num;
long int fact=1;
clrscr();
printf("enter any number:");
scanf("%d",&num);
for(; *p >0; (*p)--)
{
fact = fact * (*p);
}
printf("factorial of given no =%ld",fact);
getch();
}
Output:
enter any number: 6
factorial of given no = 720

Program 4: To assign 5 integer array elements and display.

Program 5: To read n array elements and display.


Program 6: To find the maximum element in the array.

63
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Program 7: To read m * n matrix and display.

main()
{
int a[10][10],*ptr=&a[0][0],m,n,i,j;
clrscr();
printf("Enter the size of the matrix:");
scanf("%d%d",&m,&n);
printf("Enter elements of %d * %d\n",m,n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("The given matrix elements are\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(" ele=%d\t",*(*(a+i)+j) );
}
printf("\n\n");
}
getch();
}

Output:
Enter the size of the matrix: 2 3
Enter elements of 2 * 3
10 3 6 8 2 0
The given matrix elements are
10 3 6
8 2 0

64
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Program 8: To read 2*2 matrix elements and display.


Program 8: program on call by reference
void arithmetic(int ,int *); /* prototype */
void main()
{
int a=9,b;
clrscr();
printf("Before function calling\n");
printf("a=%d\n",a);
arithmetic( a, &b); /* passing a value and b variable address */
printf(" After function calling\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
getch();
}
void arithmetic(int n,int *ptr )
{
printf("values in function body \n");
printf("n=%d\n",n);
*ptr = (n) * (n); /* result stored in *ptr i.e in b */
}
Output:
Before function calling
a= 9
values in function body
n= 9
After function calling
a= 9
b= 81

65
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Call-by-value:
A copy of the argument’s value is made and passed to the called function. Therefore,
changes to the copy do not effect the original variable’s value in the caller. The function
works with a copy of the argument sent to it.

Call-by-reference:
This is also called as pass-by-address or call-by-address. In this instead of passing the
values of the variables as parameters, the addresses of the variables are passed as
arguments. This is achieved by using the pointer.
In this mechanism, the caller gives the called functions the ability to directly access the
caller’s data. The function receives reference to variable and works directly with the
original variable.
STRUCTURES AND UNIONS
C allows us to create new datatypes using structures and unions.
A structure is a collection of variables of different datatypes. That are logically grouped
together and referenced under one name. that is, a structure provides a compound
datatype. So, we can buid more complex datatypes using structures.
A union is also a collection of variables of different data types. Unlike structures, the
variables share the same memory data.
Declaration of a structure:
The general form of structure declaration is
struct structure-name
{
data type variable 1;
data type variable 2;
data type variable 3;
.
.
.
data type variable n;
};

66
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

The structure declaration starts with the keyword struct followed by the name of
structure. Sandwiched between open and closed braces, we provide the type declaration
for the members of the structure. After the closing brace, we must specify semicolon (;).
That means every structure must end with semicolon. The members of a structure are
often called structure elements.
Initialization of structure variables:
We can create structure variable at end of the structure declaration or below the structure
declaration or within the main function.
A member of particular structure can be referenced by using dot operator (.) as follows.
Structure-variable-name.member-name;
For example
struct employee
{
int empno;
char name[30];
char dept[30];
float salary;
} emprec1; /* structure variable declaration */
For example, to reference the empno of emprec1 structure, we can write as
emprec1.empno;
The ‘.’ Operator connects the structure-name and the member name. the following simple
program illustrate the structure declaration and referencing its elements using ‘.’ (dot)
operator.
#include<stdio.h>
main()
{
struct employee
{
int empno;
char name[30];
char dept[30];

67
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

float salary;
}emprec;
emprec.empno=1;
strcpy(emprec.name,"ANIL KUMAR");
strcpy(emprec.dept, "IT");
emprec.salary=10000;
printf("Employee no : %d\n", emprec.empno);
printf("Employee name : %s\n",emprec.name);
printf("Employee designation :%s\n",emprec.dept);
printf(" salary : %f\n", emprec.salary);
}

Output:
Employee code : 1
Employee name : ANIL KUMAR
Employee designation : IT
salary : 10000.000000
Program 2: print the address of structure members(elements).
struct emp
{
int eno;
char *name;
float sal;
}e; /* structure variable declaration */
void main()
{
e.eno=10; /* Assigning structure elements */
e.name="kumar";
e.sal=1000;
clrscr();
printf("address of eno=%u\n",&e.eno);

68
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

printf("address of name =%u\n",&e.name);


printf("address of sal=%u\n",&e.sal);
printf("eno=%d\nname=%s\nsal=%f",e.eno,e.name,e.sal);
getch();
}
Output:
address of eno= 1868
address of name = 1870
address of sal= 1872
eno= 10
name = kumar
sal= 10000

Program 3: To read employee eno, name, sal of two records from keyboard.

Program 4: multiple structures declared in main functions.


void main()
{
struct student
{
int sno;
char sname[20];
float marks;
}s; /* structure variable declaration here */
struct emp
{
int eno;
char ename[10];
float sal;
}e; /* structure variable declaration of emp */
clrscr();

69
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

printf("Enter student sno,name,marks:");


scanf("%d%s%f",&s.sno,s.sname,&s.marks);
printf("Enter emp no ,name,basic:");
scanf("%d%s%f",&e.eno,e.ename,&e.sal);
printf("the given details are\n");
printf("sno=%d\n",s.sno);
printf("name=%s\n",s.sname);
printf("marks=%f\n",s.marks);
printf("-------------\n");
printf("eno=%d\n",e.eno);
printf("ename=%s\n",e.ename);
printf("esal=%f",e.sal);
getch();
}
Output:
Enter student sno,name,marks: 11 anil 560
Enter emp no ,name,basic: 1203 janardan 15000
the given details are
sno= 11
name= anil
marks= 560
-------------
eno= 1203
ename= janardan
esal= 15000
Program 6: /* structure within the structure */
struct student /* main structure name */
{
int sno;
char name[30], add[30];
struct marks /* sub structure name */

70
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

{
int s1,s2,s3, total;
float avg;
}m; /* structure variable declaration of marks */

}s; /* structure variable declaration of student */

main()
{
clrscr();
printf("Enter student sno,name,address:");
scanf("%d%s%s",&s.sno,s.name,s.add);
printf("Enter 3 subjects marks:");
scanf("%d%d%d",&s.m.s1,&s.m.s2,&s.m.s3);
s.m.total=s.m.s1+s.m.s2+s.m.s3;
s.m.avg=s.m.total/3;
printf("STUDENT DETAILS ARE\n");
printf("sno=%d\t name =%s\t address =%s\n",s.sno,s.name,s.add);
printf("s1=%d\t s2=%d\t s3= %d\n",s.m.s1,s.m.s2,s.m.s3);
printf("total=%d\t avg=%f\n",s.m.total,s.m.avg);
getch();
}
Output:
Enter student sno,name,address: 11 jamesbond jublihills
Enter 3 subjects marks: 56 55 35
STUDENT DETAILS ARE
sno=11 name = jamesbond address = jublihills
s1= 56 s2= 55 s3= 35
total= 146 avg= 48.666668

Program 7: the following program illustrates the use of array of structures.

71
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

struct student
{
int sno;
char name[30];
int marks;
}S[3];
main()
{
int i;
clrscr();
printf("Enter 3 records\n");
for(i=0;i<3;i++)
{
printf("This is record no =%d\n",i+1);
printf("Enter student details of sno,name,marks\n");
scanf("%d",&S[i].sno);
scanf("%s",S[i].name);
scanf("%d",&S[i].marks);
}
printf("Student details are\n");
for(i=0;i<3;i++)
{
printf("sno =%d\t name=%s\t marks =%f\n",S[i].sno,S[i].name,S[i].marks);
}
getch();
}
Output:
Enter 3 records
This is record no = 1
Enter student details of sno,name,marks: 11 Anil 550
This is record no = 2

72
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Enter student details of sno,name,marks: 22 kumar 570


This is record no = 3
Enter student details of sno,name,marks: 33 reddy 590
Student details are
sno =11 name= anil marks = 550
sno = 22 name= kumar marks = 570
sno =33 name= reddy marks = 590
Program 8: functions and structures - passing of structures as arguments.
struct add
{
int a,b;
};
void display(struct add); /* function prototype */
struct add A; /* struct variable declaration */
main()
{
clrscr();
printf("Enter a,b values");
scanf("%d%d",&A.a,&A.b);
display(A); /* calling fun and passing Struct variable */
getch();
}
void display(struct add A) /* definition fun */
{
printf("addition of a,b=%d",A.a+A.b);
}
Output:
Enter a,b values: 12 23
addition of a,b= 35

73
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

UNIONS
Union is similar to C structure, i.e., it contain members of different types. The difference
is that a C union is used to store different datatypes variables in the same memory
location. In general, the unions are used to save the memory area occupied by the
program.
The general form of union declaration is
union union-name
{
data type variable1;
data type variable2;
data type variable3;
.
.
.
} union-variables;
Note that union declaration has the same form as the structure declaration except the
keyword union. The members of union can be of different types.
The important point in using a union type variable will have only one member at any
time. Hence, any reference to the wrong type of data will produce meaningless results.
The following program illustrates the action of union.
#include <stdio.h>
main()
{
union intcharfloat
{
int i;
char ch;
float f;
}ichf;
printf("the size of union is %d bytes \n", sizeof(ichf));
ichf.i=10;

74
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

printf("the integer value stored in union is %d \n", ichf.i);


ichf.='A';
printf("the char value stored in union is %c\n",ichf.ch);
ichf.f=20.3;
printf("the float value stored in union is %f\n", ichf.f);
getch();
}
the union variable ichf occupies 4 bytes, since float variables occupies 4 bytes which is
greater than other elements in the union. The memory assigned to integer I, char ch and
float f by union variable ichf can be represented as

Byte1 Byte2 Byte3 Byte4


i
ch
f

Thus the amount of storage space occupied for a union variable is the amount of
storage required for the largest member of the union. It should be noted while using
unions is that all members are stored in the same memory space, with the same starting
address, but not at the same time.

TYPEDEF

The typedef (type definition ) allows defining a new name for an existing data type. Once
a new name is given to a data type. Then new variables, arrays, structures can be declared
in terms of this new name (user given name to data type). The general syntax of typedef
statement is give bellow:

typedef existing datatype newtype;

for example, the following statement defines a name number to the type int

75
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

typedef int number;


now, we can declare variables of the type number as
number I, j;
Note that the typedef declaration does not create new data types, but it simply creates
synonyms for existing types. Thus, this declaration is useful to give meaningful name to
the program.

FILE HANDLING

Storage of data in variables and arrays is temporary. Files are used for permanent storage
of large amount of data. Computer stores files on secondary storage device. C works with
files a new datatype called a file pointer.
C provides a data structure called FILE, declared in file stdio.h, to access the stream of
characters from the disk files. An I/O stream that is active, must have this data type FILE
associated with it. C also provides a number of functions for I/O to perform the basic file
operations such as opening a file, reading data from/ writing data to a file, etc.
FILE POINTER:
The structure ‘FILE’ which is declared in stdio.h acts like a link between OS and the
program and it is used to define a file pointer for use in file operations. Therefore, a
pointer to a FILE type is rewired to work with files on disk.
The syntax of declaring a file pointer is
FILE * file_ pointer;
Eg: FILE *fp;
Here fp is a file pointer of datatype FILE. The word FILE should be type in capital
letters.
OPENING A FILE
Syntax: fopen (“file_name”, “mode”);
Where the first parameter file_name is the name of the data file on the disk.
Which is to be opened. Mode specified the purpose of opening this file.
FILE *fp;
fp= fopen(“raju.dat”,”r”);

76
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

here raju.dat is the name of the data file to be opened and the second argument r
indicates that the file is opening for reading purpose.
Several modes are available in C. The following is the list of these modes along
with their descriptions.
Mode Description
“r” open for reading .the precondition is file must exist. Otherwise fun
returns Null value.

“w” open for writing. if file already exists ,its contents are overwritten.
Otherwise a file is created. The fun returns NULL if it is unable to
create the file.

“a” open for appending .if file already exist ,the new contents are
appended. Otherwise, a file is created. The fun returns NULL if it is
unable to create the file.

“r+” open for both reading and writing. The file must exits.

“w+”
open for both reading and writing .contents written over.

“a+”
open for reading and appending .if file is not existing ,the file is
created.

CLOSING A FILE:
The syntax of fclose function is
fclose(file_pointer);
Input/output operations on files:
The fputc() and fgetc() functions:
These input/output functions are used to read/write a single character from/ to
stream(files). The general forms are
fputc(char,fp);

77
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

fgetc(fp);
The fputc() function outputs a character to a stream. The first argument is the character to
be output and the second argument represents the file pointer. The fgetc() function reads
one character from input stream referred to by fp and returns it.
The fgets() and fputs() functions:
The fgets() and fputs() functions are used to read and write strings respectively.
The general forms are
fputs(string, fp);
fgets(string,length,fp);
The fputs() function outputs a string to a stream pointed to by fp.
The fgets() function requires three arguments. First argument is address of the string in
which the read data is to be placed. Second argument is the length of the string to be read
and the last argument is the file pointer. The fgets() function reads a string until either a
new line character or the number of characters given in the second argument have been
read. If a new line is read, it will be part of the string. However if gets() is terminated, the
resultant string will be null.
The fscanf() and fprintf() functions:
These functions are used for formatted I/O. These can handle mixed data at the same
time and behave exactly like scanf() and printf() except that they work on disk files rather
than on standard input and output. The general syntax of these functions are:
fscanf(fp, “format string”, argument list);
fprintf(fp, ”format string”, argument list);

Program 1: writing some text into a file.


#include<stdio.h>
#include<process.h>0
main()
{
FILE *fp;
fp=fopen("f:\\january.txt","w"); /* file open with writing */
if(fp==NULL)

78
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

{
printf("file can't created");
exit(0);
}
fprintf(fp,"this is first file in file handling"); /* it writes a single string */
fputc('r',fp); /* it writes single character */
fclose(fp); /* file closing */
getch();
}
Program 2: Write the addition of two numbers to file.
#include<process.h>
#include<stdio.h>
void main()
{
int a,b;
FILE *fp; /* file pointer declaration */
clrscr();
fp= fopen("single.txt","w"); /* file opening in writing mode */
if(fp==NULL) /* checking file is open or not */
{
printf("unable to open");
exit(0);
}
printf("Enter a, b values");
scanf("%d%d",&a,&b); /* reading 2 values from keyboard */
fprintf(fp, "a=%d\t b=%d\n",a,b); /* writing a,b values to a file */
fprintf(fp,"sum=%d",a+b);
fclose(fp); /* closeing file */
printf("file created");
getch();
}

79
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

Program 3: Reading data from a file.

#include<stdio.h>
#include<process.h>
main()
{
char c;
int count=0;
FILE *fp;
clrscr();
fp=fopen("f:\\january.txt","r"); /* file opened with reading mode */
if(fp==NULL)
{
printf("file does't exist");
exit(0);
}
while( (c=fgetc(fp))!=EOF ) /* reading data from a file */
{
printf("%c",c);
count++;
}
printf("\nNo charecters in a file=%d\n", count);
fclose(fp);
getch();
}
Program 4: Program on append mode
#include<stdio.h>
#include<process.h>
main()
{
FILE *fp;

80
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

int a=10;
clrscr();
fp=fopen("f:\\january.txt","a"); /* file opend with append mode */
if(fp==NULL)
{
printf("file not found");
exit(0);
}
fprintf(fp,"this is append mode"); /* writing to a file */
fprintf(fp,"\n%d",a);
fclose(fp);
getch();
}
Program 5: program to copy the data from existing file to new file
#include<stdio.h>
#include<process.h>
void main()
{
FILE *fr,*fw;
char str[50];
clrscr();
fw=fopen("d:\\Abhiram.txt","w"); /* writting purpose */
fr =fopen("anil11.c","r"); /* reading purpose */
if(fr==NULL)
{
printf("file does't exsit ");
exit(0);
}
while( (fgets(str,50,fr)) >0) /* reading data from anil11 file */
{

81
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)


lOMoARcPSD|29400031

fputs(str,fw); /* writting to a copied file is Abhiram */


}
fclose(fr);
fclose(fw);
getch();
}

Program 6: Write student sno, name ,6 subjects marks, total and average to a file on
the disk.
Program 7: To copy the data from existing file to a new file in the reverse order.

82
C Programming Lecture Notes By: Kaba Daniel

Downloaded by Diya Rajput (diyamin930@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy