C Language by Mahesh
C Language by Mahesh
Unit - I
The word “if” is used to specify decision in an algorithm. There are various forms of “if”
constructs used in algorithms.
a. Simple ‘if’ construct: In this method if the condition is true then it executes a process.
Otherwise it will not execute the process.
Syntax: If condition then process
Step 1: Start
Step 2: Input the first number as A
Step 3: Input the second number as B
Step 4: If A=B Then Print “Equal”
Step 5: End
b. IF.. Else construct: In this method if the condition is true then it executes process-1. If the
condition is false then it executes the process-2.
Syntax: If condition then
Process-1
Else
Process-2
Step 1: Start
Step 2: Input the first number as A
Step 3: Input the second number as B
Step 4: If A=B Then
Print “Equal”
Else
Print “Not Equal”
Step 5: End
3) Repetition:
Repetition means executing one or more steps for a number of times. Repetition is also called
Iteration or Loop.
The words “While, Do..While, For” are used to specify repetition in an algorithm. These loops
execute one or more steps as long as the condition is true.
Step 1: Start
Step 2: Let x = 1
Step 3: Repeat steps 4 and 5 while x ≤ 10
Step 4: Print x
Step 5: Let x = x + 1
Step 6: End
2. What is flowchart? Which symbols you are using while designing flowcharts.
Pictorial or Graphical representation of an algorithm is called a flowchart. Flowcharts are
designed by using some specific symbols. The most import symbols used for designing flowcharts
are:
Start / Stop Statements: The symbol used for to show START / STOP statements is “Oval”.
Symbol :
Input / Output Statements: The symbol used to represent input statements and output
statements is “Parallelogram”.
Symbol :
Flow Lines: The symbol used to represent data flow from one place to another place is “Arrow”.
Symbol :
Symbol :
Connector Symbol: The symbol used to connect two parts of the program flow is “Circle”.
Symbol :
When we reach the end of a column or a page, but total chart is not finished. In this case, at the
bottom of flow we use a connector to show that the flow continues at the top of the next column or
page.
Example : STAR A
T :
: :
A STO :
P
Additional symbols that used for designing flowcharts are:
Decision or Condition symbol: Decision diamonds create two data flow from one. A
decision diamond always has True / False or YES/NO written on the left and right
sides.
Symbol:
Loop or Iterative symbol: This symbol has hexagon shape. It is used when a problem
has repetitive steps. i.e. a problem has solution with steps repeating again and again till
a condition or definite number of times.
Symbol:
Function or procedure or sub- program symbol: This symbol has a rectangle shape
with two cuts or lines inside. This can be labeled with the function or procedure name.
Every program has ends with a terminator shape i.e. with an oval.
Function:
Eg-1: A flow chart to add two Eg-2: A flow chart to find Eg-3: A Flow Chart for
numbers equality of two numbers Repetition (To print first 10
natural numbers)
START
START START
Read A
Read Let I=1
A
Read B A
Read Yes
B Print I
Let Sum = I≤
No
10
A+B
Ye Print
A=B s “Equal” Let
Print I=I+1
No END
Sum
A
END
END
Each instruction in this language expands into several machine language instructions. Third
generation programming languages have made it easier to write and debug programs.
Third generation programming languages include languages such as BASIC (Beginners’ All –
Purpose Symbolic Code), FORTRAN (Formula Translator) and COBOL (Common Business
Oriented Language), C++ and Java.
Advantages:
The code is machine dependent.
It is easy to learn and use the language.
It is easy to document and understand the code.
It is easy to detect and correct errors.
Disadvantages:
Code may not be optimized.
The code is less efficient.
It is difficult to write a code that controls the CPU, memory, and registers.
FOURTH GENERATION: VERY HIGH LEVEL LANGUAGE
Fourth generation languages are non- procedural languages.
Here programmers define only what they want the computer to do, without supplying all
the details of how it has to be done.
Fourth generation languages need approximately one tenth the number of statements that a
high level language needs to achieve the same results.
The main objectives of fourth generation language is
Increasing the Speed of developing programs.
Minimize the user efforts to obtain the information from computer.
Decreasing the skill level required of users so that they can concentrate application rather
than coding.
Five basic types of language tools fall into the fourth generation language category.
Query language, Report generators, Application generator
Decision support systems and financial planning languages.
Some micro computer application software.
FIFTH GENERATION LANGUAGE:
Fifth generation languages concentrate on Natural languages representation.
5 GLs are designed to make the computer solve a given problem without the programmer.
While working with 4Gl, programmers have to write a specific code to do work, but with a
5GL, they only have to worry about what problems need to be solved and what conditions
need to be met, without worrying how to implement a routine or an algorithm to solve
them.
In general, 5Gls were generally built upon LISP, many originating on the LISP machine,
such as ICAD.
These languages are also designed to make the computer “smarter”. Natural languages
already available for microcomputers include Clout, Q&A, and Savvy Retriever (for use
with data bases) and HAL (Human Access Language).
Fifth generation programming languages are used in artificial intelligence research. Some
examples of 5GLs include Prolog, OPS5, and Mercury. A good example of fifth generation
language is Visual Basic.
Introduction
The programming language C was developed in the early 1972s by Dennis Ritchie at Bell
Laboratories to be used by the UNIX operating system. It was named ‘C’ because many of its
features were derived from an earlier language called ‘B’.
History of C
1. The programming language term is started in the year of 1950’s with the language called
FORTRAN.
2. From FORTRAN language one more programming language is evaluated ALGOL.
3. The beginning of C is started in the year of 1967 with the language called BCPL. Basic
Combined Programming Language which is evaluated by Martin Richards.
4. In the year of 1970’s from BCPL one more programming language is evaluated by ken
Thomson called B language.
5. From ALGOL, BCPL and B; in the year of 1972 Dennis Ritchie was evaluated one more
programming language called C language. At Bell Labs for developing system software.
6. C was documented and popularized in the book ‘The C Programming Language’ by
Brian W. Kernighan and Dennis Ritchie in 1978. This book also popular that the
language came to be known as ‘K& RC’.
7. In the year of 1989 C programming language is standardized by ANSI that version is called
ANSI C.
8. In 1990 the international standards organization (ISO) adopted the ANSI standard. This
version of C came to be known as C89.
9. In 1995, some minor changes were made to C89, the new modified version was known as
C95.
10. In 1999, some significant changes were made to C95; the modified version came to be
known as C99.
11. In the year of 2000, C99 was adopted as an ANSI standard.
1) Document Section:
This is an optional section
This section consist information about the program
It is not understand by compiler
This documenttation is provided by using comments.
C provides two types of comments.
1. Single line comments. (//)
2. Multi line comments. ( /*…. */)
Ex: /* this is a c-program to find addition of 2 numbers */
Link section or preprocessor section
Preprocessor statements are used to import different predefined functions into the program.
This section is executed , before compiling the program and it is used for linking other
program with current program.
The functions are included form the system library by the means of preprocessor directives.
The system library consists of a set of header files names ‘stdio.h’, ‘math.h’, ‘conio.h’ etc.,
these are included using ‘#include’ statement.
This statement is not terminated by a semicolon (;).
Definition section
The definition section defines all the symbolic constants.
The symbolic constants are defined by the statement ‘#define’.
This statement is not terminated by a semicolon (;).
Ex: #define pi 3.14
#define c 120
Global declaration section
Global variables are used to share the data along all functions of the program.
There are some variable that are used in more than one function. Such variable are known
as global variables.
These variables are declared in the global declaration section, which is outside of all the
functions.
These variables are accessed by entire program.
Main ( ) function section
Every ‘C’ program must have one main() function section. It consists of two parts namely:
1. declaration part
2. executable part
The declaration part declares all the variables that are used in executable part.
The executable part must contain at least one statement.
Every statement in declaration and executable parts should ends with semicolon (;) symbol.
Sub-program section
The sub-program section contains all the user-defined functions that are called in the
main() function section.
These functions can appeared in any order. These functions are placed immediately after
main() function section.
Every ‘C’ program must contain main function while other sections are optional.
FIRST C PROGRAM
C programming language is a case sensitive language. I.e. upper case and lower case both are
treated as different.
When we are working with C language existing keywords and functions should be used in same
case only.
void main()
{
printf(“Welcome to GMinformatics”);
}
OUTPUT: welcome to GMinformatics
In the above program:
void is a keyword which indicates return type of the function.
main() is a identifier which indicates starting point of the program.
Opening curly brace indicates instruction block is started, closing curly brace is indicates
instruction block is ended.
Programming in C Prepared by Mahesh MCA
CSE II 11
Every C Program has four kinds of files associated with it. These include:
Files in a C
program
Linker Runtime
Support
Executable
Prog.ex
file e
CP
U
Output
6. operators
Keywords:
It is a reserved word some meaning is already allocated to this word, and that meaning already
knows by compiler. In c programming language total number of keywords is 32. these keywords
cannot be used as an identifier.
ex:- if, else, break, while, case, goto.
Variable:
a variable is defined as a meaningful name given to a data storage location in computer memory. or
a variable is a quantity that does change during the program execution.
Constants:
It is a fixed never be changed during the execution of the program. In c programming language
constants are classified into two types.
o Alpha numeric constants.
o numeric constants
Strings:
A string is a sequence of character enclosed in double quotes. the character may be an alphabet,
number, special symbol and blank spaces.
Example: “MAHESH”, “MCA”, “gminformatics”
Special characters:
‘C’ supports some special operators of interest such as [ ], ( ), -->, * these are used as a separation,
pointer and some other special purposes.
Operators:
It is a special kind of symbol which performs a particular task. In c programming language total
number of operators 44.
7. What is identifier and write the rules to follow while selecting an
identifier?
An identifier is a name given to the program elements such as variables, arrays, and functions.
Identifiers may consist of sequence of letters, numerals, or underscores.
Rules for forming identifier names:
Identifiers cannot include any special characters or punctuation marks (like #, $, ^,?,., etc)
except the underscore.
There cannot be two successive underscores.
Keywords cannot be used as identifiers.
Identifiers can be of any reasonable length. They should not contain more than 31
characters.
In identifier declarations name of the variable must starts with alphabet or underscore only.
Examples: roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code
8. What is variable and write the rules to follow while selecting a variable?
Variable:
A variable is defined as a meaningful name given to a data storage location in computer memory.
Or
A Variable is a quantity that does change during the program execution.
Rules for forming identifier names:
Data Types
It represents without fractional part. Negative values are also allowed. C has three classes of
integer storage. They are short int, int and long int, in both signed and unsigned forms. The size
and range of these types are shown in the following table:
An array is a collection of memory locations which can share same data name and same data type
values.
Function:
Self contain block of one or more statements which is designed for a particular task is called
functions or sub program in an application called function.
Pointer:
A pointer is a variable which holds address of another variable. (Or)
3.USER DEFINED DATA TYPES:
All predefine data types are designed for basic operations only. i.e. it can work for basic data types.
In implementation whenever the primitive data types are not supporting user requirement then go
for structures.
Structure:
Structure is a collection of different data type variables in a single entity.Structure is a collection of
primitive and derived data type variables.By using structures we can create user defined data types.
Union:
Union is a user defined type. It looks similar to structure, but the functionality differs. When a
variable belongs to union is created, it allocates the common memory allocation to all the
members.
Enumeration:
enum is a keyword. By using enum we can create sequence of integer content values.By using
enum we can create userdefined datatype of integer.
It is a fixed never changed during the execution of the program. Constants are used to define fixed
values like pi or electron charge.
The literal values inserted in the code are called constants because we can't change these values. C
supports several types of constants (literals) as follows:
Integer Constants: An Integer constant refers to a sequence of digits. There are three types of
integer constants. They are: Decimal Integer, Octal Integer and Hexadecimal integer.
Decimal Integers: Decimal integers consists of a set of digits, 0 to 9, preceded by an optional – or
+ sign.
Ex: 123 -321 0 43564 +765
Octal Integers: An Octal integer constant consists of any combination of digits form 0 to 7, with a
leading 0.
Ex: 035 0 0435 0776
Input output deals with the basic understanding of the streams involved in accepting input and
printing output in C program.
Streams: A stream acts in two ways. It is the source of data as well as the destination of data.
Streams are associated with a physical device such as a monitor or with a file stored on the
secondary memory. C uses two forms of streams text – and binary.
In text stream, sequence of characters is divided into lines with each line being terminated with a
new line character (\n). And binary stream contains data values using their memory representation.
Within the double quotation whatever we leave it prints as these, if any format specifier copies that
type of value.
syntax:
printf (“control string”, variable list);
scanf( ) :
scanf is a predefine function by using scanf we can read the data at runtime from user at run time.
Scanf function its ‘n’ number of arguments but first argument must be within the double quotes
and every argument should separated with comma.
Within the double quotation we need to pass proper format specifiers only. i.e. one type of values
we need to scan same type format specifier should be provided.
When we are working with scanf function argument list should be provided with ‘&’ symbol or
else values will be not store in proper variables.
syntax
scanf(“control sting”, arg1, arg2, arg3 …., argn )
Format specifiers:-it indicates what type of values needs to be printed on console.
%d --------------------------> int
%f----------------------------> float
%c-----------------------------> char
+, -, *, /, %
Operator Meaning Syntax
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulo division a%b
2. Relational operators:
Relational operators are used in decision statements like if, while and for etc., these are the binary
operators used between any two operands. Any relational expression returns either true or false that
is 1 or 0. The relational operators in “C” language are <, >, <=, >=, ==, !=.
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
3. Logical operators:
The logical operators are used when we want to test more than one condition and make decisions.
Logical operators are also used to concatenate multiple relational expressions. Hence a logical
expression is called compound relational expressions. The result of any logical expression is either
true or false that is either 1 or 0.
Operator Meaning
&& logical AND
|| logical OR
! logical NOT
4. Equality operators: C language supports two kinds of equality operators to compare their
operands for strict equality or inequality.
Operator Meaning
== Return 1 if both operands are equal, 0 otherwise.
!= Returns 1 if operands do not have the same value, 0 otherwise.
5. Unary operators: Unary operands act on single operands. C language supports three unary
operators: Unary minus, increment, and decrement operators.
Unary minus: Unary minus operator is different from the binary arithmetic operator that operator.
When we are working with unary operator an operand is preceded by a a minus sign, the unary
operator negates its value. i.e if the number is positive then it become negative and if the number is
negative then it becomes positive.
Increment and decrement operators:
++, – – are the increment and decrement operators used to increment and decrement
the value of a variable by 1. These can be used as a postfix or prefix operators according
to the requirement.
6. Conditional operators:
Conditional operators are ternary category operators (? : ).
Ternary category means it require three arguments.
o i.e. left, middle and right side arguments.
Programming in C Prepared by Mahesh MCA
CSE II 21
If the expression is true then it returns with middle argument, if the expression is
false then it returns with right side argument and left side argument is
expression or condition.
Implicit Typecasting: It is a concept of converting the lower data type values into higher data
types.Implicit type casting is under control of compiler. i.e. as a programmer when implicit type
casting is occurred there is no need to be handle explicitly.
// An example of implicit conversion
#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
Explicit Type casting: It is a concept of converting higher data type values into lower data types.
i.e. as a programmer when we are expecting explicit type casting then mandatory to use type
casting process or else data over flow will be occurred. It helps us to compute expressions
containing variables of different data types.
int main()
{
double x = 1.2;
return 0;
}
PROGRAMMING EXAMPLES:
STATEMENTS
A statement is a syntactic construction that performs some action when the program is
executed. In C language, statements are classified into three types as:
1. Simple (or) Expression Statements
2. Compound (or) Block Statements
3. Control Statements
1. Simple (or) Expression Statements
A simple statement is a single statement that ended with a semicolon.
Example: int x,y;
Control statements
if for continue
if- else-if
switch
1. Write about the conditional branching or conditional selection statements
used in C language?
The conditional branching statements help to jump from one part of the program to another
depending on whether a particular condition is satisfied or not. These decision statements include:
1. If statement
2. if-else statement
3. if-else-if statement
4. switch statement
1. If statement: The simplest form of decision control statement that is generally used in decision
making. The general syntax of simple ‘if statement’ follows.
Syntax of if statement:
if (condition)
{
statement1;
…………….
statementn;
}
If the condition is logically true (i.e. non-zero), the statement following the ‘if’ executed.When
there are multiple statements then they must be enclosed within curly braces ‘{ }’.
w.a.p Program to demonstrate simple if
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
clrscr();
printf(" Enter age of the person : ");
scanf("%d",&age);
if(age>=18)
printf(" The person is eligible to vote");
printf(" \nThank you");
getch();
} O/P: Enter the age of the person: 30
The person is eligible to vote.
Thank you
2. If-else statement: Using else is always optional.In implementation we having alternate block of
condition then go for else part.When we are constructing the ‘else’ part mandatory to place ‘if’ part
also. Because without if there is no else among those if and else only one block will be executed.
i-e. When if condition false then only else part will be executed.
Syntax:
if(condition)
{
statement1;
statement2;
}
else
{
statement3;
}
w.a.p to find biggest of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(" enter two number: ");
scanf(“%d%d”,&a,&b);
if(a>b)
printf("%d is biggest number",a);
else
printf("%d is biggest number",b);
getch();
Programming in C Prepared by Mahesh MCA
CSE II 25
}
O/P: Enter two numbers: 20 30
30 is biggest number.
3. If-else-If statement (Nested if else): If it is a concept of placing a condition part within another
condition. We can construct ‘n’ number of nested blocks but any type of editor can support up to
255 blocks.
Syntax:
if(condition1)
{
block 1;
}
else if(condition2)
{
block2;
}
else
{
block3;
}
}
w.a.p to find biggest of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("enter 2 values:");
scanf("%d%d",&a,&b);
if(a==b)
printf(" Two numbers are equal");
else if( a>b)
printf("%d is greater number",a);
else
printf("%d is smaller number",b);
getch();
}
At the time of execution if condition return values is match with anyone of the cases then
from matching is up to break, everything will be executed, if the break is not exist
including default all cases will be executed.
A default is a special kind of case which will execute automatically when the matching case
is not occurred.
Using default is always optional, in implementation when we are not handling all cases of
the switch block then recommended go for default.
Syntax to switch case
switch(condition)
{
case const1: Block1;
break;
case const2: Block 2
break;
case const3: Block 3;
break;
default: block n;
}
Advantages of using switch statement:
Easy to debug.
Easy to read and understand.
Ease of maintenance as compared with
its equivalent if-else statement.
Like if else statement switch statement also nested.
Executes faster than its equivalent if-else construct.
w.a.p to perform arithmetic operations using switch case
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,opt;
clrscr();
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
printf("Enter your choice 1 to 4: ");
scanf("%d",&opt);
switch(opt)
{
case 1: c=a+b;
printf("Addition of two numbers: %d",c);
break;
case 2: c=a-b;
printf("Subtraction of two numbers: %d",c);
break;
case 3: c=a*b;
printf("Multiplication of two numbers:%d",c);
break;
case 4: c=a/b;
printf("Division of two numbers: %d",c);
default: printf("Invalid option");
}
Programming in C Prepared by Mahesh MCA
CSE II 27
getch();
}
2. Write about the iterative or looping control statements in C language?
Set of instructions give to the compilers to execute set of statements until condition became false
that is loop.
The way of repetitions are forms the circle, that’s why iteration statements are called loops. i.e.
loops means forming a circle. The basic purpose loop is code repetition.
In implementation whenever the repetition are occurred when instance of writing statement go for
loops.
In c programming language loops are classified into three types.
1. while loop
2. do-while loop
3. for loop
When we are working with iteration statements first it checks the condition and if the condition is
evaluated as true then loop block will be executed.
After execution of the statement block once again it checks the condition, if the condition is true
once again block will be executed.
While loop: When we are working with while loop always pre-checking process will occur and it
repeats in clock direction.
Syntax to while
while (condition)
{
statement 1;
statement 2;
………….
………….
statement n;
inc /dec;
}
Working: It executes all the statements in the statement-block as long as the condition true. When
the condition false then the loop is terminated.
In implementation if at least need to be executed the statement block once. Then go for
do-while. When we are working with do-while always post checking process will occur
i.e. after execution of the statement block only condition will be evaluated.
Syntax to do-while
do
{
statement 1;
statement 2;
statement 3;
inc/dec;
}while (condition);
Working: It executes all the statements in the statement-block first and then tests the condition.
When the condition true then the loop is repeated otherwise the loop is terminated.
statement block:
}
Working
The execution process of the for loop always starts from initialization
Initialization will be executed only once when we are entering into the loop first time.
After execution of the initialization block control will pass to conditional block, if the
condition is evaluated as true then control will pass to statement block.
After execution of the statement block control will pass to iteration block, after execution of
the iteration, once again the control will pass to the condition.
Always the repetitions will happen between condition, statement block and iteration only.
When we are working with for loop everything is optional, but mandatory to place two
semicolons.
Programming in C Prepared by Mahesh MCA
CSE II 29
When we are working with for loop it repeats in anti clock direction.
w.a..p to demonstrate for loop
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("Enter a range: ");
scanf("%d",&n);
for(i=1; i<=n; i++) //i<=n/2
{
printf("\t%d",i);
}
getch();
}
3. Write about the concept of nested loops in C.
Loop control statements can be placed within another loop control statement. Such representation
is known as nested loops. In these situations, inner loop is completely embedded within outer
loop.
Example: for( i=1; i<=n; i++) outer loop
{
----
for( j=1; j<=i; j++) inner loop
{
---
}
----
}
#include<stdio.h>
#include<conio.h>
void main()
{
int r,i,j;
printf("enter number of rows");
scanf("&d",&r);
for(i=1;i<=r;i++)
{
printf("\n");
for(j=1;j<=i;j++)
printf("*");
}
getch();
}
3. Write about the break and continue (Jumping or Skipping) statements
used in C language? Or unconditional branching statements.
Branch control statements are used to transfer the control from one place to another place. C
language provides three branch control statements. Those are
break statements:
Programming in C Prepared by Mahesh MCA
CSE II 30
‘break’ is a keyword by using break we can terminate loop body of switch body.
Using break is always optional. But it should be exist within the loop body or switch body
only.
In implementation where we know maximum number of repetitions but certain condition is
there we need to stop the repetition process, and then go for break. A break is usually
associated with an ‘if’.
Syntax: break;
w.a.p to demonstrate break statement
#include<stdio.h>
#include<conio.h>
void main( )
{
int i=1;
while(i<=10)
{
if(i==6)
break;
printf("\t Mahesh");
i=i+1;
}
getch();
} O/P: Mahesh Mahesh Mahesh Mahesh Mahesh
The ‘continue’ statement:
Continue is a keyword by using ‘continue’ we can skip some of statements from loop body.
Using continue keys always optional. But it should be within the loop body only.
In implementation where we knows maximum number of repetitions but certain conditions
is there where we need to skip the statement block of loop body then go for continue.
A ‘continue’ is usually associated with an’if’.
Syntax: continue;
Write a C++ program to demonstrate continue statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
continue;
printf("\t %d",i);
}
getch(); } O/P: 1 2 3 4 5 7 8 9 10
statement 2;
goto label;
statement 3;
Label:
statement 4;
statement 5;
/*demonstrating 'goto' statement*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("Mahesh");
goto ABC;
printf("X");
printf("Y");
printf("Hello");
ABC:
printf("\t MCA");
getch();
} O/P: Mahesh MCA
Function: Self contain block of one or more statements which is designed for a
particular task is called functions or sub program in an application called function.
Syntax:
return type function name (parameters)
{
statement body;
-----------------
-----------------
return statement;
}
Advantages:
By using functions we can develop an application in module format.
When we are applying the application in module format then easily we can develop
easily we can debug and trace the program.
By using functions large applications can be design like a smaller one.
By using functions we can keep track of what they are doing.
The basic purpose of function is code reuse.
A C program is a collection of functions.
From any function we can invoke (call) any another function.
Always compilation process will starts from top to bottom.
contain block of one or more statements which is designed for a particular task is called
functions.
A function accepts arguments from other functions, returns maximum a single value. A
C program has any number of functions. But execution starts from the main (). All the
functions other than the main are called sub function. Sub functions are executed when
they are called directly or indirectly from the main ().
Parts of function:
A function has the following parts:
1. Function prototype/declaration.
2. Definition of a function (function declarator)
3. Function call
4. Actual and Formal Arguments
5. The return statement.
1. Function Prototypes: A function prototype declaration consists of the function
return type, name, and arguments list. It tells the compiler the name of the function,
the type of value returned and the type and number of arguments. When the
programmer defines the function, the definition of function must be like its prototype
declaration. If the programmer makes a mistake, the compiler generates an error
message. The function prototype declaration statement is always terminated with semi-
colon.
Syntax:
<return type> function name (list of arguments type);
Example:
float adding(float,float);
2. Function Definition: The first line is called function declarator and is followed by
function body. The block of statements followed by function declarator is called as
function definition. The declarator and function prototype declaration should match
each other. The function body is enclosed with curly braces. The function can be defined
anywhere.
Syntax:
<return type> function name (List of formal arguments)
{
--------------------------
--------------------------
return <exp>;
}
Programming in C Prepared by Mahesh MCA
CSE II 34
Example:
float adding(float x,float y)
{
return x+y;
}
3. Function Call: A function call is a latent body. It gets activated only when a call to
function is invoked. A function must be called by its name, followed by argument list
enclosed in parenthesis and terminated by semi-colon.
Syntax:
<variable>=function name (List of actual arguments);
Example:
c=adding(a,b);
4. Actual and Formal Arguments: In function header whatever the variables we are
creating those are called formal arguments or parameters.In fnction calling statement
whatever the variables/data we are passing those variable are called actual arguments.
5. The return statement: The return statement is used to return value to other caller
function. The return statement returns only one value at a time.
welcome to functions..!
enter a & b values: 30 20
addition : 50
#include<stdio.h>
#include<conio.h>
void add(int,int); //function declaration
void main() //functions example program.
{
int a,b;
clrscr();
printf("welcome to functions..!");
printf("\nenter a & b values: ");
scanf("%d%d",&a,&b);
add(a,b); //function calling. call by reference.
getch();
}
void add(int a,int b) //function definition.
{
printf("\naddition : %d",a+b);
}
OUTPUT:
welcome to functions..!
enter a & b values: 30 20
addition : 50
#include<stdio.h>
void main()
{
int add_function(int x, int y);
int a,b,sum;
clrscr();
printf("enter any two numbers: ");
scanf("%d %d",&a,&b);
sum=add_function(a,b);
printf("the sum of %d and %d is %d: ",a,b,sum);
getch();
}
int add_function(int x,int y)
{
return(x+y);
}
OUTPUT
Programming in C Prepared by Mahesh MCA
CSE II 36
welcome to functions..!
enter m & n values: 30 20
subtraction : 10
void fun1(int,int);
void main( )
{
int a=10, b=15;
fun1(a,b);
printf("a=%d,b=%d", a,b);
getch();
}
void fun1(int x, int y)
{
x=x+10;
y= y+20;
}
Output: a=10 b=15
The result clearly shown that the called function does not reflect the original values in main
function.
CALL BY ADDRESS:
It is a concept of calling a function by sending address type arguments.
In call by address actual arguments are address type and formal arguments are pointer type.
In call by address if any modifications are happen on formal arguments then those changes
will be effected on actual arguments
Calling function needs to pass ‘&’ operator along with actual arguments and called function
need to use ‘*’ operator along with formal arguments. Changing data through an address
variable is known as indirect access and ‘*’ is represented as indirection operator.
Ex: scanf(), strcpy(), strlen()
#include<stdio.h>
#include<conio.h>
void fun1(int *,int *);
void main( )
{
int a=10,b=15;
fun1(&a,&b);
printf("a=%d,b=%d",a,b);
getch();
}
void fun1(int *x, int *y)
{
*x = *x + 10;
*y = *y + 20;
}
1. Block Scope:
A variable is said to have block scope, if it is recognised only with in the block where it is
declared.The following example demonstrates this concept:
#include<stdio.h>
main()
{
{/*Block-1*/
int a;
a=10;
printf("%d\t%d",a,b);
}
{/*Block-2*/
int b;
b=20;
printf("%d\t%d",a,b);
}
}
2.Scope of local variables:
Variables declared within a function are called local variables. The visibility of these
variables is limited to the home function in which they are declared, local variables
belongs to one function can’t be accessed from another function.
Say for example, variables declared within main() are local to main(), can’t be accessed
directly from other function like display(). In the same way, variables belongs to display()
can’t be directly accessed from the main().
/* scope of automatic variable */
#include<stdio.h>
int main()
{
int x=10;
display();
return 0;
}
void display()
{
printf("x=%d",x);
}
Output:
Error: undefined symbol “x” in function display()
3.Scope of global variables:
Variables declared outside the functions are called global variables. These variables are
available along down to the program from their declaration. Global variables are visible
only to the functions, which are down to their definition, can’t be accessed from the
functions above to their definition.
/* Scope of global variables */
#include<stdio.h>
int x=10; /* global variable definition */
void display();
int main()
{
Storage
classes
{
auto int x=100;
clrscr();
//++x;
printf("\nValue 1:%d",x);
Fun();
getch();
}
void Fun()
{
int y=20;
printf("\nValue 2:%d",y);
}
Register:
It is a special kind of variable which stored in CPU register. Register variables are declared with
the keyword ‘register’. The main advantage is that accessing is very fast when compared memory
unit. In implementation we are using a variable throughout the program,then go for register
variables.
/* Example program for register variables */
#include<stdio.h>
#include<conio.h>
void main()
{
register int x;
clrscr();
x=10;
printf("\nValue :%d",x);
getch();
}
Static: Static variables are declared with the keyword ‘static’ either within the function or
outside the function. The advantage of static variables to retain updated values between
function calls.
{
int i;
clrscr();
for(i=1;i<=3;i++)
{
printf("\nValue :%d",x);
Fun();
}
getch();
}
void Fun()
{
x=x+5;
}
extern:
External storage class variables are declared outside the function with a keyword ‘extern’.
Variable declared outside the function without a storage class specification, by default
compiler assign ‘extern’ keyword and treated as external variables.
given condition is satisfied. Some of the complex problems can be easily solved by implementing
recursion.
Recursions can be classified into two types
Direct recursion: Function itself is clled direct recursion.
void sum()
{
………
………
sum()
}
Indirect recursion: Function calls another function, which initiates to call the initial function is
called indirect recursion.
void sum()
{
………
………
}
void call()
{
……….
……….
sum()
}
UNIT – III
CHAPTER I: ARRAYS
Every element in an array is identified with an index. The index starts from 0. The index of the last
element is n-1, where n is the size of array. Every element in an array is free to participate in
arithmetic, relational and logical operations.
Declaration of a single dimensional array: Declaring an array means specifying three things.
Data type: What kind of values it can store. For example int, char, float and double.
Array name: To identify the array
Size: The maximum number of values than the array can hold.
Syntax:
<Data type> <name of array> [<size>]
Example:
20 30 50 96 100
int m [5];
m[0] m[1] m[2] m[3] m[4]
Define an array by the name ‘m’ that can hold a maximum of 5 elements. The individual elements
of an array are accessed and manipulated using the array name followed by their index. The marks
stored in the first subject is accessed as m[0] and the marks scored in the 5th subject m[4].
Accessing data from an array:
To access elements from an array, index need to be changed from 0 to n-1 that can be done by
using a common loop.
for(i=0;i<size;i++)
a[i]
Array initilization:
Initializing while declaration of an array:
We can assign a set of values of similar type to an array while its declaration. Assigning
while declaration is called initializing. Elements of same type separated with comma (,)
and placed in a pair of parenthesis { } can be directly assigned using assigning operator
(=) to the array declaration statement. Values are assigned to the array in the same
order as in the order of set.
To access elements from the keyboard and store into an array, index need to be changed from 0 to
n-1 that can be done by using a common loop.
int i, int marks[5]
for(i=0;i<size;i++)
scanf(“%d”,&marks[i]);
Example:
int a[ ]={10,20,40,45,30,12}; /* size is optional */
#include<stdio.h>
int main()
{
int a[ ]={10,20,40,45,30,12};
int i;
printf("Elements of array:\n");
for(i=0;i<6;i++)
printf("%d\t",a[i]);
return 0;
}
int marks[5]={90,45,67,85,36};
int marks[4] = { 78,65};
int marks[ ] = {90,45,69,85};
Example:
int a[ ]={10,20,40,45,30,12}; /* size is optional */
#include<stdio.h>
int main()
{
int a[ ]={10,20,40,45,30,12};
int i;
printf("Elements of array:\n");
for(i=0;i<6;i++)
printf("%d\t",a[i]);
return 0;
}
Inputtng values from th ekey board: An array can be fillled by inputting values from the
keyboard.
To access elements from the keyboard and store into an array, index need to be changed from 0 to
n-1 that can be done by using a common loop.
int i, int marks[5]
for(i=0;i<size;i++)
scanf(“%d”,&marks[i]);
Assign values to individual elements: The third way is to assign values to individual elements of
the array by using assignmnet operator.
Marks[3]=100;
Here 100 is assigned to the fourth element of the array which is specified as marks[3].
/* Program to read and write array elements */
#include<stdio.h>
int main()
{
int a[5];
int i;
Programming in C Prepared by Mahesh MCA
CSE II 46
printf("Enter 5 integers:\n");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printf("The elements are:\n");
for(i=0;i<5;i++)
printf("%d\t",a[i]);
return 0;
}
4. How do you calculate the length of an array in C language?
An array is a collection of memory locations which can share same data name and same data type
values.
Every element in an array is identified with an index. The index starts from 0. The index of
the last element is n-1, where n is the size of array. Every element in an array is free to participate
in arithmetic, relational and logical operations.
In C language, there is no direct way to get how many elements are there in the array
(length), because all the elements of array have the same size, dividing the total size of the array by
the size of any one of the elements gives the number of elements in the array. Here we use element
0 because it is the only element guaranteed to exist, as arrays must have at least one element.
#include<stdio.h>
int main()
{
int a[5],len;
len=sizeof(a)/sizeof(a[0]);
printf("Length of array %d",len);
return 0;
}
For two dimensional arrays, memory is allocated in terms of table format that contains collection
of rows and columns. So, that double dimensional arrays are useful for matrix representation of
given elements.
For the above example, memory allocation will be:
0 1 2 3
K 1
Let ‘m’ is the row size and ‘n’ is the column size, then a double dimensional array can be defined
as – “Double dimensional array is a collection of m x n homogeneous data elements that are stored
in m x n successive memory locations”.
There are a number of operations that can performed on arrays. These operations include:
Traversing an array
CHAPTER – II STRINGS
A string is a one dimensional array of characters terminated by a null (\0) character. The null
character is stored at the end of array of characters to mark the end of the string.
Declaring a String Variable:
To manipulate strings, an array must be declared with character data type. A string can be declared
as follows:
Syntax: char arrayname[size];
Here the ‘size’ is the number of characters in the array.
Example: char name[40]; char city[15]; etc.
Initializing a String Variable:
1. A string of characters can be stored in an array as follows:
In the example-2, the null character is not needed. The compiler automatically inserts
‘\0’ character at the end. So, the conceptual view for the above examples is as shown
below:
N E L L O R E \0
Here, ‘size1’ specifies the number of strings and ‘size2’ refers the number of characters in each
string.
City[0] N E L L O R E \0
V I J A Y A W A D A \0
City[1]
A M A R A V A T H I \0
City[2]
This example reserves three memory locations to store three strings. Each string may
contain ten characters (10 bytes). The conceptual view for the above declaration is above
table.
string character by character, stores into the character array and a terminating character ‘\0’ is
automatically added at the end.
Example:
char x[50];
scanf("%s",x);
Writing a string:
Similar to scanf(), if we give the address of character array with its name and a format specifier %s
to the printf(), the printf() automatically prints the string character by character until the
terminating character ‘\0’.
Example:
printf(“%s”,x);
/* program to read and write a string */
#include<stdio.h>
int main()
{
char x[50];
int i;
printf("Enter any string:");
scanf("%s",x);
printf("The given string:");
printf("%s",x);
return 0;
}
Execution:
Enter any string: Mahesh
The given string: Mahesh
In C language, there are several function are used to manipulate strings. These functions are
included in “string.h” file. The following are some of the most commonly used string functions:
1. Finding the length of a string:
Strlen():
strlen() is a predefined function in the header file “string.h”
By using this function we can find the length of the string.
Strlen() function required one argument of type const char* and from given address it
returns length of the string.
Length of the string is total number of characters including null.
Syntax: strlen(string)
scanf("%s",x);
l=strlen(x);
printf("The length of string %d",l);
return 0;
}
Execution:
Enter any string: Mahesh
The length of string 6
2. Reversing a string:
Strrev():
strrev() is a predefined function defined within the header file “string.h”.
By using strrev function we reverse the given string.
Strrev function require one argument of type char*.
from given address up to null entire content will be arrange in reverse order.
Syntax: strrev(str)
Program for Reversing the length of a string
#include<stdio.h>
#include<string.h>
int main()
{
char x[50];
int i;
printf("Enter any string:");
scanf("%s",x);
strrev(x);
printf("The reverse string %s",x);
printf("%s",x);
return 0;
}
Execution:
Enter any string: Mahesh
The reverse string hsehaM
3. Copying a string:
Strcpy ():
strcpy() is a predefined function defined with in the header file “string.h”
By using ‘strcpy’ function you can copy a string into another string.
‘strcpy’ function require two arguments of type char* i.e an address of a string.
When we are working with strcpy function from given address all source string content will
be copied to destination string position.
Syntax: strcpy(string1, string2);
Here ‘string1’ is destination string and ‘string2’ is source string. The contents of string2 are copied
to string1.
char x[50],y[50];
printf("Enter any string:");
scanf("%s",x);
strcpy(y,x); /* "x" is copied onto "y" */
printf("%s",y);
return 0;
}
Execution:
Enter any string: Mahesh
Mahesh
4. Concatenating a string to another:
Strcat( ) :
strcat() is a predefined function defined within the header file “string.h”
This function appends the contents of one string (source) to another string (destination).
This is called concatenation of two strings.
The contents of the source string are unchanged.
Syntax: strcat(string1, string2);
Where ‘string1’ is destination string and ‘string2’ is source string. The contents of string2 are
appended to string1.
Program for concatenating a string
#include<stdio.h>
#include<string.h>
int main()
{
char x[50],y[50];
printf("Enter the first string:");
scanf("%s",x);
printf("Enter the second string:");
scanf("%s",y);
if(strcmp(x,y)==0)
printf("Equal");
else if(strcmp(x,y)>0)
printf("Biggest string %s",x);
else
printf("Biggest string %s",y);
return 0;
}
Execution:
Enter the 1st string: hello
Enter the 2nd string: sir
The resultant string is hellosir
#include<string.h>
int main()
{
char s[50];
int pos;
printf(“Enter any string in upper case..\n”);
scanf(“%s”,s);
printf(“Enter the position:”);
scanf(“%d”,&pos);
if(pos<1||pos>strlen(s))
printf(“Invalid position”);
else
{
pos--;
s[pos]=s[pos]+32; /* converting a character to lower case */
printf(“The resultant string is %s\n”,s);
}
return 0;
}
Execution:
Enter any string in lower case..
AMERICA
Enter the position:3
The resultant string is AMeRICA
tolower( ) function: It checks whether given character is alphabetic and converts to lowercase.
toupper( ) function: It checks whether given character is alphabetic and converts to uppercase.
C STRING FUNCTIONS:
String.h header file supports all the string functions in C language. All the string functions are
given below.
strcat( ) function: It concatenates two given strings. It concatenates source string at the end of
destination string.
Example:
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
strcat ( str1, str2 ); – str2 is concatenated at the end of str1.
strncat( ) function: It concatenates (appends) portion of one string at the end of another string.
Syntax :char * strncat ( char * destination, const char * source, size_t num );
Example :
strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of str2.
strncat ( str1, str2, 3 ); – First 3 characters of str2 is concatenated at the end of str1.
strlen( ) function counts the number of characters in a given string and returns the integer value.
It stops counting the character when null character is found. Because, null character indicates the
end of the string in C.
strcmp( ) function: It compares two given strings and returns zero if they are same.
If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value.
Syntax :int strcmp ( const char * str1, const char * str2 );
UNIT IV
Programming in C Prepared by Mahesh MCA
CSE II 57
CHAPTER I: POINTERS
1. What is pointer and write how to define a pointer and list few advantages?
A pointer is a variable which holds address of another variable. (Or)
A pointer is a derived data type in C which is constructed from fundamental data type of C
language.
Advantages:
Normal variable stores the value whereas pointer variable stores the address of the variable.
Pointers save the memory allocation.
It promotes direct memory accessing, which improves the performance of the program.
It allows to directly access the array elements using pointer arithmetic’s.
Pointer makes possible to return multiple values to the calling function.
Pointer is the key concept in using complex data structures.
By using pointers we can access a variable which is define outside the function.
By using pointers we can handle the data structures more effectively.
When we are working with the pointers it can increase the execution speed.
Declaring a pointer variable: A pointer variable should be declared before using it. The pointer
variable is declared as follows
Syntax: DtataType *ptr_variable;
int *p;
& ( Address of operator) : & symbol is used to get the address of the variable.
* (Dereference operator) : * symbol is used to get the value of the variable that the pointer is
pointing to. It is used to access the value of memory allocation indirectly through its address.
#include <stdio.h>
#include<conio.h>
int main()
{
int *p; /* declaration of pointer */
int x=345; /* declaration of variable */
p=&x; /* assigning the address to the pointer */
printf("x=%d",x); /* direst accessing */
printf("\nx=%d",*(&x)); /* indirect access through the address */
printf("\nx=%d\n",*p); /* indirect access through the pointer */
return 0;
}
o Increment
o Decrement
o Addition
o Subtraction
Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This
is somewhat different from the general arithmetic since the value of the pointer will get increased
by the size of the data type to which the pointer is pointing.The Rule to increment the pointer is
given below:
new_address= current_address + i * size_of(data type)
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented b
y 4 bytes.
return 0;
}
Decrementing Pointer in C
Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start
pointing to the previous location. The formula of decrementing the pointer is given below:
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate
previous location.
Programming in C Prepared by Mahesh MCA
CSE II 59
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number
from a pointer will give an address. The formula of subtracting value from the pointer variable is
given below:
A null pointer is a special type of pointer that cannot points to any where. Null pointer is assigned
by using the predefined constant NULL; which is defined by several header files including stdio.h,
stdlib.h and alloc.h.
At the time of assigning address of the variable to ptrvariable, type casting must be placed to refer
the data item.
main()
{
int a=10;
double b=3.45678;
void *p;
clrscr();
p=&a;
printf("\nValue 1:%d",*(int *)p);
p=&b;
printf("\nValue 2:%lf",*(double *)p);
}
4.Discuss about pointers and arrays
Write about the pointer representation to an array?
The elements of an array can be efficiently accessed by using pointers. ‘C’ Language
provides two methods of accessing array elements. They are pointer arithmetic method and array
indexing method. However, pointer arithmetic will be faster.
To access array elements, the memory address of first element (base address) of an array
can be assigned to the pointer variable. Using this address we can access the remaining elements of
that array quickly.
Programming in C Prepared by Mahesh MCA
CSE II 61
For example,
main( )
{
int a[20],i , n, *p;
clrscr( );
printf(“How many values “);
scanf(“%d”,&n);
p = a; /* assigns base address of ‘a’ to ‘p’ */
for(i=0;i<=n-1;i++)
scanf(“%d”,(p+i)); /* inputs value to array thru pointer */
for(i=0;i<=n-1;i++)
printf(“%d”,*(p+i)); /* displays value of array thru pointer */
}
Array of Pointers:
A pointer can also be declared as an array. As pointer variable always contains an address,
an array of pointers contains a collection of addresses.
Example:
main( )
{
int a=10, b=20, c=30, d=40;
int *p[4];
p[0] = &a;
p[1] = &b;
p[2] = &c;
p[3] = &d;
}
In the above example, the pointer variable ‘p’ declared as an array with 4 elements. Hence, it can
hold 4 memory addresses of integer variables i.e. a, b, c and d. This can be as shown below:
a b c d
10 20 30 40
#include<stdio.h>
#include<conio.h>
void rectangle(int,int,int*,int*);
int main()
{
int l,b,area,peri;
printf("Enter two sides of rectangle:\n");
scanf("%d%d",&l,&b);
rectangle(l,b,&area,&peri);
printf("Area %d",area);
printf("\nPerimeter %d",peri);
return 0;
}
void rectangle(int x,int y,int *a,int *p)
{
*a=x*y;
*p=2*(x+y);
}
Output:
Elements of array: 22 44 64 65 72 77
This function is used to release (remove) the memory allocated dynamically. When the
memory space is not required, then this function can be used.
Syntax: free(fp); where fp is file pointer
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
int main()
{
int*arr;
int size,i;
clrscr();
printf("\nEnter no of Elements: ");
scanf("%d",&size);
arr=(int*)malloc(sizeof(int)*size);
printf("\nDefault values: ");
for(i=0; i<size; i++)
printf("%d ",*(arr+i));
//printf("%d ",arr[i]);
printf("\nEnter %d values: ",size);
for(i=0; i<size; i++)
{
scanf("%d",&arr[i]);
}
printf("\nArr list is: ");
for(i=0; i<size;i++)
printf("%d ",arr[i]);
getch();
free(arr);
return 0;
}
Enter no of Elements: 5
Example program
#include<iostream.h>
#include<conio.h>
struct employee
{
int eno;
char ename[30];
float sal;
};
void main()
{
struct employee e={105053011,"mahesh",25000};
clrscr();
printf("Employee Number: ",&e.eno);
printf("Employee Name: ",&e.ename);
printf("Employee salary: ",&e.sal);
getch();
}
#include<stdio.h>
struct data
{
int x;
struct
{
int y;
int z;
}p;
};
int main()
{
struct data a;
a.x=10;
a.p.y=20;
a.p.z=30;
printf("x=%d\ny=%d\nz=%d",a.x,a.p.y,a.p.z);
return 0;
}
struct book
{
char name[50];
char author[50];
char publisher[50];
float price;
};
void display(struct book);
int main()
{
struct book x={"Let us C","Kanithkar","BpB",275};
display(x);
return 0;
#include<stdio.h>
union num
{
char ch;
int x;
float y;
};
int main()
{
union num a;
printf(“Size of union variable %d Bytes\n”,a);
a.ch=’p’;
a.x=12356;
a.y=678.65310;
printf(“ch=%c\n”,a.ch);
printf(“x=%d\n”,a.x);
printf(“y=%f\n”,a.y);
return 0;
}
Output:
ch=
x=-239878
y=678.65310
By the above output it is proved that last assigned value (678.65310) is overwritten on previous
values. a.ch prints last byte binary equal of 678.65310, a.x prints last two bytes binary equal of
678.65310.
Union as a generic type:
A union can have different members of different types. At a time we can store any single value
but of any member type. So any variable belongs to union is capable to store the data belongs to
any type called generic type.
#include<stdio.h>
union num
{
char ch;
int x;
float y;
};
int main()
{
union num a,b,c;
a.y=234.768956;
b.x=615;
c.ch='s';
printf("x=%f",a.y);
printf("\ny=%d",b.x);
printf("\nz=%c",c.ch);
return 0;
}
Output: y=234.768951
x=615 ch=s
Structures Unions
The size of variable is the sum of sizes The size of variable is the size of field with
of all the fields maximum size
struct demo
{
float x;
short y;
char ch;
};
struct demo var;
union demo
{
float x;
short y;
char ch;
};
union demo var;
1. The enumeration constants cannot be read from the key board by using “cout”
statement.
2. When we are printing these variables, only the integer values associated with it will
be printed on the screen.
Example
#include <stdio.h>
#include<conio.h>
enum ABC{X,Y,Z};
void main()
{
int a;
a=X+Y+Z; //a=0+1+2;
printf(“a value is ",a);
FILES
Introduction
File is a name of physical memory location in secondary storage area which
contains n number of information. i.e. collection of information.
In implementation when we need to retrieve the input data from secondary storage
area and when we need to redirect the data to secondary storage area then go for
file operations.
Generally secondary IO operations are called file operations.
When we are working with standard I/O devices then it is called standard I/O
operations.
In implementation when we are interact with secondary I/O operations then it is
called file operations.
All file operations related functions are defined in stdio.h i.e <stdio.h>
The files are generally classified into various type based on their data format and
type.
In order to read the data from the file or write the data to the file, first that the file
is to be opened. A file internal has to base references such are BOF (beginning of file)
and EOF (end of file). The beginning of file can be accessed with built in structure
called FILE. It is conglomerate data type, which holds all the attributes of the file,
such are permissions, file type, data and time of access and size in bytes.
C language is supported with rich set of library function, which can handle the
text, binary, and executable file belongs to various systems.
Use of Files: We can use files to store data permanently in the memory. A file is created in the
secondary memory device such as hard disk. When a file is created, we can modify or delete data
present in the file as and when needed.
FILE datatype: To read and write data of files in ‘c’ language, we must use FILE datatype. It
is a structure datatype that is used to create file buffer area.
6. A+(w+r or r+w):- open for append, open for update at the end of the file, or create new file
if the file does not exist.In ‘a+’ mode if the file is not exist then only new file will be created.
Examples:
FILE *f1, *f2;
f1 = fopen(“student.dat”,”w”);
f2 = fopen(“employee.txt”,”r”);
Closing a File ( fclose( ) function) : The opened file must be closed at the end of all input and
output operations done on it. The fclose( ) function is used to close an opened file. Once a file is
closed, we cannot perform any operation on that file until it is opened again.
Syntax: fclose(fp);
Here, ‘fp’ is file pointer that holds the opened file.
2. Write about functions used to perform read/write operations on files?
fputc():
It accepts two arguments that are the character that we want to write on to the file and a file
pointer. It writes the character onto the file through the file pointer.
fputc('g',fp);
It writes ‘g’ onto the file through file pointer fp
fgetc():
This function accepts the file pointer as argument and returns ASCII value of last fetched
(accessed) character from the file.
ch=fgetc(fp);
It reads character by character from the file through file pointer fp and assigns to ch
fputs()
It accepts two arguments that are the string that we want to write on to the file and a file pointer.
It writes string or line of text onto the file through the file pointer.
fputs(“india”,fp);
It writes ‘india’ onto the file through file pointer fp
fgets():
It accepts the address of a character array, the length of text has to fetch from the file and the file
pointer as arguments. It reads the specified length of text from the file and assigns to the
character array whose address has sent as argument.
fgets(str,40,fp);
It reads 40 characters from the file and stores into the string str
fprintf():
It works similar to printf() function but writes on to the file rather console output. It takes
three arguments that are the file pointer, format string and the list of variables. The list of values
of variables would be printed on to the file as per the format string.
fprintf(p,"%d\t%s\t%f\t%d\t%f\n",pcode,pname,price,qty,tot);
It prints the details of a product onto the file “product” through the file pointer “p”
fscanf():
It is similar to the function scanf() but the difference is that, It fetches records row by row
from the formatted text file and stores into the specified variables as per the format specifier.
It accepts the file pointer, format string and the list of addresses of variables as
arguments, read the record from the file through the file pointer and stores into the specified
variables in a sequence.
fscanf(p,"%d%s%f%d%f",&pcode,pname,&price,&qty,&tot);
It fetches a record from the file “product” through the file pointer “p” and stores into the
specified variables.
3. Write programs to write and read the data onto the file?
WRITING DATA TO A FILE
i) fprintf() function: This function is used to store values into the file. It writes values based on
formatting characters specified.
Syntax: fprintf(fp, formatstring, valueslist) ;
Here, ‘fp’ is file pointer. The ‘formatstring’ contains formatting characters. The
‘valueslist’ contains one or more values separated by commas.
Ex: fprintf(fp, “%d %s %f”,rno, snm, avg);
ii) fputc() function: This function is used to store a single character into file.
Syntax: fputc(ch, fp);
Here, ‘ch’ is a character variable or constant and ‘fp’ is file pointer.
iii) fputs() function: This function is used to store a string into the file.
Syntax: fputs(string, fp);
Here, ‘string’ is a string constant or variable. ‘fp’ is file pointer.
Program to write text onto the file
#include<stdio.h>
int main()
{
FILE *p;
char ch;
p=fopen("igate","w"); /* opeing file */
while(1)
{
ch=getchar(); /* reading from Console Input */
if(ch==-1) /* checking end of file */
break;
fputc(ch,p); /* writing on to file */
}
fclose(p); /* closing the file */
printf("1 file is created..");
return 0;
}
i) fscanf() function:
This function is used to read values from the file and stores them into variables. It reads
values based on formatting characters specified.
Syntax: fscanf(fp, formatstring, variablelist) ;
Here, ‘fp’ is file pointer. The ‘format-string’ contains formatting characters. The
‘variable-list’ contains one or more variables.
Ex: fscanf(fp, “%d %s %f”,&rno, snm, &avg);
ii) fgetc() function:
This function is used to read a single character from the file and stores it in a variable.
return 0;
}
DETECTING THE END OF FILE
When reading or writing data from files, we do not know exactly how long the file is. In
C, there are two ways to detect end of file.
i) EOF symbolic constant:
While reading the file in text mode, we can compare each character with EOF symbolic
constant. It is defined in stdio.h with a value -1.
Example:
Example:
#include <stdio.h>
main()
{
FILE *fp;
----
----
While (!feof(fp))
{
----
----
}
}
Example:
#include <stdio.h>
main()
{
FILE *fp;
----
----
if (ferror(fp))
{
Printf(“there is an error in the file”);
}
-----
-----
}
Clearerr() function:
This function is used to clear the EOF and error indicators for the file. It is used because
error indicators are not automatically cleared.
Syntax: clearerr(fp) where fp is file pointer
Example:
#include <stdio.h>
main()
{
FILE *fp;
----
----
if (ferror(fp))
{
clearerr(fp);
}
-----
-----
}
PROGRAMMING IN C LAB
1. Perfect number
AIM: To write a C program find out whether the given number is perfect or not.
ALGORITHM:
Step1: Start
Step2: declare variables n,i,sum0
Step3: print ‘enter a value’
Step4: Read n value.
Step5: for i1 to i<=n/2 in steps repeat step6
Step6: if n%i==0
6.1: sumsum+i
[end for loop]
Step7: if n==sum
7.1: print ‘Given number is perfect number’.
Else
7.2: print ‘Given number is not perfect number’.
Step8: Stop
PROGRAM:
/* 1.PROGRAM TO CHECK WHETHER A GIVEN NUMBER IS
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,sum=0;
clrscr();
printf("enter a value:");
scanf("%d",&n); OUTPUT
for(i=1;i<=n/2;i++) Case1: Enter a value: 8
8 is not perfect number:
Programming in C …………………………..
Prepared by Mahesh MCA
Step1: start
Step2: Declare the variables n,temp,r, sum0
Step3: Write ‘enter a number’.
Step4: Read ‘n’ value.
Step5: tempn
Step6: if(temp>0) then
6.1: rtemp%10
6.2: sumsum+(r*r*r)
6.3: temtemp/10
6.4: got step6
Step7: if(sum==n)
7.1: Print :”Given number is Amstrong number”.
Else
7.2: Print “Given number is not Amstrong number”
Step8: Stop.
PROGRAM:
/* PROGRAM TO CHECK WHETHER A GIVEN NUMBER IS
#include<stdio.h>
#include<conio.h>
void main()
{
int n,temp,sum=0,r;
clrscr(); OUTPUT
printf("enter a value: ");
Enter a value: 153
scanf("%d",&n);
temp=n; 153 is Armstrong number
while(temp!=0) …………………………….
{ Enter a value: 123
r=temp%10;
123 is not Armstrong number
sum=sum+(r*r*r);
AIM: To Write a C program to find the sum of individual digits of a positive integer.
ALGORITHM:
Step1: Start
Step2: declare variables n,sd0
Step3: print ‘enter a value’
Step4: Read ‘n’ value
Step5: while n>0 in steps repeat step6
Step6: sdsd+n%10
6.1: nn/10
[End while loop]
Step7: print ‘ sd’ value for sum of digits.
Step8: Stop
PROGRAM:
/* PROGRAM FOR SUM OF DIGITS OF A NUMBER */
#include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
int n,sd=0; Enter a value: 456
clrscr();
printf("enter a value: "); Sum of digits = 15
scanf("%d",&n);
while(n>0)
{
sd=sd+n%10;
n=n/10;
}
printf("\n sum of digits = %d",sd);
getch();
}
4. FIBONACCI SERIES
10.3: ki+j
[End while loop]
Step11: stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
long int n,n1,n2,t;
int count=0,flag;
clrscr();
printf("Enter Two values: ");
scanf("%ld%ld",&n1,&n2);
for(n=n1; n<=n2; n++)
{
flag=0;
for(t=2; t<n; t++) //t<=sqrt(n) <math.h>
{
if(n%t==0)
{
flag=1;
break;
}
}
if(flag==0&&n!=1)
printf("\n%3d.PRIME=%5d",++count,n);
}
getch();
}
Aim: To write a C program to find largest and smallest number in a list of integers.
Algorithm:
Step1: Start
Step2: declare the variables max,min, i
Step3: declare the array name ‘arr’
Step4: print enter the require values
#include <stdio.h>
#include <conio.h>
#define size 10
int main()
{
int arr[size];
int max,min;
int i;
clrscr();
printf("\nEnter %d Values: ",size);
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
max=min=arr[0];
for(i=1;i<size;i++)
{
OUTPUT
if(arr[i]>max)
{
Enter 10 Values: 10 20 30 40 60 80
max=arr[i];
} 160 5 69 41
if(arr[i]<min)
{ Max=160
min=arr[i];
}
}
printf("\nMaximum number in the list =%d",max);
printf("\nMinimum number in the list=%d",min);
getch();
return 0;
}
7. Addition and Subtraction of matrix
AIM: To Write a C program to find out the addition of given two matrices.
ALGORITHM:
Step1: start
Step2: Declare the variables i,j,m,n
Step3: take an array a[10][10],b[10],c[10][10]
Step4: Write ‘enter the row and column of the matrix’.
Step5: Red m,n values
Step6: Write ‘Enter the elements of matrix A’.
Step7: for i0 to i<m
7.1: for j0 to j<n
7.1.1: Read a[i][j]
7.1.2: ji+1
7.1.3: Repeat Step 7.1
7.2:ii+1
7.3: Repeat step7
Step8: Write ‘Enter the elements of matrix B’.
Step9: for i0 to i<m
9.1: for j0 to j<n
9.1.1: Read a[i][j]
9.1.2: jj+1
9.1.3: Repeat Step 9.1
9.2: ii+1
9.3: Repeat step 9
Step10: calculate the addition of matrix and store c.
10.1: for i0 to i<m
10.1.1: for j0 to j<n
10.1.2: c[i][j]a[i][j]+b[i][j]
10.1.3: jj+1
10.1.4: Repeat step 10.1.1
10.2: ii+1
10.3: Repeat step 10.1.
Step11: Write ‘addition of matrix A and B are’.
Step12: for i0 to i<m
12.1: for j0 to j<n
12.1.1: Read c[i][j]
12.1.2: jj+1
12.1.3: Repeat Step 12.1
12.2: ii+1
12.3: Repeat step 12.
Step13: Write ‘subtraction of matrix A and B are’.
6 6
CSE II Programming in C 88
for(j=0;j<c;j++)
printf("%5d",a[i][j]-b[i][j]);
printf("\n");
}
getch();
}
8. String operations
#include<string.h>
int main()
OUTPUT
{
enter a string: sree chaitanya degree
char str[30];
college
int l;
clrscr(); Sree Chaitanya Degree College
printf("enter a string: ");
gets(str); Lenght of str:17
puts(str);
l=strlen(str);
printf("\nLenght of str:%d",l);
getch();
return 0;
}
9. Searching
Algorithm: To write a C program that implements searching of a given item in a given list.
Step1: start
Step2: take an array
Step3: declare the variables num, I, n, found=0, pos=-1
Step4: print ‘how many elements you want’.
Step5: read n value
Step6: print ‘enter the elements’
Step7: read the elements in the array
Step8: print ‘enter the number that has to be search’
Step9: read the number
Step10: for i0 to i<n repeat step 11
Step11: if arr[i]==num
11.1: found =1
11.2: POS=I
Step12: print ‘given number is found in the array’
[End for loop]
Step13: if found==0
13.1: print’ given number not in the list’
Step14: Stop
PROGRAM
/* PROGRAM TO IMPLEMENT SEARCHING OF GIVEN ITEM IN A GIVEN LIST*/
#include<stdio.h>
Aim: To Write a C++ program to Sort the given set of number in ascending order.
Algorithm:
Step1: Start
Step2: Declare the variables i,j,n
Step3: take an array a[10]
#include <conio.h>
#define size 10
int main()
{
int arr[size];
int i,j,t; OUTPUT
clrscr();
printf("\nEnter 10 Values:"); Enter 10 Values:85 63 74 96 45 65 36
for(i=0;i<size;i++)
scanf("%d",&arr[i]); 12 1 6
for(i=0;i<size;i++)
{ After sorting....1 6 12 36 45 63 65 74 85
for(j=i+1;j<size;j++) 96
{
if(arr[j]<arr[i])
{
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
printf("\nAfter sorting....");
for(i=0;i<size;i++)
printf("%d ",arr[i]);