Notes Notes of of Language Language
Notes Notes of of Language Language
Notes
Of
C
Language
C Language Programs
S.no Name of the Program
Simple programs(1 to 15)
1. WAP print “hello”.
“hello”.
2. Write a program to add two numbers. (without scanf()).
scanf()) .
3. Write a program to add, multiply, divide, subtract two numbers. (Without
scanf()).
4. WAP to find out simple interest. (Without scanf()).
5. WAP to enter 5 subjects’ marks and calculate total marks and percentage.
(With scanf()).
6. Write a program to give name of item, cost, qty and calculate total bill.
7. Write a program to input marks and calculate total marks and the
percentage.
8. Write a program to input the length and breadth of rectangle to calculate
its area.
9. Write a program to calculate d=(b*b)-4*a*c/quadratic
d=(b*b)-4*a*c/quadratic equation.
10. Write a program to convert centigrade to Fahrenheit.
11. Write a program to input five ages and find the average.
12.
13. Write
Write a
a program
program to
swap two
to
swap two numbers without
numbers with third
third number.
number.
14. Write a program to
input radius and find the area of circle.
15. Write a program to
print int,float values using format specifiers.
Conditional Statements
Simple If(16-21)
16. Write a program to find the smallest from two numbers.
17. Write a program to input age of a person and find whether he/she is
eligible for voting or not.
18. WAP to Input marks in three subjects calculate total marks and
percentage if per>=50 then print pass else fail.
19. Write a program to input a number and find whether it is –ve or +ve.
20. Write a program to find whether a given number is odd or even.
21. Write a program to find whether the year is leap or not.
Nested If (22-27)
22. Write a program to find greatest from three integers.
23. Input age of a person conditions are
if age<12 then child if age between 12 to 25 then young if age between
25to 50 then adult if age >=50 old.
24. WAP to calculate the division of a student after getting valid marks for
three subjects with the conditions that percentage>60 is First division,
percentage<60&>40 is second division, percentage<40 is third division.
25. Input basic pay and calculate total pay (basicpay+bonus) conditions are
Pay<1000 then bonus 10% if pay between 1000 to 3000 then bonus 9% if
Looping programs
Strings(52-56 )
52. Write a program to change the string from upper to lower case.
Arrays
Multidimensional arrays(66-72)
66.
Input the value of 3*3 matrices and display it input days of a week and
display it.
67. Write a program to add two matrices.
68. Write a program to subtract two matrices.
69. Write a program for matrix multiplication.
70. Write a program to find the sum of diagonal elements of a matrix.
71. Write a program to find the transpose of a given matrix.
72. WAP to find a specific word from string.
Functions(77-89)
ADD TWO NUMBERS USING FUNCTIONS
77 Without arguments without return
Pointers(90-92)
90.
Write a program to find largest among n numbers using pointers and
arrays.
91.
Write a program to swap two numbers using pointers.
92
Multidimensional arrays and pointers and WAP to add two matrices ,
passed as arguments (as ref) using pointers.
97 WAP that will generate a data file containing the list of customers and
their corresponding phone numbers. Use a structure variable to store the
name and telephone of each customer. Create a data file using a sample
list.
OTHER IMPORTANT PROGRAMS
98 Input 3 digits no print sum of its digits.
99 Input 3 digits no print reverse of it.
100 Print
1
12
123
1234
12345
Chapter 1
INTRODUCTION TO PROGRAMING LANGUAGES
Programming Languages
Programming languages are the languages used to make programs that can
be executed by the computer using compiler or interpreter. We can create
programs, application software, web sites etc with the help of these
programming languages. Programming language can be categorized
cate gorized as below.
Low Level Language.
Assembly Language.
High Level Language.
Low Level Language (Machine Language)
Machine Language is a language that a computer can understand, but it is
very difficult for the human beings to understand. Programs written in
machine language consist of machine instructions. Machine language consists
of strings of binary numbers (0, 1). Each microprocessor can have different
machine language.
Advantages:
1. Machine language instructions are directly executed, so there
is no compilation
compilation or translation needed, that’s why it is fast in
2. execution.
Machine language uses computer memory very well.
Disadvantages:
1. Machine language is a machine dependent.
2. It is very difficult to remember the codes.
3. Modification is difficult in machine language program.
4. High programming skills are required to develop programs in
machine language.
Assembly Language
In 1950s operation codes [opcodes] were developed. Assembler is used to
convert these codes into to machine language. Like it is difficult to remember
any code like(01010001 for add) instead of this binary code in assembly
Advantages:
1. Assembly language programs are easier to use than machine
language.
2. Error detection is possible and easy.
3. Modification is simple in assembly language program.
4. Less efforts are required as compared to machine language in
writing the program.
Disadvantages:
1. These languages are fully machine dependent language.
2. Good programming skills are required to develop a program in
assembly language.
HIGH-LEVEL LANGUAGE (HLL)
High level languages are very powerful and these are similar to English
language. C, C++, Java, Visual Basic etc are the examples of HLL.
High level
language Compiler
interpreter/ Machine
language
program program
Advantages:
1. HLL are easy to learn and understand.
2. It is very easy to write the program.
3. Mostly the syntax of all high level languages are similar.
4. Knowledge of hardware is not essential to write program.
5. Program written in HLL are easy to modify.
Disadvantages:
1. Compiler or interpreter is required to convert HLL into low level
l evel
language.
2. Due to conversion these are slower in speed.
3. Specific hardware and
software are required for some high level language.
Compiler And Interpreter
Compiler and interpreter both are used to convert the high-level
high -level language
program into the object code.
Interpreter:- Interpreter convert the pprogram
rogram of High level language into
Low level language line by line.
2) Extensibility:-
Extensibility :- A good programming language should be
extended to sub-program. It increases the readability of the language.
3) :- Programs written in a good language should be
Efficiency:-
Efficiency
efficient. That is, program should take less space & time to run
efficiently.
4) Better documentation :- A good programing language should
be easily understood by programmer. Coding should be precise and
logics should be upto mark.
5) :- A good programming should have a mechanism to
Flexibility:-
Flexibility
control the computers CPU, memory & registers.
6) errors:- A good programming language should have
Fewer errors:-
compilers & interpreters which can automatically detect syntax errors.
So these can be easily corrected by the programmer.
COMMON LANGUAGES
1) BASIC ( BEGINNERS ALL PURPOSE SYMBOLIC INSTRUCTION
CODE):- All purpose symbolic instruction ) It is designed in 1964 by
John George Kemeny and Thoman kurtic. It is easy for beginners,
provide error messasges, no need to understand hardware. Its based
on fortran-2nd + ALGOL.
2) ALGOL(( ALGORITHM C LANGUAGE) :- Developed in 1950. It is
ALGOL
the first language that implement nested functions.
3) (FORMULA TRANSLATOR):- It is developed for numeric
FORTRAN(FORMULA
FORTRAN
computation and scientific calculation and it is developed by IBM in
1950.
4) COBOL
COBOL:- :- Common Business-oriented language design for
business, finance administrative systems. Cobol 2002 also support
object-oriented programming.
5) LISP:-
LISP :- (List processing) It is used to implement lists that is a
major data structure developed in 1958.
7) BCPL:-(
BCPL: -( Basic combine programming language) It can
perform
pe rform task of many language ‘C’ is based on this language.
7) LOGO:-
LOGO :- It gives graphics. It is develop in 1968. It is used to create
simple programs that can contain simple graphics.
8) SQL (STRUCTURE QUERY LANGUAGE):- It is used in databases to
create database and access information from it.
C/C++ compilers
Turbo C++
Borland C++
Pelles C
Intel C++
VisualAge C++
Tiny 'C' Compiler
First-generation language
is given to the computer byisthe
theprogrammer
lo
lowest
west levelin
computer language.
binary form. Binary Information
instructions
are the same as on/off signals. The language consists of zeros and ones.
Second-generation Language
Assembly language was the second generation of computer language.
Assembly language consists of letters of the alphabet. This makes
programming much easier as compared to binary form.
Third-generation Language
These languages are similar to spoken English. Third-generation computer
languages are much easier than first two generations.
Fourth-generation Language
Chapter 2
BASIC OF 'C' LANGUAGE
Before Writing 'C' Program
Before starting programming in ‘C’ Language, it is better to learn some basic
concepts like:-
1. Important logics that will be used in common 'C' programs.
2. Character set of 'C' language.
3. Constants
4. Variables
5. Keywords
6. Data types
7. Operands
8. Operators
9. How to open 'C' Compiler.
10. Compile and run 'C' program
11. Open and save 'C' program.
12. Algorithms and Flow Charts.
1. Basic Logics [Formulas]: Some of the basic formulas that we will
1.
use in 'C' are:-
2.
2. Character set: A character represent alphabet, digit or special
symbol that we can use in 'C' language. In 'C' we can type mainly three
types of characters.
1) Alphabets :A to Z and a to z
2) Numbers: 0,1,2,3,4,5,6,7,8,9
3) Special Symbols : { } ” :
: ; [ ] ( ) + - * & ^ % < . ? , = !
# etc
3.
3. Constant: The value of a constant is fixed and we cannot change
the value of the constant. We use const keyword to declare constant in
'C' language.
constants:-
Types of c constants:-
'C' constants can be divided into two major
m ajor categories.
a) Primary constants
Integer constants, real constants, character constants.
b) Secondary constants
Array, pointers, structures, union, enum.
4.
4. Variables: The value of variable can be changed during the
program. Variables can be local or global.
Local variables: Local variables are defined with in the pair of braces or
or
between the body of the function. The scope of the variable is with in the
function.
Global variables: These variables are defined out side of all the
functions. And these variables can be used in any function with in the file
because the scope of these variables are global to the file.
Constant Variable
1) Constant value doesn’t 1) Variable vary during
change during execution of the program.
execution of the program.
2) It is fixed quantity. 2) It’s value can be changed.
changed.
3)e.g. z=2x+5y 3)e.g. z=2x+5y
here 2,5,are constants. here x,y are variables.
5. Keywords: Keywords are the reserved words with some specified
function. The meanings of keywords are already defined in 'C' compiler.
We
like cannot
if, for, use keywords
while, as variable
void, int, names.
float, do, In continue,
break, C there aregoto,
32 keywords
struct,
enum, double etc.
6.
6. Data types: The value stored in variable or constant depends
upon data type, or we can say Data types represent what type of data
will be stored in the variable . In 'C' language we have three basic
datatypes int (used
(used to store numbers without decimal), float (used
(used to
store numbers with or without decimal), char (used
(used to store alphanumeric
characters). Data types available in C are :-
8.
8. Operator: operators refer to symbols that represent a particular
operation to be performed on data. Types of operators are:-
Assignment operator : Assignment operators are used to assign the
values to a variable. Assignment operators are (+=,-=,/=,*= etc).
Arithmetic operator : These are used to perform arithmetic
calculation on the operands. Arithmetic operators are +,-,*,/,%.
Relational operator : Use to check relation between operands. E g.
>,<,<=,>= etc.
Logical operator: These operators are used to attach more than one
relational operator in one statement. These are &&(AND), ||(OR),
!(NOT).
Conditional operators: These are used when we want to execute the
statements according to the condition.
operators:Bitwise operators are special operators designed
Bitwise operators:Bitwise
to work on the bit level.
Bitwise Meaning
Operator
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ One’s complement
complement
9.
9. How to install c into your computer:-
1) First of all , find turboc .exe file.
2) Copy this file and paste it on c:drive.
3) Now, open DOS prompt.
4) Type cd\ and press enter.
5) C:\turboc.exe –d. It will extract all directories from turboc c to
your c drive.
10.
10. How to open 'C' Compiler.
If you are writing program in windows98, 2000,2003,XP then you can use
any compiler of 'C'. But if you use windows vista or window 7 then it is
better that you use 32-bit or 64-bit Compiler according to the operating
system.
Steps to open 'C' compiler
1. Select Run from start and type command or cmd in rrun un
box.
3. With these commands 'C' editor will open that look like
To run the program select run option from the run menu or Press Ctrl + F9
12. Open and save 'C' program.
12.
To open a file select open from file menu or press F3, and to save
select save form file menu or press F2,the extension of 'C' program is
.c
Steps to take C programs in printed form:
1) Go to c:\tc\bin and press enter.Right click on the file having
extension .c or .cpp and open it
i t with notepad.
2) Now go to file menu of notepad & click on print option.
3) The printed form of required C program will be in your hands.
Algorithms
Algorithms are the English like steps to solve a problem. It is the part of
software designing. Before creating a program or software we develop its
design using some tools like algorithms, DFDs, Flowcharts etc. Mainly we
follow following steps to design an algorithm.
Step 1. START //it represents beginning of the algorithm
Step 2. DECLARE //the variables used in algorithm are declared in this step.
Step 3. INPUT // here we input the values
Step 4. FORMULA// the required result is generated in this step.
Step 5. OUTPUT // display the result.
Step 6. STOP // end of algorithm
**We can use if else, goto ,loops etc according to requirement
Flowchart:-
Step 3: STOP
Flowchart
START
STOP
PRINT C
START
Q3. Write an algorithm and draw
STOP
flowchart to add, sub, mul, div
Declare A, B, SUM, SUB, MUL,
2 numbers. DIV
Algorithm
Step 1: START
Step 2: DECLARE A, B, ADD, SUB, INPUT A,B
MUL, DIV
Step 3: INPUT A, B
Step 4: ADD A+B ADD = A+B
Step 5: SUB A-B
Step 6: MUL A*B SUB = A-B
Step 7: DIV A/B
Step 8: PRINT “SUM=”,
PRINT “SUM=”, ADD
Step 9: PRINT “SUB=”, SUB MUL = A*B
Step 10: PRINT “MUL=”, MUL
Step 11: PRINT “DIV=”, DIV DIV = A/B
Step 12: STOP
PRINT “SUM=”, ADD
STOP
DECLARE A,B
INPUT : A, B
IF
A>B
PRINT: A IS
then
BIG
N
PRINT: A IS
BIG
Y
STOP
C
Tokens
Keywords Strings
Constants Identifiers
Operators Special
s
y
m
b
o
l
s
Chapter 3
START PROGRAMING IN 'C' LANGUAGE
As we discuss we can use various approaches to develop software. Today
languages are based on two main concepts Procedural Programming and
Object Oriented Programming. ‘C’ is procedural language and ‘C++, Java’ are
a re
Object Oriented languages. In procedural language functions are created to
perform various tasks. Functions can be inbuilt or user defined and in object
oriented language classes are created. Classes are the combination of
functions and data.
'C' language is a procedural language where every thing is done in the form
of functions. In 'C' language we have two main types of functions
1. Inbuilt
2. User defined functions.
declaration
Global Variable declaration
inbuilt functions like printf , scanf , getch etc.In C there are 24 header files.
Step1 Start
Step2 Print “hello world”
Step3 Stop
To write a program from algorithm, we step by step convert the steps into
program.
Algorithm Program
Step1 Start void main()
{
When we use inbuilt function in the program it is better to include header files
of that functions like printf function is define in stdio.h so we include this file
in our program. The program become like this.
We compile the program with alt+F9. It displays errors. After removing the
errors we can run the program using Ctrl+F9.Complier runs the program and
control come back to the editor screen, we can use Alt+F5 to view result.
same scope.
.Algorithm Program
Step1 Start void main()
{
Step2 declare a,b,c int a,b,c;
Step3 a=10 a=10;
Step4 b=20 b=20;
Step5 c=a+b c=a+b;
Step6 Print c printf(“%d”,c);
printf(“%d”,c);
Step7 Stop }
In printf we need format specifier to print value of the variable like we use
%d to print value of variable c. Some times we use getch() to avoid pressing
Alt+F5. and clrscr() function if we want to clear the screen. clrscr() function
should be used after the variable declaration.
#include<conio.h>
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
a=10;
b=20;
c=a+b;
printf("%d",c);
getch();
}
Output:- 30
If we write printf function like :- printf(“sum=%d”,
printf(“sum=%d”,c);
c);
Output:- sum=30
Write algorithm and program to swap two numbers
Step1 Start
Step2
Step3 declare
a=10 a,b,c
Step4 b=20
Step5 c=a
Step5 a=b
Step5 b=c
Step6 Print a
Step6 Print b
Step7 Stop
Algorithm Program
Step7 Stop }
#include<conio.h>
#include<stdio.h>
void main()
{
int a,b,c;
a=10;
b=20;
c=a;
a=b;
b=c;
printf("a=%d ",a);
printf("b=%d ",b);
getch();
}
declares
declares an
an identifier
identifier to be fixed
whose [not
value changeable].
can rightfully beThe volatile qualifier
changed.
#include<conio.h>
#include<stdio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character ");
scanf("%c",&ch);
printf("character=%c",ch);
getch();
}
Output:
Enter a character G
character =G
We can also assign a character without scanf function, but character
should be in single quotes like ‘a’ ‘F’ etc
#include<conio.h>
#include<stdio.h>
void main()
{
char ch;
clrscr();
ch='A';
printf("character=%c",ch);
getch();
}
Output:- character=A
Chapter 4
OPERATORS
Operators are the symbols that are used to perform various operations on
data, like arithmetic operations, comparison or logical operations etc.Operator
refers to a symbol that tells the computer to perform certain mathematical or
logical tasks on operands. Operators can be Unary and Binary. Unary
Operators work on one operand like –a, b++ etc and Binary operators
work on two operators like a+b, a*c etc.
C provides different types of operators as follow:-
1) Arithmetic operators
2) Logical operators
3) Assignment operators
4) Relational operators
5) Bit wise operators
6) Unary operators
7) sizeof operator
8) Comma operator
9) Conditional operator
These operators are performed on operands and operands are the variables
on which these operations are performed.
e.g x+y
In this x,y are operands and + is operator and x+y is called expression.
Multification *
Division /
/
Modulus %
a*b=36
a/b=2 (decimal ignored as it is an integer arithmetic)
a%b=1 (remainder)
b) Real arithmetic:- The Operators which are performed only on real
b)
operands, called real arithmetic. Real operands may include decimal or
exponential notation.
e.g a=9.0 and b=4.0
then a/b=9.0/4.0=2.250000
NOTE:-
NOTE :- The operation % cannot be used with real operands.
c) Mixed mode arithmetic:- It is the combination of real operand &
c)
integer operand. In this case if either
ei ther operand is of real type then result will
always be is a real no. e.g 25/10.0=2.5
whereas 25/10=2
2) Logical operators: - The logical operators && and || are used when we
2)
want to test more than one condition to make decisions. The result of logical
operator AND (&&) will be true only if both the conditions are true, whereas
the result of a logical operator OR (||) will be true if one or more conditions
are true. In other words, the result of a logical OR operation will be false only
if all conditions are false.
logical operators
NAME SYMBOL IN 'C'
D &&
OR ||
NOT !
LOGICAL OR (||)
OR (||) is a logical operator that will give result if minimum one of its
condition is true.
b<athe
It means is false
result of relational operators is returned as either true or false
i.e.1 or 0.
Operator Meaning
& Bit wise Logical AND
| Bit wise OR
^ Bit wise XOR
<< Left shift
>> Right shift
~ Complement
#include<stdio.h>
void main()
int n,m,and,or,com,rs,ls,xor;
n=11;
m=5;
and=n&m;
or=n|m;
xor=n^m;
com=~n;
ls=n<<2;
rs=n>>2;
printf("\n n&m=%d",and);
printf("\n n|m=%d",or);
printf("\n n^m=%d",xor);
printf(“\n
printf(“\n ~n=%d",com);
printf("\n rs>>2=%d",rs);
printf("\n ls<<2=%d",ls);
}
Output:-
n&m=1
n|m=15
n^m=14
n^m=14
~n=-12
rs>>2=2
ls<<2=4
1011
0101
0001 which is=1 so n&m=1
b. n|m
1011
0101
1111 which is=15 so n|m=15
c. n^m
1011
0101
1110 which is=14 so n^m=14
d. ~n
int a=5;
a++:
printf(“%d”,a);
printf(“%d”,a);
Output is 6 means ++ operator increase the value by 1.
Example
int a=5;
a--:
printf(“%d”,a);
printf(“%d”,a);
Output is 4 means -- operator decreases the value by 1.
Increment or Decrement operators are further two types: -
1) Pre increment operator/Pre Decrement operator
2) Post increment operator/post Decrement operator.
Both operators increment or decrement the variables but at different times.
The statement ++x increments x before using its value, while x++
increments x after its value has been used.
The x++ or x-- reads the value & store a copy of it at temporary location.
The computer increments or decrements the variables, & the temporary
copy is used in expression.
e.g.
int x,y;
x=5;
y=x++;
printf(“x=%d,y=%d\ n”,x,y);
n”,x,y);
o/p :-
x=6,y=5
Example of pre increment operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b;
b=++a;
printf(“\
printf(“\ na=%d”,a);
na=%d”,a);
printf(“\
printf(“\ nb=%d”,b);
nb=%d”,b);
getch();
}
output:- a=6
b=6
Example of post increment operator
#include<stdio.h>
#include<conio.h>
void
{ main()
int a=5,b;
b=a++;
printf(“\ na=%d”,a);
na=%d”,a);
printf(“\ nb=%d”,b);
nb=%d”,b);
getch();
}
output:- a=6
b=5
Example of pre decrement operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b;
b=--a;
printf(“\
printf(“ \ na=%d”,a);
na=%d”,a);
printf(“\ nb=%d”,b);
nb=%d”,b);
getch();
}
output:- a=4
b=4
Example of post decrement operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b;
b=a--;
printf(“\
printf(“ \ na=%d”,a);
na=%d”,a);
printf(“\ nb=%d”,b);
nb=%d”,b);
getch();
}
output:- a=4
b=5
7) sizeof operator: - The sizeof operator returns the size , in bytes
7)
, of the given operand. A sizeof operator is a unary operator that returns
the number of bytes required to store a variable or a data type.
Syntax is:-
sizeof(datatype or variable)
Example:-
sizeof (int)
Output
size of int =2 bytes
size of float=4 bytes
size of char=1 byte
8) Comma operator: - The comma operator (,) is used to declare
8) dec lare more
than one variable in single line. It is also known as separater as it separates
one variable name from other.
Example
int a,b,c;
9) Ternary operator: - Ternary operator is also known as conditional
9)
operator or immediate if. These are ? and : ternary operator. An operator that
takes three statements to work. The syntax of this operator is
<Condition>? <Expression1>: <expression2>
The <condition> is evaluated first. If the result is true then expression 1 is
executed, otherwise expression 2 is executed.
If <condition> is false ,expression3 is evaluated & its value becomes the
result of expression.
e.g. if a=15,b=5
x=(a>b)?a:b
The above example means that if a is greater than b then a will be assigned
to x, otherwise b will be assigned to x.
It can be achieved using if-else statements as follows:
if(a>b)
x=a;
else
x=b;
The detail of if-else is discussed in next chapter.
Note:The
Note:
Operators
Associativity
([-. Left to right
! - ++ -{- + * & (type-cast) sizeof Right to left
* /% Left to right
+ - Left to right
<< >> Left to right
< <= > >= Left to right
== != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Left to right
= += -= *= /= %= Right to left
&= ^= |= <<= >>= Left to right
Important Questions[Short]
1. Define relational operators.
2. Explain Advance assignment operator.
3. Define Ternary operators.
4. Define sizeof operator.
5. Write difference between logical AND and OR operators.
6. Write difference between ++I and I++.
Important Questions[Long]
1. Explain Bitwise operators.
2. Explain increment and decrement operators with example.
3. Write precedence of the operators.
Chapter 5
CONDITION CONTROL STATEMENTS
Control Statements
Normally program is executed in the sequential order, and when we want to
change the normal execution of the program then we need to use control
statements or we can say control statements are used to change the normal
execution of the program.
Control statements are mainly divided into three types
1. Condition control statements
2. looping or iterative statements
3. branching statements
1.
1. Condition control statements
These are used when we want to execute the statement or block of
statements according to some condition. Conditional execution can be
controlled by :-
a. if
b. if else
c. if else if
d. Nested if
e. switch case
f. Conditional operator or ternary operator
If Statement
It is the basic condition control statement. When we have single
condition then we mostly use it. The if statement allows a programmer
to test the value of a conditional expression and to select or reject the
execution of the statement or block of statements depending on this
value.
Syntax of if:
if (condition)
Expression {
false
statement1;
true statement2;
1. Write an algorithm and program to Input age and print “you
1.
are child” if age <10.
age <10.
Algorithm Program
Step1 Start void main()
{
Step2 declare age int age;
Step3 Print “Enter
“Enter age” printf(“Enter age”);
printf(“Enter age”);
Step4 Input age scanf(“%d”,&age);
scanf(“%d”,&age);
Step5 if age< 10 if(age<10)
then {
Print “You are child” printf(“You are child”);
child”);
End }
Step7 Stop }
IF ELSE
If is a single selection structure and if else is a double-selection structure
because it selects from two different actions. If else is one of the most
commonly used control statement.
true false
Expression
Statement1 Statement2
Syntax
if (Expression)
statement1
else
statement2
If Expression is true then it executes statement1
st atement1 otherwise it executes
statement2
Write an algorithm and program to Input two number and print
greatest from them.
Algorithm Program
Step1 Start void main()
{
Step2 declare a,b int a,b;
Step3 Print “Enter value of a” printf(“Enter value of a”);
a”);
Step4 Input a scanf(“%d”,&a);
scanf(“%d”,&a);
Step5 Print “Enter value of b” printf(“Enter value of b”);
b”);
Step6 Input b scanf(“%d”,&b);
scanf(“%d”,&b);
Step5 if a> b if(a>b)
begin {
Print “a is big” printf(“a is big”);
big”);
End }
Else else
Begin {
Print “b is big” printf(“b is big”);
big”);
End }
Step7 Stop }
Output:-
Enter value of a 20
Enter value of b 10
a is big
In this example if a is greater than b then first block is executed and if b>a
then second block will execute else ifi f none of the above conditions are true
then else part will execute. If –else-if is faster than multiple if block because
in this if first block is executed then all the other blocks are ignored by the
compiler.
Nested if
We can write if statement within the scope of another if or else block, it is
known as nested if.
Syntax of nested if:
if (condition)
{
if (condition)
{
do this;
}
else
{
do this;
and this;
}
}
else
{
do this;
}
} }
getch(); }
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter the value of a");
scanf("%d",&a);
printf("enter the value of b");
scanf("%d",&b);
printf("enter the value of c");
scanf("%d",&c);
if(a>b)
{
if(a>c)
{
printf("a is big");
}
else
{
printf(“c is big”);
big”);
}
}
else
{
if(b>c)
{
printf("b is big");
}
else
{
printf(“c is big”);
big”);
}
}}
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b;
clrscr();
printf("enter the value of a");
scanf("%d",&a);
printf("enter the value of b");
scanf("%d",&b);
(a>b)?printf("a is big"):printf(" b is big");
getch();
}
Nested ternary operators.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter the value of a");
scanf("%d",&a);
printf("enter the value of b");
scanf("%d",&b);
printf("enter the value of c");
scanf("%d",&c);
(a>b&&a>c)?printf("a is big"):(b>c)? printf(" b is big"):printf(“c is big”);
getch();
}
Switch statement
When we have multiple if statements then we can use switch case statement.
s tatement.
The variable used in switch is known as switch variable. The variable in the
switch statement can be of int or char type only. The switch statement can
also contain the default statements that will be executed if none of the case
is executed, default is optional.
syntax of Switch
switch (expression)
{
case 1:
...block of statements1...
break;
case 2:
...block of statements2...
break;
-----------------
-----------------
-----------------
default:
...block of statements for default..
break;
}
#include<stdio.h>
#include<conio.h>
void main( )
{
char c;
clrscr();
printf("enter the value of c");
scanf("%c",&c);
if(c==’r’)
if(c==’r’)
{
printf("colour is red");
}
else if(c==’b’)
if(c==’b’)
{
printf("colour is blue");
}
else if(c==’g’)
if(c==’g’)
{
printf("colour is green");
}
else
{
printf("colour is white");
}
}
break;
case ‘b’:
‘b’:
printf("colour is blue");
break;
case ‘g’:
‘g’:
printf("colour is green");
break;
default:
printf("colour is red");
}
}
Applications of switch:
1) It makes program easy to read and understand.
2) It is the replacement of multiple if statements.
s tatements.
3) Whole switch block is act like a single block.
Limitations of switch:
1) We can only use int and char type data.
2) We can not write relational operators in case.
Like case > 10 is wrong.
fflush(stdin);
scanf(“%c”,&ch);
switch(ch)
{
case ‘a’:
c=a+b;
printf(“\
printf(“\ naddition=%d”,c);
naddition=%d”,c);
break;
case ‘s’:
c=a-b;
printf(“\
printf(“\ nsubtraction=%d”,c);
nsubtraction=%d”,c);
break;
case ‘d’:
c=a/b;
printf(“\
printf(“\ ndivision=%d”,c);
ndivision=%d”,c);
break;
default:
printf(“\
printf(“\ nwrong
nwrong key pressed”);
pressed”);
}
getch();
}
Chapter 6
LOOPING AND BRANCHING STATEMENTS
Loops are used to execute statement or block of statements more than once.
In other words, Loop is defined as continuity. In simple language, it means to
do a particular task again and again till a particular condition is true or
satisfied.
For example
A person is given a task to go upstairs or downstairs for five no. of times
continuously. These processes of going up and down again and again are
known as loop. In a simple way we can say that a particular work or job is
done repeatedly.
Use of loops in programming is to calculate the result or percentage of 100,000
students of Punjab school education board. In this case, we have to calculate
the percentage of each student individually. To do this, we have to apply the
same formula again and again for each student. This process is very time
consuming, so to save memory space as well as time, loop is used in the
database. We can apply formula with the help of loop in one single line
according given condition.
Thus a loop is a part of program through which the control moves several
times during the execution of the program. The part which is executed again
and again is known as body of the loop. During the execution of loop,
whenever control falls to end of the body of the loop, it again jumps to the
starting point of body of the loop. This continues till a condition is satisfied
and control comes out of the loop if the condition is not satisfied.
Increment/decrement;
}
There will be no semicolon at the end of the line containing the keyword
while in while loop.
Algorithm
Step 1: START
Declare
Step 2: DECLARE A
Step 3: A=1 A=1
Step 4: IF A<=10 GOTO STEP 5
ELSE GOTO STEP 7
Step 5: PRINT “HELLO” N0
IF
Step 6: A=A+1 GOTO STEP 4 A<=10
Step 7: STOP
Or
Algorithm yes
Step 1: START
Step
Step 2:
3: DECLARE
A=1 A PRINT”HELLO”
Write A Program To
T o Print Series 2,4,8,10 ---- 100
#include<stdio.h>
#include<conio.h>
void main()
{
int a=2;
clrscr();
while(a<=100)
{
printf(“%d”,a);
a=a*2;
}
getch();
}
Step
Step1:2:START
DECLARE i,num
Step 3: PRINT “Enter the ending point number”
Step 4: INPUT num
Step 5: i=1
Step 6: PRINT “hello”
Step 7: i=i+1
Step 8: if(i<=num) then GOTO STEP 6 else GOTO STEP 9
Step 9: STOP
3. FOR: - In for loop the initialization, condition and increment or decrement
3.
can be done in one line. It executes the statements till the condition is true.
Mostly this loop is used in complex programming.
Syntax
for
{ (initialization; condition; increment/decrement)
Statement;
Statement;
}
1) First initialize the variable.
2) After initialization, condition is checked. If condition is true then
statement is executed.
3) After that increment or decrement the variable according to
condition.
Write a program to find sum of 1 to 10 numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,s=0;
clrscr();
for(a=1;a<=10;a=a+1)
{
s=s+a;
}
printf(“%d”,s);
getch();
}
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c=c+1;
}
}
printf("count= %d",c);
getch();
}
void main()
int n,i,s=0;
clrscr();
printf("enter a no");
scanf("%d",&n); //let n=1234
while(n>0)
i=n%10; //4
s=s+i; //0+4=4 4+3=7 7+2=9 9+1=10
n=n/10; //123 12
#include<stdio.h>
void main()
int n,i,s=0;
clrscr();
printf("enter a no");
scanf("%d",&n); // let n=1234
while(n>0)
i=n%10; //i=4 3
s=s*10+i; //s=0*10+4
//s=0*10+4=44*10+3=43
=44*10+3=4343*10+2=432
43*10+2=432432*10+1=43
432*10+1=432
2
n=n/10;
1. NESTED LOOP: -Nested loop means nesting or loops means within
loop. In nested loop the first loop is called outer loop & second loop is
called inner loop. In this the condition of outer loopis true then the
condition of inner loop is checked. If it is true then inner loop will execute.
execute .
The inner loop would act as a part of the body for the outer loop.
Therefore, execution of inner loop will depend on the execution of the
outer loop.
Syntax
for (initialization; condition; increment/decrement)
increment/decrement) //outer
//outer
Loop
{
for (initialization; condition; increment/decrement)
// Inner
loop
{
Statement;
}
}
If
if the
the condition
condition of
ofouter
innerloop
loopis is
true then
true control
then will goto
executes the the inner loop
statement. If and
the
condition of outer loop is false the control doesn’t go into in the inner
inner loop.
loop.
Write a program to print :-
12345
12345
12345
12345
12345
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
printf(“%d”,j);
printf(“%d”,j);
}
printf(“\ n”);
n”);
}
getch(); }
In above program we have used nested loop. Ist loop is outer loop and 2 nd
loop is inner loop. If the outer loop is true then control goes to the inner loop
otherwise exit the control in outer loop. In simple meaning outer loop act as
no of rows and inner as no of column.
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,i);
printf(“%d”,i);
}
printf(“\
printf(“\ n”);
n”);
}
getch();
}
for(j=1;j<=i;j++)
{
printf(“9”);
printf(“9”);
}
printf(“\ n”);
n”);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,s=0,m;
clrscr();
for(m=1;m<=1000;m++)
{
n=m;
s=0;
while(n>0)
{
i=n%10;
s=s*10+i;
n=n/10;
}
if(s==m)
printf(" %d",s);
}
getch();
}
Branching Statements
There are another kind of control statements that can change the execution
of loop or execution of the program. Branching statements are further divided
into three types.
a.
a. Break
b.
b. Continue
c.
c. goto
Break: - Break statement is used to exit from the loop or switch statement.
Whenever break statement is encountered the rest of the statements inside
the loop are ignored and the control go to the next statements
s tatements after the loop.
It can also be used with a while , a do while , a for or a switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
printf("\n% d",i);
}
getch();
}
output
1
2
3
4
E xample
ample continu
conti nue
e state
statem
ment
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrcsr();
for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf(“ %d ”,i);
”,i);
}
getch();
}
Output: 1 2 3 4 6 7 8 9 10
Goto: - The goto statement is control statement that causes the control to
jump to a different location in the program with or without checking any
condition . It is always used with the label. It increase the readable
complexity of the program so programmers avoid to use this. The goto
statement can only be used within the body of a function definition.
There are two types of goto:-
1) Unconditional jump
2) Conditional jump
Output
One
Two
Three
Seven
Eight
2.
2. Jump: In this control is transferred from one
Conditional Jump:
statement to another according to the condition.
EXAMPLE conditional GOTO STATEMENT
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
Abc:
printf(“Enter no greater than 10”);
scanf(“%d”,&a);
scanf(“%d”,&a);
if(a<=10)
goto Abc;
printf(“You enter number greater than 10”);
getch();
}
in this program control goes back to Abc label until user not enter number
greater than 10.
Important Questions[Short]
1. What do you mean by loop?
2. What are the limitations of goto statement?
3. Write advantages of for loop over while and do-while.
Important Questions[Long]
1. Explain various types of loops in 'C' language .
2. Write difference between break and continue.
3. Write difference between while and do-while.
4. What are various jump statements in 'C' language .
** Perform Programs from 27 to 51 from program list
Chapter 7
ARRAYS AND STRINGS
Arrays are group of similar data types. It’s used to store a large amount of
data. The array elements are stored in contiguous memory locations. In other
words, if an array is declared to be of an int type, it can’t contain elements
that are not of int type.
How to declare an Array:
DataType variablename[size]
Example:- int ary[5];
10 20 30 40 50
ary[0] ary[1] ary[2] ary[3] ary[4]
In the above program ary is variable name which hold the 5 elements which
have a same name, same data type but with different memory locations. As
the memory is allocated sequentially so that data can be easily accessed by
increment or decrement by single variable. Arrays always start with index
value zero.
Advantages of arrays
1. Array is the simplest data structure.
2. It is easy to create.
3. We can use one name for similar identifier.
4. Arrays use reference type so we need not to use return statement.
Limitations
1. Array may require large amount of contiguous memory, which is not
available sometimes.
2. B
Bound
ound checking is not done by 'C' compiler. Means in ary[5] the index value
should be between 0 to 4 but if we write ary[7],ary[34] etc compiler does
not show any error and display garbage value.
3. Overflow condition may occur in array if we want to store more values
then its size.
ARRAY
Array is TYPES
two types
1) One dimensional array
2) Multidimensional array
1) One dimension array:- A list of items have only one subscript and such
a list is called one dimensional array.
Declaration of an array.
int a[5];
In the above example we defined an array a [5]. Here a iis s a variable name.
Data type of a is integer and 5 is the size of an array. Size is always written
in subscript []. This means that it can store only five elements. Index of a is
start from 0 to 4.
Initialization
declare it. array:- we can also assign values to an array when we
of an array:-
int a[]={1,2,3,4,5};
compiler automatically sets the size of the array like in this case size of a is
5 and it requires 10bytes of memory[2 for each int]
int a[10]={1,2,3,4,5,6,7,8,9,10};
In this we assign values to the ten elements of a. We can access array
elements with its index, for example, if we want to print 5 th element from the
list we use a[4].
Write a program to print five elements of an array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={1,2,3,4,5};
clrscr();
printf(“%d”,a[0]);
printf(“%d”,a[0]);
printf(“%d”,a[1]);
printf(“%d”,a[1]);
printf(“%d”,a[2]);
printf(“%d”,a[2]);
printf(“%d”,a[3]);
printf(“%d”,a[3]);
printf(“%d”,a[4]);
getch();
}
In this program 1 is store at location 0,2 at location 1 similarly others.
When we print a[0] it will display 1.
Write a program to input and print five elements using array.
**it is always helpful to use loop in array
#include<stdio.h>
void main()
int a[5],i;
clrscr();
for(i=0;i<=4;i++) /*it will execute scanf statement 5 times and
value in array*/
printf(“enter array
array element=”);
scanf(“%d”,&a[i]);
scanf(“%d”,&a[i]);
for(i=0;i<=4;i++)
printf(“ %d”,a[i]);
%d”,a[i]);
getch();
2) Multidimensional
Multidimensional Array: - Array in 'C' can have more than one
dimension. An array with two dimensions or more is known as
for(i=0;i<=4;i++)
for(j=0;j<=4;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf(“ %d”,c[i][j]);
%d”,c[i][j]);
}
printf(“\
printf(“\ n”);
n”);
}
getch();
}
a b c
1 2 3 4 5 1 1 1 1 1 2 3 4 5 6
Write a 1 2 3 4 5 1 1 1 1 1 program to 2 3 4 5 6
multiply two
1 2 3 4 5 1 1 1 1 1 2 3 4 5 6
matrices. 1 1 1 1 1
1 2 3 4 5 2 3 4 5 6
1 2 3 4 5 1 1 1 1 1 2 3 4 5 6
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5] , b[5][5],c[5][5],i,j,k;
clrscr();
printf(“enter 1st matrix”);
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
scanf(“%d”,&a[i][j]);
scanf(“%d”,&a[i][j]);
}
}
printf(“enter 2nd matrix”);
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
scanf(“%d”,&b[i][j]);
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
c[i][j]=0;
for(k=0;k<=4;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
printf(“%d”,c[i][j]);
printf(“%d”,c[i][j]);
}
printf(“\
printf(“\ n”);
n”);
}
getch(); }
Write a program to print transpose of matrix.
Transpose means converting the rows into column;
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j;
clrscr();
printf(“enter array matrix”);
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
scanf(“%d”,&a[i][j]);
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<=4;i++)
{
for(j=0;j<=4;j++)
{
printf(“ %d”,a[j][i]);
%d”,a[j][i]);
}
printf(“\
printf(“\ n”);
n”);
}
getch();
}
A B
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15 1 5 9 13 17
13
16 17 18 19 20
2 6 10 14 18
14
array:- eg int
3-Dimensonal array:- 3 7 11 15 19
15 A[4][5][3]. In this
we can store total 4*5*3=60 4 8 12 16 20
16 elements and size
of A is 120 bytes.
Write a program of 3-D Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][5][4],i,j,k;
clrscr();
printf(“enter array matrix”);
for(i=0;i<=2;i++)
{
for(j=0;j<=4;j++)
{
for(k=0;k<=3;k++)
{
scanf(“%d”,&a[i][j][k]);
scanf(“%d”,&a[i][j][k]);
}
}
}
for(i=0;i<=2;i++)
{
for(j=0;j<=4;j++)
{
for(k=0;k<=3;k++)
{
printf(“%d”,a[j][i][k]);
printf(“%d”,a[j][i][k]);
}
}
}
getch();
}
String
C language does not provide any data type in which we can represent
collection of character. So if we want to do this we use character array that is
called string. As we can store more than one element in integer or float array,
similarly we can store more than one character in character array. Group of
characters is also known as String.
A string is a one dimensional
di mensional array of characters terminated by a NULL(‘\
NULL(‘ \ 0’).
0’).
For example,
char name[20]={‘P’,’R’,’A’,’T’,’H’,’A’,’M’};
name[20]={‘P’,’R’,’A’,’T’,’H’,’A’,’M’};
or
char name[20]={“PRATHAM”};
name[20]={“PRATHAM”};
The size of name is 20 bytes(1 byte for 1 char) and we use only first three
bytes to store “PRATHAM” after this we have 13 1 3 bytes left that contain garbage
value. But when we print it, it display first three characters only because
compiler place NULL also represented as ‘\ ‘\ 0’
0’ at the end of the string, so when
compiler print the string it print up to NULL character. We can input and print
string using %s format specifier in scanf and
a nd printf functions. We can also use
gets to input a string and puts to print a string.
Write a program to input and print a string.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch[20];
clrscr();
printf("Enter
printf("Enter name ");
scanf("%s",&ch);
scanf("%s" ,&ch); // or
or we can use gets(ch);
printf("Name=%s",ch);
getch();
}
String library functions are the functions, which are used regularly and
stored in library file and whenever these functions are needed , you need to
include the required header file in your program like as,
#include<string.h>
There are 7 inbuilt functions to perform different operations on strings.
1.. strlen: This function is used tto o count the characters in a string.
It calculates the length of the string.
Syntax:
strlen(array variable);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[20];
int i;
clrscr();
printf(“Enter string “);
scanf(“%s”,&s1);
i=strlen(s1);
printf(“Length=%d”,i);
getch();
}
2.
2. strcpy: This function copies the contents of one string into
another string.
Syntax
strcpy(target,source);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
clrscr();
printf(“Enter string “);
scanf(“%s”,&s1);
strcpy(s2,s1);
printf(“string =%s ”,s2);
getch();
}
3.
3. strcat: This function is used to concatenate the source string
at the end of the target string.
Syntax
strcat(target,sourcetoadd);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
int i;
clrscr();
printf(“Enter string “);
scanf(“%s”,&s1);
printf(“Enter string “);
scanf(“%s”,&s2);
strcat(s2,s1);
printf(“ concatenated string =%s ”,s2);
getch();
}
4.
4. strcmp: This function compares two strings to find out whether
they are same or different. The two strings are compared character by
character until there is a mismatch or end of the string. This function
returns 0 if both the strings are identical.
Syntax
Strcmp(string1,string2);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
int i;
clrscr();
printf(“Enter string “);
scanf(“%s”,&s1);
printf(“Enter string “);
scanf(“%s”,&s2);
i=strcmp(s2,s1);
if(i==0)
printf(“ Both strings are same”);
else
printf(“ Strings are not same”);
printf(“
getch();
}
5. strrev() : - String reverse function is used to reverse the
string. This function also contain a single argument
6.
6. strupr() : - String upper case is used to convert the string in to
upper case or in capital letter. This function
f unction contains single argument.
7.
7. strlwr() : - String lower case is used to convert the string into
lower case or in small letter. This function
functi on contains single argument.
atoi()[define in stdlib header file: This function comes under <stdlib.h>
header file. This function convert numeric string into integer
Syntax
int atoi(string);
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char s1[20];
int i;
clrscr();
printf(“Enter string “);
scanf(“%s”,&s1);
i=atoi(s1);
printf(“ i=%d”,i);
getch();
}
String can also be accessed as array like we can create programs without
using string functions.
JEEVANOPADHII
JEEVANOPADH Walia Enclave Opp Punjabi Univ
Patiala.
Patiala.
3058 Urban Estate Phase 2 Patiala
Patiala
Chapter 8
FUNCTIONS
Functions are the blocks of C programs which perform the specifc task.
Functions are used to divide the long program into sub program. In general,
a function is a block of code that performs one or more actions. Functions are
called by other functions. A program in the C language consists of several
functions. One such function we use is the main () function. Every function
has a name. The name of the function ends with a pair of parenthesis. This
parenthesis may or may not contain any thing. Whatever is inside the
parenthesis is known as the arguments of the function.
While defining function you must know these things: -
1. Function name.
2. Function return type (if there is no return then use void)
3. Function argument( if there is no argument here also use void).
Syntax to define a function:
<Return type> <function name>(<arguments>);
Example: -
void show();
Why we use function: -
1. Functions are used to find the errors in the program.
2. Functions are used for reusability.
3. It decreases the cost of the software.
4. It increases the efficiency.
5. It makes the programming simple.
6. It reduces the complexity of the program.
Types of Functions
There are two types of functions. First are known as built in functions and
second are the user defined functions.
1. Built in functions:
functions: - Built in functions are those functions, which
are provided to us by the programming language. But before
be fore using these
functions we have to include some header files like,
<stdio.h> which are provided to us by the various input output related
functions like printf() and scanf() function. Others are string handling
functions, mathematical functions which are stored in
<string.h> and <math.h> header file respectively.
Math Functions
Some examples of Math functions
Basic Math functions are sqrt() ,pow(), cos(), tan() and sin() etc.
1. sqrt ():- This function returns
returns the square root of a number. This
function accepts a single argument. As shown in the syntax and example
ex ample
given below: -
The syntax for the sqrt() function is:-
# include <math.h>
int sqrt(int h);
2.
2. User defined Functions: - These functions are defined by the
user are according to their requirement, known as User define functions.
User defined functions have four types: -
a)
a) Without Return Without Arguments
b) Without Return with Arguments
b)
c)
c) With Return Without Argument
d) With Return With Argument
d)
For creating user defined functions we have to follow three basic
steps. These are given below: -
a) Function Declaration / Function Prototyping
a)
b) Function Definition
b)
c) Function Calling
c)
1. Without Return Without Argument: - This is the first type of user
1.
define function and also known as no return no argument. No return means
that function start with ‘void’ keyword. It tells the compiler that the
function cannot return any value. No arguments mean we cannot pass
anything from the calling function to called function. It means we can leave
leav e
the parentheses blank. In C, the declaration of the show () function can be
something like this:
Void show();
We can also write it as;
void show(void);
Note that the keyword ‘void’ is used in the declaration to indicate to the
compiler that no argument is passed to the function. The compiler will produce
an error message if an argument is passed to show () function later in a
program when this function is called.
Example1.WAP to add and subtract two numbers using function with
no return no argument.
As show in the Example: -
#include<stdio.h>
clrscr();
sum(); //Function calling
sub();
getch();
int a,b,c;
printf(“enter first number”);
scanf(“%d”,&a);
scanf(“%d”,&a);
printf(“enter second number”);
scanf(“%d”,&b);
scanf(“%d”,&b);
c=a+b;
printf(“sum=%d”,c);
printf(“sum=%d”,c);
int a,b,c;
printf(“enter first number”);
scanf(“%d”,&a);
scanf(“%d”,&a);
printf(“enter second number”);
scanf(“%d”,&b);
scanf(“%d”,&b);
c=a-b;
2. Without Return with argument:- This is the second type of user
2.
define functions. This function starts with void keyword, which tells the
compiler that function hasn’t any return type. It can’t return any thing to
its calling program. But with argument means we must pass information to
the calling function. In this we should declare variables inside the
parentheses we cannot leave the parentheses blank. The argument of a
int a;
void sqr(int n)
int m;
printf(“\n
printf(“\n the square=%d”,m);
square=%d”,m);
void cube(int n)
int m;
m=n*n*n;
Local variables: - Local variables are those variables, which are declared
inside a block or function. These variables
v ariables are accessible only within the block
and are passed as argument into the function or declared inside the function.
These are also known as function level variable because they are accessible
only within the function.
Global variables: - Global variables are those variables, which are declared
outside the block or function. These are known as global variables. Which is
accessible by each block of the program.
3.
3. With return without Argument: - Return type functions are
those functions, which return a value to the calling function. These
functions start with a specific data type in place of void keyword. These
type of functions use return keyword to send the data back to the calling
function.
As shown in the example:-
Example 3. WAP to find the factorial of a given number using
function with return type.
#include<stdio.h>
int f;
int a,b=1,n;
printf(“enter any number”);
scanf(“%d”,&n);
for(a=1;a<=n;a++)
b=b*a;
return b;
4.
4. With return with argument: - This function contains argument
and also return the value to its calling function, as show in the given
example :.
void main()
int a,b;
clrscr();
printf(“please enter any number”);
scanf(“%d”,&a);
scanf(“%d”,&a);
b=reverse(a); // Function calling
printf(“\
printf(“\ n Reverse of a number=%d”,b);
getch();
int r,s=0;
{
r=n%10;
s=s*10+r;
n=n/10;
return s; }
Recursive Functions
Recursive functions are those functions, which call itself again and again.
Normally function is called by the other function, but in recursive function it
call itself repeatedly. This process known as recursion, as shown in the
example
Examplebelow:
. WAP to find the factorial of a given number using recursion.
#include<stdio.h>
#include<conio.h>
int fact(int n);
void main()
{
int n,f;
clrscr();
printf(“enter any number”);
scanf(“%d”,&n);
scanf(“%d”,&n);
f=fact(n);
printf(“factorial=%d”,f);
getch();
}
int fact(int n)
{
if(a==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
#include<stdio.h>
#include<conio.h>
int fibo(int a,int b);
void main()
{
clrscr();
fibo(0,1);
getch();
}
int fibo(int a,int b)
{
printf(“%d”,a);
if(a>100)
{
return 0;
}
fibo(b,a+b);
}
Call by Value
In C language by default, the arguments
a rguments are passed to the function by value.
It means the actual arguments copy their value into the formal arguments. In
call by value, we can pass the value. If any change is done into the formal
arguments, it doesn’t affect the actual arguments because both the arguments
use the different memory location.
#include<stdio.h>
#include<conio.h>
void show(int a); //declaring the function (a is our formal
argument)
void main()
{
int x;
clrscr();
printf(“enter any number”);
scanf(“%d”,&x);
scanf(“%d”,&x);
show(x); //calling the function
function ( x is our actual arguments)
printf(“\
printf(“\ n now value of x=%d”,x);
getch();
}
void show(int a) // function
function definition
definition ( a is our
our formal
argument)
{
a=a+1;
printf(“\
printf(“\ n the value of a=%d”,a);
a=%d”,a);
}
Output
Enter any Number = 5
The value of a = 6
Now value of x = 5
Call by reference
In call by reference we can pass the address of a variable in place of value. It
means we can pass the address of actual argument to the formal argument.
If any change is done in to the formal arguments ,it also affects the actual
arguments, because the address of the actual arguments are passed to the
formal arguments .In call by reference, we can pass pointer variable as formal
arguments.
As show in the example:-
#include<stdio.h>
#include<conio.h>
void show(int *a); //declaring the function (a is our
formal argument)
void main()
{
int x;
clrscr();
printf(“enter any number”);
scanf(“%d”,&x);
scanf(“%d”,&x);
show(&x); ///calling the function ( x is our actual
arguments)
printf(“\
printf(“\ n now value of x=%d”,x);
getch();
}
void show(int *a)// function definition ( a is our formal
argument)
{
*a=*a+1;
printf(“\
printf(“\ n the value of a=%d”,*a);
a=%d”,*a);
}
Output
Enter any Number = 5
The value of a = 6
Now value of x = 6
void
void show(int
main() a[]); //Parameter Array Type
{
int x[5],i;
clrscr();
for(i=0;i<5;i++)
{
printf(“enter any number”);
scanf(“%d”,&x[i]);
scanf(“%d”,&x[i]);
}
show(x);
getch();
}
void show(int a[])
{
int i;
for(i=0;i<5;i++)
{
printf(“\
printf(“ \ n%d”,a[i]);
n%d”,a[i]);
}
}
Passing structure as argument into the function
We can also pass structure as an argument into the function same as any
other variable. As shown in the example:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll,marks;
};
void show(struct student);
void main()
{
struct student s;
clrscr();
printf("enter student name");
scanf("%s",&s.name);
printf("enter student roll number");
scanf("%d",&s.roll);
printf("enter student marks");
scanf("%d",&s.marks);
show(s);
getch();
}
void show(struct student s)
{
printf("\nstudent name=%s",s.name);
printf("\nstudent roll=%d",s.roll);
printf("\nstudent marks=%d",s.marks);
}
Nested Function
Nested function means a function inside a function. But C does not allow
nested functions. But we can call one function into another function. It is also
known as nested function. As shown in the example:
#include<stdio.h>
#include<conio.h>
void sum(int a,int b);
void input(int a,int b);
void input(int a,int b)
{
sum(a,b);
}
void sum(int a,int b)
{
int c;
c=a+b;
printf(“the sum=%d”,c);
sum=%d”,c);
}
void main()
{
int x,y;
clrscr();
Chapter 9
STORAGE CLASSES
Storage classes tell us about three things.
1. Storage classes tell us about the memory. It means a variable
uses which type of memory. It uses RAM or any other memory (CPU
Memory).
2. Storage classes tells us about the scope of variable.The scope of
a variable is defined as the area of program in which it is accessible.
3. Storage classes tells us about the default value
v alue of the variable.
There are four types of storage classes.
1.
1. Auto
2.
2. Static
3.
3. External
4.
4. Register
1. Auto: - Auto means automatically. It is the default scope of variables
1.
and they are declared with or without auto keyword, belong to auto storage
class. Auto variable are active in the block in which they are declared. Block
means statements inside the braces ({}).
The scope of auto variable is limited. It means they are local
variable. They can access within the block where they are declared.
The auto storage class variable uses primary memory for storing
data. It means RAM.
The default value of auto storage class is garbage.
For E.g :-
void main( )
{
auto int a,b;
int c;
clrscr( );
printf(“Enter two numbers=”);
scanf(“%d%d”,&a,&b);
scanf(“%d%d”,&a,&b);
c = a + b;
printf(“Sum=%d”,c);
getch( );
}
Note: - As shown above a,b and c all are belong to the auto storage
class .
2) variable: - Static variable are those variable, which start
Static variable:
with static keyword. Static variables retain their values through out the
execution
use primaryof memory
the program. Their initial
for storing value is
data. Static zero. Static
variables variable
are also also
active in
the block in which they are declar
declared,
ed, means the scope of variable is
Output :- 0
1
2
3) Extern variable: - Extern variable are those variables, which are,
declared outside of the block/main. This variable can be accessible by
each block of the program. They are known as global variables. These
variables are declared with extern keyword. Its initial value is zero. They
consider as local variable but work as global variables. They also use a
primary memory (RAM) for storing a data.E.g :-
#include<stdio.h>
#include<conio.h>
void show();
void main( )
{
extern int a;
clrscr( );
printf(“\n
printf(“ \n the value of a=%d”,a);
show( );
a = a + 10;
printf(“\
printf(“ \ nNow
nNow the value of a=%d”,a);
getch( );
}
void show( )
{
extern int a;
a=a + 5;
printf(“\
printf(“ \ nThe
nThe value of a=%d”,a);
a=%d”,a);
}
Output :- 0
5
15
4) -Register variable are those variable, which
Register variable: -Register
start with register keyword. We can use register keyword to increase the
speed of program. The Resister variable uses the CPU memory. Their
default value is garbage. They are also block level variables, which can
access with in the block where they are declared. In case of non-
availability of CPU memory, these variables
v ariables use primary memory (RAM).
E.g :-
void main( )
{
register int a;
clrscr( );
printf(“\
printf(“
getch( \ nThe
);nThe value of a=%d”,a);
}
Chapter 10
STRUCTURE
Structure is a group of similar and dissimilar data types. Structure is user
defined data type. To create a structure, we use struct keyword. Structure
starts with a delimiters ({) and close with a delimiter(}). After closing the
delimiters,
we create a westructure
place a semicolon. To accessfield.
variable/ structure the elements
With the of theofstructures,
help structure
variable we use the dot operator and a specific element name,
nam e, which we want
to access. As shown in the syntax below:
Syntax
Syntax
struct<structure name>
name>
{
<variable>;
<data type> <variable>;
<data type><variable>;
type><variable>;
};
};
Example
Example
student
struct student
{
char name[20];
int roll, marks ;
;
};
};
In this example student is structure name and in this structure we declare
two different data types , i.e. char & int.
int.
Example of structure
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll,marks;
};
void main()
{
struct student s; //s is structure variable
clrscr();
printf(“enter student name”);
scanf(“%s”,&s.name);
printf(“enter student roll no”);
scanf(“%d”,&s.roll);
printf(“enter student marks”);
scanf(“%d”,&s.marks);
scanf(“%d”,&s.marks);
printf(“\
printf(“\ n your name=%s”,s.name);
printf(“\
printf(“\ n your roll=%d”,s.roll);
printf( \ n your marks=%d ,s.marks);
,s.marks);
getch();
}
Initialization of structure
Initialization of structure means to give the initial values to the structure
elements in place of giving the values at run time. As shown in the example
given below:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll,marks;
};
void main()
{
struct student s={“Anju”,1,89};
s={“Anju”,1,89}; //initialization of structure
variable s
clrscr();
printf(“\
printf(“
printf(“\ n
printf(“\
\ n your
your roll=%d”,s.roll);
name=%s”,s.name);
printf(“\n
printf(“\n your marks=%d”,s.marks);
getch();
}
name
0 1 2 3 4 ----------------------------------------- 16 17 18 19
roll
0 1
marks
0 1
Here s is the structure variable and name,marks are the elements of structure
which we are accessing using dot operator.
Structure Array
We can also create an array of the structure for storing the details of more
than one student.
struct student s[5];
Here s is the name of the structure array.The elements of this array are
s[0],s[1],s[2],s[3],s[4].
Write a program to enter the details of five students: their name, roll
no and marks using structure.
# include<stdio.h>
# include<conio.h>
struct student
{
char name [20];
int roll,marks;
};
void main( )
int i;
struct student s [5];
clrscr( );
for(i=0;i<5;i++)
{
printf(“\
printf(“\ n enter your name”);
scanf(“%s”,& s[i].name);
printf(“please enter roll no”);
no”);
scanf(“%d”,& s[i].roll);
printf(“please enter your marks”);
scanf(“%d”,& s[i].marks);
s[i].marks);
}
for(i=0;i<5;i++)
{
printf(“\
printf(“\ n your name=%s”,s[i].name);
printf(“\
printf(“\ n your roll no=%d”,s[i].roll);
printf(“\
printf(“\ nyour
nyour marks=%d”,s[i].marks);
marks=%d”,s[i].marks);
}
getch( );
}
Nested structure
Nested structure means a structure inside a structure.It is possible to
have one structure as a member of another structure.In nested structure the
first structure is called the outer structure and second structure which inside
the structure is known as inner structure.E.g :-
struct emp
{
char name[20];
struct dep
{
int salary ;
}d;
};
void main( )
{
struct emp e;
clrscr( );
printf(“Enter Employ name=”);
sacnf(“%s”,& e.name);
printf(“Enter your salary=”);
sacnf(“%d”,& e.d.salary);
e.d.salary);
printf(“\
printf(“\ n Your name=%s”,e.name);
printf(“\
printf(“\ n Your salary=%d”.e.d.salary);
getch();
}
struct student
{
char name[30];
int roll, marks;
};
void show(struct student s);
void show(struct student s);
s);
{
print(“\
print(“ \ n Student name=%s”,s.name);
print(“\
print(“ \ n Student roll=%d”,s.roll);
print(“\
print(“ \ n Student marks=%d”,s.marks);
marks=%d”,s.marks);
}
void main()
{
struct student s={“Harparteek”,1,89};
clrscr();
show(s);
getch();
}
In the above example first we declare the structure and then declare the
function with structure argument. Then we define th body of the function and
in last call the function with main function.
Structure Array
Structure starts with struct It does not start with any keyword but
keyword. is uses subscript for creating an array.
We can use dot operator to We can use index of the arrayto access
accesses the elements of the the element of the space array.
structure.
Important
1. Long
Explain Answer
structure Type
in C. How Questions
can you differentiate it from an array?
2. How structures are defined and initialized? Explain with example.
3. Explain by giving example how the members of structure are
accessed in C.
4. What do you mean by structure within a structure? Give Example.
5. Explain how structure can be passed to a function as argument
with example.
6. Write a program in C to define a structure student with data
members like rollno, class and marks of 5 students. Calculate total
marks and show the students detail.
7. Write a program to create a structure student having data
members
argument. as student name, rollno and pass it to a function as an
Chapter 11
UNION
Union is a group of similar and dissimilar data types or elements. It is a user
defined data type. Union starts with ‘union’ keyword and terminate with
semicolon same as structure. Union allocates a single memory to its elements.
All the elements of the union share the single memory. To access the elements
0 1 2 3 4 5 6 ------------------------- 17 18 19
roll
marks
As shown in the example and figure the union allocate 20 bytes memory for
name, roll and marks, which is the largest or higher memory in the union.
WAP to create union, which can store student detail like students
name, rollno, and marks.
union student
{
char name[20];
int rollno,marks ;
};
void main( )
{
union student s;
clrscr( );
printf(“Enter Employ name=”);
sacnf(“%s”,& s.name);
s.name);
printf(“\
printf(“ \ n Your name=%s”,s.name);
printf(“Enter your Rollno.=”);
sacnf(“%d”,& s.rollno);
s.rollno);
printf(“\
printf(“ \ n Your Rollno.is=%d”,s.rollno);
printf(“Enter your Marks=”);
sacnf(“%d”,& s.marks);
s.marks);
printf(“\n
printf(“ \n Your Marks is=%d”,s.marks);
getch();
}
Initialization of union
We cannot initialize the union same as structure
s tructure because it uses the
single memory location and all the elements use the same memory.
Ass sho
A shown i n the exam
xample below
low:
#include<stdio.h>
union student
char name;
int roll,marks;
};
void main()
union student s;
clrscr();
s.name='h'; //initialization of union variable s
printf("\n your name=%c",s.name);
s.roll=1;
printf("\n your roll=%d",s.roll);
s.marks=99;
printf("\n your marks=%d",s.marks);
getch();
Union Array
We can also create the array of the union same as structure for storing
the details of more than one student.
Write a program to enter the detail of five students: their name,
rollno and marks using union.
# include<stdio.h>
# include<conio.h>
union student
{
char name [20];
int roll,marks;
};
void main( )
{
int i;
union student s[5];
clrscr( );
for(i=0;i<5;i++)
printf(“\
printf(“\ n enter your name”);
scanf(“%s”,& s[i].name);
s[i].name);
printf(“\
printf(“\ n your name=%s”,s[i].name);
printf(“please enter roll no”);
scanf(“%d”,& s[i].roll);
s[i].roll);
printf(“\
printf(“\ n your roll no=%d”,s[i].roll);
printf(“please enter your marks”);
scanf(“%d”,& s[i].marks);
s[i].marks);
printf(“\n
printf(“\n your marks=%d”,s[i].marks);
marks=%d”,s[i].marks);
}
getch( );
}
union emp e;
clrscr();
printf(“the size of the union=%d”,sizeof(e));
getch();
}
Difference between structure and union
Structure Union
Structure start with ‘struct’
‘struct’ Union start with ‘union’ keyword
keyword
All the elements of the structure All the elements use the single
use different memory locations memory location for storing the
for storing the data. data.
It allocates different memory to It allocates single memory. All the
each element. elements share the same memory.
Chapter 12
ENUMERATION
The enumerated data type is used when we know in advance about a finite
list of values as a particular data type. The declaration of enumerated data
type start with ‘enum’ keyword.. ‘enum’ keyword is followed by an enum
name, an open brace, each of the values separated by a comma, and finally a
closing brace and a semicolon. The list of values is known as the enumerated
list of items.
Syntax: -
enum <enum name>{value1,value2,value3……….value n}; n};
example:
enum color { red, blue, green, white, black };
Note:- Here color is the name of the enum, and red, green, blue are the
symbolic constants. Each enum constant has an integer value. If we have not
given any value, then the initial value of the red is 0, blue is 1 an
and
d so on and
incremented by one.
As shown in the example below:
#include<stdio.h>
#include<conio.h>
enum col{red, green, blue, yellow, black, white };
void main()
clrscr();
printf(“\
printf(“\ n the value of red=%d”,red);
printf(“\
printf(“\ n the value of green=%d”,green);
printf(“\
printf(“\ n the value of white=%d”,white);
getch();
output:-
the value of red=0
the value of green=1
the value of white=5
void main()
{
clrscr();
printf(“\
printf(“\ n the value of red=%d”,red);
printf(“\
printf(“\ n the value of green=%d”,green);
printf(“\
printf(“\ n the value of white=%d”,white);
getch();
}
Output: -
the value of red=0
the value of green=5
the value of white=9
Important Short Answer Type Questions
1. Give an example of enumerated data type in C.
Important Long Answer Type Questions
1. Explain enum declaration in C with suitable example.
2. How can you differentiate enum from an array?
Chapter 13
POINTER
Pointer is a special type of variable, which is used to store the address of
another variable. This variable starts with asterisk symbol (*). The pointer can
use two special operators.
1. The first one is *(asterisk), it is called indirection operator or
value of operator.
2. The second is &(ampersand), it is called
ca lled address of operator.
Pointer declaration
A pointer is declared same as a variable with a specific data type. But
declared with an asterisk sign. As show in the example below:
Example
int *ip; //ip is our integer pointer
float *fp; //fp is our Float pointer
char *cp; //cp is our character pointer
to pointer
Indirection operator variable ip*/
* (asterisk)
65524
Address of
pointer
variable
of the
variable
a 65526
scanf(“%d” , &b);
c=&a; &b);
d=&b;
//swapping of two numbers
*c= *c+ *d;
*d= *c - *d;
*c= *c- *d;
printf(“\
printf(“\ after
after swapping the numbers”);
printf(“\
printf(“\ n now the value of a=%d”,a);
printf(“\
printf(“\ n now the value of b=%d”,b);
getch();
}
Arithmetic pointers
We can also use pointers for arithmetic purposes same as
a s variables. When
we write a++ it increase the value of the variable but when we write p++,
p=p+3;
Assume that the address of p is 65524.
When we add 3 to the pointer it move to the next location is 65527.
Note that we can perform any arithmetic operation on a pointer variable.
Pointers with array
The values of the array can be accessed with the help of pointer. Normally
we can assign the address of first element of an array to the pointer. When
we increment inside the pointer, it increments its address. It
I t means it reads
the address of next element. The address of first element of an array is
called base address of array.
b=*p;
}
p++;
}
printf(“the maximum number=%d”,b);
getch();
}
for(j=0;j<3;j++)
{
printf("enter any number");
scanf("%d",&a[i][j]);
}
}
p=&a[0][0];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d",*p);
p++;
}
printf("\n");
}
getch();
}
Pointer with
We can also structure
access the elements of the structure with help of pointer. We can
assign the address of the structure variable to the pointer variable. For
accessing the elements we can use arrow (->) operator in place of dot(.)
operator.
Write a program to access the elements of the structure-using
pointer.
#include<stdio.h>
#include<conio.h>
struct stu
{
char name[20];
int roll;
};
void main()
{
struct stu s={"Pratham",1};
struct stu *p;
clrscr();
p=&s;
printf("\n your name=%s",p->name);
printf("\n your roll=%d",p->roll);
getch();
}
Pointer to pointer
Pointer to pointer means which can store the address of another pointer
variable. A pointer-to-pointer
pointer-to-pointer variable start with d
double
ouble asterisk (**) sign. A
simple pointer can store the address of a variable but a pointer to pointer
can store the address of another pointer. As shown in the example below:
Example :-
int a, *p,*
*p,**pp;
*pp;
a=5;
p=&a;
pp=&p;
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
int a,*p,**pp;
clrscr();
a=5;
p=&a;
pp=&p;
printf("\nthe value of a=%d",a);
printf("\nthe value of pointer =%d",*p);
printf("\n the value of pointer to pointer=%d",**pp);
getch();
}
Pointer passing as argument to the Function
We can also pass pointer variable as an argument into the function. This is
also known as reference variables.
As shown in the example below:
#include<stdio.h>
#include<conio.h>
void swap(int *a , int *b);
void swap(int *a, int *b)
{
*a=*a + *b;
*b=*a - *b;
*a=*a - *b;
}
void main()
{
int x,y;
clrscr();
printf(“enter the value of x”);
scanf(“%d”,&x);
scanf(“%d”,&x);
printf(“enter the value of y”);
printf (“Before Swapping”);
printf(“\
printf(“\ n %d/n%d”,x.y);
%d/n%d”,x.y);
scanf(“%d”,&y);
scanf(“%d”,&y);
swap(&x ,&y);
printf(“\n
printf(“\n after swapping “);
printf(“\
printf(“\ n the value of x=%d”,x);
printf(“\
printf(“\ n the value of y=%d”,y);
getch(); }
Function
A function Returning Pointer
can return a pointer same as it returns a variable. In this we can
declare and define the function with indirection
i ndirection (value of operator) operator.
int *show();
int *show()
int a;
printf("enter any number");
scanf("%d", &a);
a=a*a;
return &a;
void main()
int *p;
p=show();
printf("\n The value of a=%d",*p);
getch();
Advantages of Pointers
1. Pointers increase the speed of the program.
2. It is used to read the address of the variable.
3. It is used to the manage memory efficiently.
4. For Dynamic memory allocation we can use pointers.
5. With the help of pointers we can create efficient programs.
6. Pointers can be used to access elements of the structure.
7. It can pass as arguments into
i nto the function.
sign.
It can store the value. It can store the address of another
variable
It can not use any special It uses two special operators first is
operator. address operator and second is
indirection operator(value of operator).
Example Example
int a; int *p,b=5;
a=5; p=&b;
time.
is It is as
known known as static
dynamic memory.
memory. ThisThe memory
memory is which
waccessed
hich is allocated at run time
using pointer. For
dynamic memory we can use various methods, which are stored in the alloc.h
header file.These function are:-
1.
1. malloc() function
2.
2. calloc () function
3.
3. realloc() function
4.
4. free() function
1.
1. malloc()Function:-- malloc means memory allocation function.
malloc()Function:
This function is used to allocate dynamic memory at run time to the
pointer variable. This function allocates a single block of memory of
specific data type. As shown in the example below:
#include<alloc.h>
void main()
{
int i, n,*p;
clrscr();
printf("enter the size of the values");
scanf("%d",&n);
p=(int*) malloc(n);
for(i=0;i<n;i++)
{
printf("enter any number");
scanf("%d",(p+i));
}
for(i=0;i<n;i++)
{
printf("%d\n",(*p));
p++;
}
getch();
}
#include <stdio.h>
#include <alloc.h>
#include <string.h>
#include<conio.h>
void main()
{
char *p;
clrscr();
p = (char *) malloc(10);
strcpy (p, "CJSOFTECH");
printf("String is %s”,p);
printf(“\
printf(“\ n Address is %u”, p);
p = (char *) realloc(p, 20);
strcpy(p,"CJSOFTECH Patiala");
printf(“String is %s”,p);
%s”,p);
printf(“\n
printf(“\n New address is %u",p);
getch();
}
4. Free function:-
occupied This function
by the variable. is used which
That memory, to release the memory
is allocated which
by the aboveis
discussed functions like malloc(), calloc(), realloc(), so this function is used
to free the memory. This function contains a single argument, whose
memory we want to release. As shown in the syntax and example below:
2. What is a pointer? Explain the difference between simple variable and
pointer variable.
3. Demonstrate how pointer can be used to access data of a structure.
4. Describe how pointers are used for handling character string.
5. Write C program-using pointers to find the greatest of given three
numbers.
6. Write C program-using pointers to sort the given list of number in
ascending order.
7. What do you mean by dynamic memory allocation. Explain different
methods used for dynamic memory allocation.
Chapter 14
FILE HANDLING IN C
To understand the concept of File handling, we must understand the
following things;
things;
1.
1. Data : Raw information is called data. For example student name,
father’s name, address, dob, rollno etc. Each individual item is called
data.
For example
Name is a data, rollno is a data, dob is a data. In electricity dept person
name, address, meter no is a data.
2.
2. Record: Record is a collection of data of same type. It is a detail
of data. For example all things in your admission form name, fname,
dob, rollno, marks of yours together is known as record.
For example (navjeet, s. karamjit singh, 2-08- 1983, 1. 89). It is a
record of a single student.
In one record data should be of same concerned item or thing or person.
In one record we cannot mix data of different things.
D Person name
Student name Address
Address A Ph No
Father’s Name Meter No
Ph No
Roll No T Old Reading
New
School Name A Reading
Suppose these two different records are of yours. Name, Ph.no, Address
is common. But Roll no, meter no is different that’s why we create
different records.
3.
3. File : File is a collection of similar same type of records. For
example student’s records will
will be placed in a one file. (Student name,
Address, father’s name, phno, rollno, school name)
school name)
Electricity dept will hold records of bill in different file(Person Name,
Diagram of file
Data Name
Data Father’s Name ( N records mark 1 file)
Data Address
Data Ph No
Data DOB
Data City
Data School
Data Marks
N records
1 record
3rd record
nd
2 record
In earlier days, the amount of information is stored in manual form. The major
drawbacks of manual system are Required more space to store the data in file
Updating of data was very difficult.
Searching is quite difficult.
No security in manual Files Manual file were not reliable means if file was
lost all the data would also lost.
Now modern files are made on computers. The data is stored in
computerized files.
It has following advantages;
1. Data can be easily stored in compact space updating of data is
very easy. Using the pointers concept when we perform any changes in
a file, all the files which related with that file are automatically updated.
2. Searching is very easy.
3. The data in modern file are very secure. Only the authorized
persons can view data.
4. Files are very reliable because adequate backup checks are there.
The main motive of file handling is to transfer the data from primary
memory to secondary memory.
Types of Files
There are three types of files, which are;
3.
3. Append:: - If a file in this mode is opened we can add the data
Append
into the file at the end of the file. Parameter used in fopen is “a”.
is “a”.
r+ mode:- To open the file for reading and writing the data.
w+ mode:- To open the file for writing. Data can ca n be read after writing.
a+ mode:- To open the file ,write the data at the end of the file. Data
can be read after writing.
2.
2. fclose() function:- It is used to close a file. This function
contains a single argument, which is the file pointer. As shown in the
syntax and example given below:
Syntax: -
fclose(file pointer);
Example:
fclose(fp);
3.
3. fputs() function:- It is used to write a string into the file. This
function contains two arguments first is string and second is the file
pointer. As shown in the syntax and example
Syntax :-
fputs(string, file pointer);
Example:-
fputs(str, fp);
4.
4. fgets() function:- This function is used to read the data from a
file in string format. This function contains three arguments. First is
string in which data is stored, second argument is the length of the
string and third is the file pointer (fp). As shown in the syntax and
example
Syntax: -
fgets(string, length, file pointer);
Example: -
fgets(str,40,fp);
5. getc() Function:- This function is used to read a character from a file.
5.
This function contains a single argument of file pointer. As shown in the
syntax and example-
Syntax: -
variable=getc(file pointer);
Example:
char a;
a=getc(fp);
Note:
The character read from the file is assigned to a char variable a.
6.
6. Function:-This function is used to write a character to a
putc() Function:-This
file. It has two arguments, first is the character variable and second is
the file pointer. As shown in the example:-
Example:char a;
putc(a,fp);
Note:
include<conio.h>
void main()
{
char str[32],*p;
FILE *fp,*fp1;
clrscr();
fp=fopen(“CJSOFTECH.txt”,”r”);
fp1=fopen(“CJSOFTECH.txt”,”w”);
while((p=fgets(str,40,fp))!=’ \
\ 0’)
0’)
{
fputs(str,fp1);
}
fclose(fp);
printf(“data is copied”);
fclose(fp1);
getch();
}
FILE *fp;
int i;
for(i=1;i<=10;i++)
putw(i,fp);
printf("data is written");
fclose(fp);
getch();
printf("%d",n);
}
fclose(fp);
getch();
}
fp=fopen(“CJSOFTECH.txt”,”w”);
if (ferror(fp)==0)
{
printf(“No problem in file accessing”);
accessing”);
}
else
{
printf(“There is problem in file accessing”);
accessing”);
}
EOF():- This is known as End of file.
f ile. This function is used to check
the file end. In place of EOF we can use –1. It is same as end of file;
when our cursor reach as the end of the file then it returns a negative
Chapter 15
MACRO
Macro is also called a substitution string. A macro always start with # define.
After the # define, we can give the name to the macro and after that we can
give replacement text/value. Wherever the preprocessor encounters that
name, it will replace it with the replacement text. Macro is always declared in
capital letters, which differentiate the macro from variable. If we want to
change the value of the macro variable we can do it at only at place where it
is defined. Macro never ends with semicolon.
The value of the macro body specified by a #define directive can be any
character string or number. For example, the following definition
defini tion is NAME with
the string "CJSOFTECH".
SYNTAX:
#define <identifier><value>
Example:-
#define A 50
program.
WAP to use macro in the program.
#include<stdio.h>
#include<conio.h>
#define a 10
void main()
{
int b;
clrscr();
b=a*a;
printf(“square=%d”,b);
getch();
}
In macro we can also pass arguments inside the macro. It works as function,
which are defined before using it.
Write a program to swap two numbers without using third variable
and by using macro.
#include<stdio.h>
#include<conio.h>
#define swap(x,y)x=x+y;y=x-y;x=x-y
void main()
{
int a,b;
clrscr();
printf(“enter two no”);
scanf(“%d%d”, &a,&b);
swap(a,b);
printf(“\
printf(“\ n now value of a=%d” ,a);
printf(“\
printf(“\ n now value of b=%d”,b);
b=%d”,b);
getch();
}
Typedef
Definition: - Typedef means to rename the existing data type. With the
help of ‘typedef’
of ‘typedef’
/structure we
we
typedef can give the
declaration new
does notname to the
declare any inbuilt
new datadata type
type which does
not exist in the C language. Typedef means to create new definition name of
an existing data type.
SYNTAX: -
typedef<data type><new data type>;
Example: -
typ edef int cj ;
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int cj;
clrscr();
cj a,b,c;
printf(“enter two numbers”)
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum=%d”,c);
getch();
}
int i;
clrscr();
for(i=1;i<argc;i++)
{
printf("%s",argv[i]);
}
getch();
}
Steps to execute the program
1. After typing the program save the file with .c extension.
2. Now compile the program using ALT+F9.
3. Now click on file menu and select “Dos
“Dos shell”
shell” option.
4. Now first- type file name and then type number of arguments.
Example:
C:\tc\bin> filename one two three
Note: -Here CJSOFTECH is the file name and one ,two three are
arguments
5. Now press enter key.
To go back to the C program type “exit” and press enter key
key