Programming for Problem Solving Guide
Programming for Problem Solving Guide
INSTITUTEOF
ENGINEERING ANDTECHNOLOGY
(Autonomous)
(GR24A1006)
LECTURE MATERIAL
B. Tech I Year
(CSE,ECE,EEE,IT,CE,ME,DS,AIML)
Preface
The main objective of the course entitled “Programming for Problem Solving” is to make first year
B.Tech students familiar with the Computer Programming concepts and language fundamentals in a
more systematic manner. This material is written according to GRIET GR-24(Autonomous)
syllabus. This book has been prepared to meet the requirements of Programming for Problem
Solving
1. S T G Y.Sandhya
2. D. SugunaKumari
3. R.S.Shalini
4. G.Vandhana
5. N.Sashi Prabha
6. V.Vijay Kumar
7. M.Mounica
8. K.Shoban Babu
9. M.Sunitha
UNIT-I
I/O: Simple input and output with formatted I/O and unformatted I/O.
Representation of Algorithm Flowchart and Pseudo code with Examples: Algorithm:
Algorithm is a finite set of instructions that , if followed accomplishes a particular task. The same problem can be solved
with different methods. So, to solve a problem different algorithms, may be accomplished. Algorithm may vary in time.
User writes algorithm in his / her own language. So ,it can not be executed on computer. Algorithm should be in sufficient
detail that it can be easily translated into any language.
Advantages of Algorithms:
1. It provides the core solution to a given problem. the solution can be implemented on a computer system
using any programming language of user’s choice.
2. It facilitates program development by acting as a design document or a blue print of a given problem
solution.
3. Itensureseasycomprehensionofaproblemsolutionascomparedtoanequivalent computer program.
4. It eases identification and removal of logical errors in a program.
5. It facilitates algorithm analysis to find out the most efficient solution to a given problem.
Disadvantages of Algorithms:
1. In large algorithms the flow of program control becomes difficult to track.
2. Algorithms lack visual representation of programming constructs like flowcharts.
3. Understanding the logic becomes relatively difficult.
Examples:
Flowchart:
A Flowchart is a Visual representation of the sequence of steps for solving a problem. A flowchart is a set of symbols that
indicate various operations in the program .For every process, there is a corresponding symbol in the flowchart. A pictorial
representation of a textual algorithm is done using a flowchart. A flowchart gives a pictorial representation of an algorithm.
The first flowchart is made by John Von Neumann in 1945.It is a symbolic diagram of operations sequence,
dataflow, control flow and processing logic in information processing. The symbols used are simple and easy to
learn. It is a very helpful tool for programmers and beginners.
Purpose of a Flowchart :
1. Provides communication.
2. Provides an overview.
3. Shows all elements and their relationships.
4. Quick method of showing program flow.
5. Checks program logic.
6. Facilitates coding.
7. Provides program revision.
8. Provides program documentation.
9. Advantages of a Flowchart :
10. Flowchart is an important aid in the development of an algorithm itself.
11. Easier to understand than a program itself.
12. Independent of any particular programming language.
13. Proper documentation.
14. Proper debugging.
15. Easy and clear presentation.
Limitations of a Flowchart :
Complex logic.
1. Drawing is time consuming.
2. Difficult to draw and remember.
3. Technical detail.
Ans: Algorithm:
Step 1: Start
Step 2: Input A , B
Step 3 : if A > B then output A else output B
Step 4 : Stop
Flowchart :
Develop an algorithm and flowchart to find the largest among three numbers. Algorithm:
Step 1 : Start
Step 2 :Input A, B, C
Step 3 :If A > B go to step 4 ,otherwise go to step 5.
Step 4 :if A > C go to step 6,otherwise go to step 8 Step 5 :if B > C goto step 7,otherwise go to step 8
Step 6 : print A is largest and go to step9
Step 7 : print B is largest and go to step9 Step 8 : print C is largest and go to step9 Step 9 :Stop
Flowchart:
Simulate an algorithm and flowchart to find factorial of a number Flowchart:
Algorithm:
Step 1:Start
Step 2:Input n
Step 3:Initialize counter variable, i , to 1 and factors = 1
Step 4:if i<= n go to step 5 otherwise go to step 7
Step 5:Calculate factors = factors * i
Step 6:Increment counter variable, i, and go to step 4
Step 7:output factors.
Step 8:stop
Pseudocode:
“Pseudocode is an informal way of programming description that does not require any strict programming language syntax
or underlying technology considerations”.
It is used for creating an outline or a rough draft of a program.
Pseudocode summarizes a program’s flow, but excludes underlying details.
System designers write pseudocode to ensure that programmers understand a software project's requirements and align code
accordingly.
Advantages of pseudocode –
Pseudocode is understood by the programmers of all types.
It enables the programmer to concentrate only on the algorithm part of the code development.
It cannot be compiled into an executable program.
Example of Pseudocode: Bigger of 2 numbers:
Read a, b. If (a >b)
Then print a “is bigger”; Else print b “is bigger”;
endif
Example: Word processor. The text editor could be generalized word processor, but every compiler comes with associated
text editor.
Some of the features of editors are:
Search: To locate and replace statements.
Copy & Paste: To copy and move statements.
Format: To set tabs to align text.
After the program is completed, the program is saved in a file to disk. This file will be input to the compiler, it is known as
source file. The following figure shows the various steps in building a C – program.
Fig: Steps followed to Build a C – program
Compiling Programs: The code in a source file on the disk must be translated into machine language. This is the job of
compiler which translates code in source file stored on disk into machine language. The C compiler is actually two separate
programs: the preprocessor and the translator. The preprocessor reads the source code and prepares it for the compiler. It
scans special instructions known as preprocessor commands. These commands tell the preprocessor to take for special code
libraries make substitutions in the code. The result of preprocessing is called translation unit. The translator reads the
translation unit and writes resulting object module to a file that can be combined with other precompiled units to form the
final program. An object module is the code in machine language. This module is not ready ffor execution because it does
not have the required C and other functions included.
Linking Programs: C programs are made up of many functions.
Example: printf( ) , cos( )… etc. Their codes exists elsewhere , they must be attached to our program. The linker assembles
all these functions, ours and the system ‘s, into a final executable program.
Executing Programs : Once our program has been linked, it is ready for execution. To execute a program, we use
operating system command, such as run to load the program in to main memory and execute it. Getting program
into memory is the function of an Operating System programs called loader. Loader locates the executable
program and reads it into memory. In a typical program execution, the program reads data for processing, either
from user or from file. After the program processes the data, it prepares output. Data output can be to user‘s
monitor or to a file. When program has executed, Operating System removes the program from memory.
Syntax And Logical Errors In Compilation:
In a logic error is a program that causes it to operate incorrectly, but not to terminate abnormally. A logic error produces
unintended or undesired output or other behavior, although it may not immediately be recognized as such.
Logic errors occur in both languages. Unlike a program with a a program with a logic error is a valid program in the
language, though it does not behave as intended. Often the only clue to the existence of logic errors is the production of
wrong solutions, though may sometimes spot them.
Object and Executable Codes:
Object Code:
“Object code is produced when an interpreter or a compiler translates source code into recognizable and executable machine
code”.
Object code is a set of instruction codes that is understood by a computer at the lowest hardware level.
Object code is usually produced by a compiler that reads some higher-level computer
language source instructions and translates them into equivalent machine language instructions.
Executable Code:
“Executable code is a file or a program that indicates tasks according to encoded instructions.”
The CPU can directly execute an executable file to defined tasks.
In other words, it is machine code instructions for a physical CPU.
As a CPU can directly execute an object code, we can also consider the object code as an executable code.
Furthermore, it is sometimes possible to consider or script language instructions as an executable code.
Documentation section:
This section consists of comment tags giving the name of the program, the author and other details of the program which
the programmer would like to use later.
Link section:
It provides instructions to the compiler to link the functions for executing a program.
It is also used to define symbolic constants of the program.
To write a program this section is used to include predefined or user-define header files.
A header file has an extension .h and these are included using “ #include “.
Ex : #include (standard input/output header file)
#inclide (console input/output header file)
#define PI 3.14 (assigns symbolic name PI to the constant value 3.14)
VARIABLES
“A variable in C language is the name associated with some memory location to store data of different types”.
There are many types of variables in C depending on the scope, storage class, lifetime, type of data they store, etc.
A variable is the basic building block of a C program that can be used in expressions as a substitute in place of
the value it stores.
The declaration of variables must be done before they are used in the program.
The syntax for declaring a variable is as follows:
data-type v1,v2,…….,vn;
v1,v2,…,vn are the names of variables. Variables are separated by commas. A declaration statement must
end with a semicolon(;).
Example: int count;
int number, total;
double ratio;
The simplest declaration of a variable is shown in the following code fragment: Example:
/*……………. Program for variable declaration………….*/
int main()
{
//Declarations float x,y;
int code;
short int count; long int amount; double deviation; unsigned n;
char c;
/*…………………………Computation */
}
/*…………………………Program ends… */
Initialization of variable :
Initialize a variable in c is to assign it a starting value. Without this we can't get whatever happened to memory at that
moment.
C does not initialize variables automatically. So if you do not initialize them properly, you can get unexpected results.
Fortunately, C makes it easy to initialize variables when you declare them.
For Example :
int x=45;
int month_lengths[] ={23,34,43,56,32,12,24};
Data types :
A data type is a classification of the type of data that a variable can hold in computer programming. Data type is the type of
the data that are going to access within the program. C supports different data types. Each data type may have pre-defined
memory requirement and storage representation.
C supports 4 types of data types.
1.Primary or (fundamental) data type-(int, char, float, double)
2.User-defined data type-(typedef, structures, unions)
3.Derived data type-(arrays, pointers,)
4.Empty data type -(void).
1.Primary or (fundamental) data type:
All C compilers support 4 fundamentals data types, they are
1.Integer (int)
2.Character(char)
3.Floating (float)
4,Double – precision floating point(double)
Integer types:
Integers are whole numbers with a range of values supported by a particular machine. Integers occupy one word of storage
and since the word size of the machine vary. If we use 16 bit word length the size of an integer value is -32768 to +32767.
In order to control over the range of numbers and storage space, C has 3 classes of integer storage, namely short, long, and
unsigned.
FORMAT
DATA TYPE RANGE SIZE
SPECIFIER
Character type:-
Single character can be defined as a character (char) type data. Characters are usually stored in 8bits of internal storage.
Two classes of char types are there:
signed char, unsigned char.
signed char(or) char 1 byte- -128 to +127 %c
unsigned char 1 byte -0 to 255 %c
3)Floating point types:
Floating point (real) numbers are stored in 32 bits, with 6 digits of precision when accuracy provided by a float number is
not sufficient.
float 4 bytes 3.4e-38 to 3.4e+38 %f
4)Double precision type:
Double datatype number uses 64 bits giving a precision of 14 digits. These are known as double precision numbers. Double
type represents the same data type that float represents, but with a greater precision. To extend the precision further, we may
use long double which uses 80 bits.
Double 8 bytes 1.7e-308 to 1.7e+308 %lf
long double 10 bytes 3.4e-4932 to 1.1e+4932 %lf
Where identifier is user-defined datatype which is used to declare variables that can have one of the values enclosed within
the braces. value1 ,value2,……valuen all these are known as enumeration constants.
Ex:-enum identifier v1, v2,……vn v1=value3;
v2=value1;………
Ex:-enum day {Monday,Tuesday…………. sunday}; enum day week-f,week-end
Week-f = Monday
enum day{Monday…Sunday}week-f, week-end;
CONSTANTS IN C
Constants is the most fundamental and essential part of the C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the same during the entire execution of
the program.Constants are also called literals.Constants can be any of the data types.
It is considered best practice to define constants using only upper-case names.
Types of C constants:
1. Integer constants
2. Real constants
3. Character constants
4. String constants
Integer constants: An integer constant refers to a sequence of digits. There are three types ofintegers, namely, decimal
integer, octal integer and hexadecimal integer. Examples of Integer Constants:
426 ,+786 , -34(decimal integers)
037, 0345, 0661(octal integers)
0X2, 0X9F, 0X (hexadecimal integers)
Real constants:These quantities are represented by numbers containing fractional parts like18.234. Such numbers are called
real (or floating point) constants. Examples of Real
Constants: +325.34426.0
-32.67 etc.
The exponential form of representation of real constants is usually used if the value of the constant is either too small or too
large. In exponential form of representation the real constant is
represented in two parts. The first part present before 'e' is called Mantissa and the part following 'e'is called Exponent.
For ex. .000342 can be written in Exponential form as 3.42e-4.
Single Character constants:Single character constant contains a single character enclosedwithin a pair of single quote
marks.
For ex. 'A',‘5‘,‘;‘,‘ ‗
Note that the character constant‘5‘ is not same as the number 5. The last constant is a blank space.Character constant has
integer values known as ASCII values. For example, the statement
printf(“%d”,a); would print the number 97,the ASCII value of the letter a. Similarly, the statement printf(“%c”,97); would
output the letter ‗a‘
Backslash Character Constants: C supports some special backslash character constants that are used in output functions.
Some of the back slash character constants are as follows:
CONSTANT MEANING
‘\0’ NULL
‘\t’ Horizontal tab
‘\b’ Backspace
‘\a’ Audible bell
‘\n’ New line
‘\v’ Vertical tab
‘\?’ Question mark
‘\’’ Single Quote
‘\”’ Double Quote
‘\\’ Backslash
These character combinations are called escape sequences.
String constants: A string constant is a sequence of character enclosed in double quotes. The characters may be letters,
numbers, special characters and blank space. Examples are: “HELLO!”
“1979”
“welcome” “ !”
“5+3”
“A”
Operators :
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used
in programs to manipulate data and variables.
C operators can be classified into a number of categories, they are
+ Addition c=a+5;a=b+c;h=9+6;
- Subtraction d=e-f;
* Multiplication k=3*g;
NOTE:
Integer division truncates any fractional part.
The modulo division operation produces the remainder of an integer division.
Modulus operator is not valid for real and mixed mode arithmetic.
Integer Arithmetic:
If both the operands in an arithmetic expression are integers, then it is known as integer arithmetic and the result is an
integer.
Real Arithmetic:
If both the operands in an arithmetic expression are real operands, then it is known as real arithmetic and the result is real.
Mixed mode Arithmetic:
If the operands in an arithmetic expression are of different types, then it is known as mixed mode arithmetic and the result is
a bigger type.
Relational Operators:
Relational operators are used for comparing two quantities and used for decision making.
For example we may compare the age of two people or the price of two items which can be done with the help of relational
operators.
An expression containing a relational operator is termed as a relational expression. The
value of a relational expression is either one or zero. It is one if the specified relation is true and zero if the relation is false.
Ex:- 13<34 (true) 23>35(false)
C supports 6 relational operators
Operator Meaning Example Result
== is equal to 8==8 1
When arithmetic expression are used on either side of a relational operator, the arithmetic
expression will be evaluated first and then the results compared, that means arithmetic operators have a higher priority over
relational operators.
Logical Operator:
C has 3 logical operators. The logical operators are used when we want to test more than one condition and make decisions.
The operators are as follows:
The logical operators && and || are used when we test more than one condition and make decisions. Logical expressions
combines two or more relational expressions, is also known as compound relational expression. The truth table for Logical
AND and Logical OR is as below
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Assignment operator:
These operators are used to assign the result of an expression to a variable. The usual assignment operator is “=‟.
In addition ,C has a set of shorthand assignment operators of the form:
v op = exp;
Where v is a variable, exp is an expression and op is a C binary arithmetic operator. The operator op=is known as the
shorthand assignment operator.
++ and - - are increment and decrement operators in C. The operator ++ adds 1 to the operand, while - - subtracts 1.Both are
unary operators. They exist in postfix and prefix forms.
We use the increment and decrement statements in for and while loops extensively Consider the following example when
m=5,then
y=++m; the value of y=6 and m =6. Suppose if we write the above statement as m=5; y= m++; the value of y=5 and m=6.
A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. On the other hand, a
postfix operator first assigns the value to the variable on left and then increments the operand. Likewise for decrement
operator.
Conditional operator:
o/p:- Big will be assigned the value of b (45) since a>b is false.
Bitwise Operators:
C supports a special operator known as bitwise operators for manipulation of data at bit level. These operators are used for
testing the bits or shifting them right to left.
Note: Bitwise operators may not be applied to float or double.
| Bitwise OR x|y
This statement first assigns the value 10 to x, then assigns 5 to y and finally assigns 15. In for loops: for
(n=1 , m=10; n<=m; n++, m++);
sizeof operator: The sizeof is a compile time operator and when used with an operand, it returns the
number of bytes the operand occupies. The operand may be variable, a constant or a data type qualifier.
m = sizeof (sum);
The sizeof operator is normally used to determine the lengths of arrays and structures when their sizes
are not known to the programmer. It is also used to allocate memory space dynamically to variables
during execution of a program
Expressions:
An expression in C is some combination of constants, variables, operators and function calls.
Examples:C= a + b;
tan (angle)
•Most expressions have a value based on their contents.
•A statement in C is just an expression terminated with a semicolon. For Example:
sum = x + y + z;
The rules given below are used to evaluate an expression,
If an expression has parenthesis, sub expression within the parenthesis is evaluated first and arithmetic
expression without parenthesis is evaluated first.
The operators of high level precedence are evaluated first.
The operators at the same precedence are evaluated from left to right or right to left depending on the
associativity of operators.
Expressions are evaluated using an assignment statement of the form:
variable = expression;
Expression evaluation:
A variable is any valid C variable name. When the statement is encountered, the expression is evaluated
first and the result then replaces the previous value of the variable on the left-hand side. All variables
used in the expression must be assigned values before evaluation is attempted
Ex:- x = a*b-c;
y = b/c*a;
z = a-b / c+d;
Ex:- x= a-b/3+c*2-1 when a=9, b=12, and c=3 the expression becomes. x = 9- 12/3 +3*2-1
Step1: x = 9-4+3*2-1
Step2: x = 9-4+6-1
Step3: x = 5+6-1
Step4: x = 11-1
Step5: x = 10
Precedence and Associativity of operators:
Operator precedence:
Various relational operators have different priorities or precedence. If an arithmetic expression contains
more operators,
then the execution will be performed according to their properties. The precedence is set for different
operators in C.
Note:
Precedence rules decide the order in which different operators are applied
Associativity rule decides the order in which multiple occurrences of the same level operators are
applied.
Hierarchy of operators in C :
The higher the position of an operator is, higher is its priority.When an expression contains two operators
of equal priority the tie between them is settled using the associativity of the operators.
Associativity can be of two types—Left to Right or Right to Left
Left to Right means, as you go from left to right in an expression which operator among the two is found,
execute it first.Right to left means, as you go from right to left in an expression which operator among
the two is found, execute it first.
Consider expression a=3/2*5 Here there is a tie between operators of same priority, that is between / and
*. This tie is settled using the associativity of / and *. But both enjoy Left to Right associativity, which
means as you go from left to right / is found so execute it first.
The table clearly shows the associativity and precedence of operators in c.
RANK OPERATORS MEANING ASSOCIATIVIT
Y
1 ++ POSTFIX INCREMENT
-- POSTFIX DECREMENT
() FUNCTION CALL
[] ARRAY SUBSCRIPTING LEFT TO RIGHT
. STRUCTURE AND UNION MEMBER ACCESS
STRUCTUTRE AND UNION MEMBER ACESS
THROUGH POINTER
2 ++ PREFIX INC REMENT
-- PREFIX DECREMENT
+ UNARY PLUS
- UNARY MINUS
RIGHT TO LEFT
! LOGICAL NOT
~ BITWISE NOT
(TYPE) TYPE CAST
* INDIRECTION
& ADDRESS OF
sizeof() SIZE OF
3 * MULTIPLICATION
/ DIVISION LEFT TO RIGHT
% MODULO DIVISION
4 + ADDITION LEFT TO RIGHT
- SUBTRACTION
5 << BITWISE SHIFT LEFT LEFT TO
>> BITWISE SHIFT RIGHT RIGHT
6 < RELATIONAL OPERATORS LESSER
<= LESSER THAN OR EQUAL TO LEFT TO RIGHT
> GREATER THAN
>= GREATER THAN OR EQUAL TO
7 == IS EQUAL TO LEFT TO
!= IS NOT EQUAL TO RIGHT
8 & BITWISE AND LEFT TO RIGHT
12 || LOGICAL OR LEFT TO
RIGHT
13 ?: TERANARY LEFT TO RIGHT
For Example:
i= 2*3/4+4/4+8-2+5/8 i=6/4+4+8-2+5/8 i=1+4/4+8-2+5/8 i=1+1+8-2+5/8 i=1+1+8-2+0
i=2+8-2+0 i=10-2+0 i=8+0
i=8
Type conversion:
It is a process of converting a variable value or a constant value temporarily from one data type to other
data type for the purpose of calculation is known as type conversion.
There are two types of conversions.
Automatic type conversion (or) Implicit conversion.
Type Casting (or) explicit conversion (or) manual conversion.
Implicit: In this lower data type can be converted into higher data type automatically. The figure
below shows the C conversion hierarchy for implicit –type conversion in an expression: The sequence of
rules that are applied while implicit type conversion is as follows: All short and char are automatically
converted into int then
if one of the operands is long double the other will be converted to long double and the result will be
long double.
else, if one of the operand is double, the other will be converted to double and the result will be double.
else, if one of the operand is float ,the other will be converted to float and the result will be float.
else, if one of the operand is unsigned long int, the other will be converted to unsigned long int and the
result will be unsigned long int.
else, if one of the operand is long int, the other is unsigned int then
if unsigned int can be converted into long int, the unsigned int operand will be converted as such and the
result will be long int.
else both operands will be converted to unsigned long int and the result will be unsigned long int.
else if one of the operand is long int ,the other will be converted into long int and the result will be long
int.
else if one of the operand unsigned int ,the other will be converted into unsigned int and the result will be
unsigned int.
The final result of an expression is converted to the type of the variable on the left of the assignment sign
before assigning the value to it. The following changes are introduced during the final assignment.
float to int causes truncation of the fractional part
double to float causes rounding of digits
long int to int causes dropping of the excess higher order bits.
Example : Consider the following variables along with their datatypes: int i,x; float f; double d; longint l;
Explicit:
In this type of conversion, the programmer can convert one data type to other datatype explicitly .Such
conversions are also known as forced conversions or manual conversions or type casting.
Syntax: (datatype) (expression) Expression can be a constant or a variable Ex:y = (int) (a+b) y=
cos(double(x)) double a = 6.5; double b = 6.5;
int result = (int) (a) + (int) (b); result = 12 instead of 13. int a=10;
float(a)> 10.00000 Example:
//converting fahrenheit to Celsius by type casting #include<stdio.h> #include<conio.h> void main()
{
float c,f; clrscr();
printf("\n enter Fahrenheit:"); scanf("%f",&f); c=(float)5/9*(f-32);
printf("\n c=%f",c); getch();
}
getchar ( ):- It reads single character from standard input device. This function don‘t require any
arguments.
Syntax : - char variable _name = getchar( ); Ex:- char x;
x = getchar( );
putchar ( ):- This function is used to display one character at a time on the standard output
device.Syntax:-putchar(variable_name); Ex:- char x;
putchar(x);
program:
void main( )
{
char ch;
printf("enter a character:"); ch=getchar( );
printf("\ncharacter is:"); putchar(ch);
}
Output:
puts( ):- This function is used to display string to the standard O/P device.
isdigit(c) Is c a digit?
isprint(c) Is c a character?
program:
void main()
{
char a,x; printf(“enter char”); a = getchar();
if (isupper(a))
{
x= tolower(a); putchar(x);
}
else
putchar(toupper(a));
}
Output:- enter char A a
Formatted I/O Functions:
Formatted I/O refers to input and output that has been arranged ina particular format. Formatted I/P
functions scanf( ), fscanf()
Formatted O/P functions printf( ) ,fprintf()
scanf( ) :-scanf() function is used to read information from the standard I/P device.
Syntax:-scanf(“controlstring”, &variable_names);
Control string (also known as format string) represents the type of data that the user is going to accept
and gives the address of variable.
(char-%c , int-%d , float - %f , double-%lf).
Control string and variables are separated by commas. Control string and the variables going to I/P
should match with each other.
Ex:-int n; scanf(“%d”,&n);
Inputting Integer Numbers:
The percentage sign(%) indicates that a conversion specification follows. w is an integer number that
specifies the field width of the number to be read and d known as data type character indicates that the
number to be read is in integer mode.
Ex:-scanf(“%2d,%5d”,&a,&b);
The field width of real numbers is not to be specified unlike integers. Therefore scanf reads real numbers
using the simple specification %f.
Ex: scanf(“%f %f”,&x,&y);
Suppose the following data are entered as input: 23.45 34.5 The value 23.45 is assigned to x and 34.5 is
assigned to y.
printf( ): This function is used to output any combination of data. The outputs are produced insuch a
way that they are understandable and are in an easy to use form. It is necessary for the programmer to
give clarity of the output produced by his program.
Syntax:- printf(“control string”, var1,var2……); Control string consists of 3 types of items
Characters that will be printed on the screen as they appear.
Format specifications that define the O/P format for display of each item.
Escape sequence chars such as \n , \t and \b…..
The control string indicates how many arguments follow and what their types are.
The var1, var2 etc..are variables whose values are formatted and printed according to the specifications
of the control string.
The arguments should match in number, order and type with the format specifications
Example Program:
#include<stdio.h>
int main()
{
printf("%s\n","program");
printf("%3s\n","program")
;
printf("%12s\n","program");
printf("%-12s\n","program");
printf("%12.3s\n","program");
return 0;
}
Output
:-
progra
m
progra
m
progra
m program
pro
UNIT-II
Conditional Branching and Loops: Conditional branching with if, if-else, nested if else, else if ladder, switch-case,
loops : for, while, do-while, jumping statements: goto, break, continue.
Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of arrays.
Searching: Basic searching in an array of elements, linear and binary search.
Example :
If we have two expressions being tested in a logical AND operation:
expr1 && expr2
The expressions are evaluated from left to right. If expr1is 0 (FALSE), then expr2would not be evaluated at
all since the overall result is already known to be false.
Truth table for AND (&&)
FALSE=0 TRUE=1
0 X (0) 0
0 X (1) 0
1 0 0
1 1 1
Expr2 is not evaluated in the first two cases since its value is not relevant to the result.
Examples:
1.if (5 || ++x)
{
printf("%d\n",x);
}
2.int x=0;
if(5||2&&++x) printf("%d", x);
• Simple if Statement
• if – else Statement
• Nested if-else statement
• else – if Ladder
• switch statement
• for Loop
• while Loop
• do-while Loop
3. Unconditional control statements
• goto Statement
• break Statement
• continue Statement
• return statement
Conditional Branching:
Conditional statements help you to make decision based on certain conditions. These conditions are
specified by a set of conditional statements having Boolean expressions which are evaluated to a Boolean
value true or false.
When we need to execute a block of statements only when a given condition is true and skip some statements
when the condition is false ,we then use branching or selection control structures in c.
There are the following types of conditional statements in C.
• Simple if statement.
• if…else statement.
• Nested if…else statement.
• else if ladder
• switch case
if statement
if statement is used for branching when a single condition is to be checked. The condition enclosed in if
statement decides the sequence of execution of instruction. If the condition is true, the statements inside if
statement are executed, otherwise they are skipped. In C programming language, any non zero value is
considered as true and zero or null is considered false.
Syntax of if statement
if (condition)
{
statements;
... ... ...
}
Stmt x;
Example of if statement
Example 1: C program to print the square of a number if it is less than 10.
if…else statement is used to make a decision based on two choices. It has the following form:
Whenever if...else statement is encountered, first the condition is tested. It returns either true or false. If the
condition is true, the control enters into the true stmt block. Once, the end of true stmt block is reached, the
control transfers to stmt-x without considering else-body.
If the condition is false, the control enters into the false stmt block by skipping true stmt block. Once, the end
of false stmt block is reached, the control transfers to stmt-x.
Syntax:
if(condition)
{
truestmt block;
}
else
{
falsestmt block;
}
stmt-x;
FLOWCHART
In this syntax,
Output:
enter age 47
person is not retired
#include<stdio.h>
int main()
{
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n%2 == 0)
printf("%d is even",n);
else
printf("%d is odd",n);
return 0;
}
Output:
Enter a number:5 5 is odd
Nested if Statements:
When a if statement is kept inside another if statement, it is called nested if statement. Nested if statements
are used if there is a sub condition to be tested. The depth of nested if statements depends upon the number of
conditions to be checked.
if (condition 1)
{
statements;
if (sub condition 1)
{
statements;
}
statements;
}
else if (condition 2)
{
statements;
if (sub condition 2)
{
statements;
}
statements;
}
... ... ...
... ... ...
else
{
statements;
if (sub condition n)
{
statements;
}
statements;
}
Flow chart:
Example
#include<stdio.h>
int main ( )
{
int a, b,c;
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
Printf(“%d is big\n”,a);
else
printf("%d is big\n", b);
}
else
{
if(c>b)
{
printf("%d is big\n" , c);
else
printf("%d is big\n" , b);
}eturn 0;
}
Output:
10
20
30
30 is big
Example:
Write a c program if the number is even or odd, and then if it is even, whether it is divisible by 4 or not, and
if it is odd, whether it is divisible by 3 or not.
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
if (n % 2 == 0)
{
printf("Even ");
if (n % 4 == 0)
{
printf("and divisible by 4");
}
else
{
printf("and not divisible by 4");
}
}
else
{
printf("Odd ");
if(n % 3 == 0)
{
printf("and divisible by 3");
}
else
{
printf("and not divisible by 3");
}
}
return 0;
}
Output:
4
Even and divisible by 4
It is used when more than one condition is to be checked. A block of statement is enclosed inside if, else if
and else part. Conditions are checked in each if and else if part. If the condition is true, the statements inside
that block are executed. If none of the conditions are true, the statements inside else block are executed. A if
… else if … else statement must have only one if block but can have as many else if block as required. Else
part is optional and may be present or absent.
Example:
#include<stdio.h>
int main()
{
int day;
printf("Enter day number: ");
scanf("%d", &day);
if(day==1)
{
printf("SUNDAY.");
}
else if(day==2)
{
printf("MONDAY.");
}
else if(day==3)
{
printf("TUESDAY.");
}
else if(day==4)
{
printf("WEDNESDAY.");
}
else if(day==5)
{
printf("THURSDAY.");
}
else if(day==6)
{
printf("FRIDAY.");
}
else if(day==7)
{
printf("SATURDAY.");
}
else
{
Printf(“INVALID DAY”);
}
return(0);
}
OUTPUT:
Enter day number: 4
WEDNESDAY
Example Program:
void main()
int m1,m2,m3,avg,tot;
avg=tot/3; if(avg>=75) {
printf("distinction"); }
Output:
switch statement is one of decision-making control-flow statements. Just like else if ladder, it is also used to
make a decision among multiple choices. switch statement has the following form:
Syntax:
switch(<exp>)
{
case<exp-val-1>: statements block-1;
break;
case<exp-val-2>: statements block-2;
break;
case<exp-val-3>: statements block-3;
break;
case<exp-val-N>: statements block-N;
break; default: default statements block;
}
Next-statement;
In this syntax,
• The statement block and break statement can be enclosed with in a pair of curly braces{and}.
• The default along with its statements block is an optional one. The break statement can be placed at the
end of default statements block. The default statements block can be placed at anywhere in the switch
statement. If they are placed at any other place other than at end, it is compulsory to include a break
statement at the end of default statements block.
• Next-statement is a valid C statement.
Whenever, switch statement is encountered, first the value of <exp>gets matched with case values. If suitable
match is found, the statements block related to that matched case gets executed. The break statement at the
end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed and then the control gets transferred
to Next-statement.
Example:
#include <stdio.h>
int main()
{
char gender;
printf("Enter gender (M/m or F/f): ");
scanf("%c",&gender);
switch(gender)
{
case 'M':
case 'm': printf("Male."); break;
case 'F':
case 'f':
printf("Female."); break;
default:
printf("Unspecified Gender.");
}
printf("\n"); return 0;
}
OUTPUT:
Enter gender (M/m or F/f): f Female.
Example Program:
#include<stdio.h>
void main()
{
int a,b,c,ch;
printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
printf("\nEnter the choice:");
scanf("%d",&ch); switch(ch)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
default: printf(“ enter a valid choice \n”);
}
printf("\nThe result is: %d",c);
}
Output: enter the choice 1 Enter two numbers 4 2
6
Use of switch statement:
• while Loop
• do while loop
• for loop
1. while Loop:
The simplest of all the looping structures in c is the while statement. A WHILE loop has one control
expression, and executes as long as that expression is true.
The basic format of the while statement is:
Syntax:
while(condition)
statements;
The while is an entry–controlled loop statement. The condition is evaluated and if the condition is true then
the statements will be executed. After execution of the statements the condition will be evaluated and if it is
true the statements will be executed once again.
This process is repeated until the condition becomes false and the control is transferred out of the loop. On
exit the program continues with the statement immediately after the body of the loop.
#include<stdio.h>
void main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d ",i); i=i+1;
}
}
It is one of the looping control statements. It is also called as exit-controlled looping control statement. i.e., it
tests the condition after executing the do-while loop body.
The main difference between “while” and “do-while” is that in “do-while” statement, the loop body gets
executed at least once, though the condition returns the value false for the first time, which is not possible
with while statement. In “while” statement, the control enters into the loop body only when the condition
returns true.
Syntax:
Initialization statement;
do
statement(s);
}while(<condition>);
next statement;
In this syntax:
While and do are the keywords.<condition>is a relational expression or a compound relational expression or
any expression that returns either true or false. initialization statement, statement(s) and next_statement are
valid ‘c’ statements.
The statements within the curly braces are called as do-while loop body. The updating statement should be
included within the do-while loop body. There should be a semi-colon(;) at the end of while(<condition>).
Whenever “do-while” statement is encountered, the initialization statement gets executed first. After then, the
control enters into do-while loop body and all the statements in that body will be executed. When the end of
the body is reached, the condition is tested again with the updated loop counter value.
If the condition returns the value false, the control transfers to next statement without executing do- while
loop body. Hence, it states that, the do-while loop body gets executed for the first time, though the condition
returns the value false.
Program to print n natural numbers using do while
#include<stdio.h>
void main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
do
{
printf("%d ",i);
i=i+1;
}while(i<=n);
}
Output: enter the range 8
12345678
for(exp1;exp2;exp3)
for-body;
}next_statement;
In this syntax,
for is a keyword. exp1 is the initialization statement. If there is more than one statement, then
the statements must be separated with commas. exp2 is the condition. It is a relational expression
or acompound relational expression or any expression that returns either true or false. The exp3 is the
updating statement. If there is more than one statement then, they must be separated with commas.
exp1, exp2 and exp3 should be separated with two semi-colons. exp1, exp2, exp3, for-body and
next_statement are valid ‘c’ statements. for-body is a simple statement or compound statement or a null
statement.
Whenever “for” statement is encountered, first exp1 gets executed. After then,exp2 is tested. If exp2 is
true then the body of the loop will be executed otherwise loop will be terminated.
When the body of the loop is executed the control is transferred back to the for statement after evaluating
the last statement in the loop. Now exp3 will be evaluated and the new value is again tested
.if it satisfies body of the loop is executed .This process continues till condition is false.
Syntax:
Example Program :
#include<stdio.h>
void main()
{
inti,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
}
Output:
1
12
123
1234
12345
The syntax for a nested while loop statement in C programming language is as follows -
Syntax:
while(outer condition)
{
outer while statements;
while(inner condition)
{
inner while statements;
}
1
12
123
1234
12345
Program1:
#include <stdio.h>
int main ()
{
int i, n, in;
printf ("ENTER A NUMBER ");
scanf ("%d", &n);
i = 1;
while (i <= n)
{
printf ("\n");
in = 1;
while (in <= i)
{
printf ("%d ", in);
in = in + 1;
}
i = i + 1;
}
return 0;
Output:
1
12
123
1234
12345
The syntax for a nested do...while loop statement in C programming language is as follows −
Syntax:
Statements;
do
{
Statements;
do
{
Statements;
}while( condition );
Statements;
}while( condition );
FLOWCHART:
Example:
#include <stdio.h> #include <stdlib.h> int main()
{
int i,j; i=1;
printf("Triangle number pattern\n"); printf("Here your pattern\n");
do{ j=1;
do{ printf("%d",j); j++;
}while(j<=i);
printf("\n"); i++;
}while(i<=9);
getch(); return 0;
}
OUTPUT:
1. Break Statement
2. Continue Statement
3. Goto Statement
4. Return Statement
1. Break Statement :
Break Statement in C is a loop control statement that is used to terminate the loop. There are two usages and
the given statement is explained below.
Inside a Loop: If the break statement is using inside a loop along with the if statement then if the condition
becomes true the loop is immediately terminated and the next statement after the loop starts executing by the
program control.
Inside a Switch Case: If Break Statement in C is using inside a switch case after each switch case then the
break statement terminates a case after executing the case.
In general the break statements we used in the situations where we need to stop the loop execution based on
the condition or not sure how many times the loop is to be iterate. If the break statements using inside the
nested loop, then the break statement breaks the inner loop and starts executing the statement after the inner
loop of the program control continue to the outer loop.
The break statement is written inside the loop. First, the execution of the loop starts.
If the condition for the loop is true, then the body of the loop executes; otherwise, the loop terminates. If the
body of the loop executes, the break condition written inside the body is checked.
If it is true, it immediately terminates the loop; otherwise, the loop keeps executing until it meets the break
condition or the loop condition becomes false.
Example:
#include <stdio.h> int main() {
int i;
for (i = 1; i <= 15; i++) { printf("%d\n", i);
if (i == 10) break;
}
return 0;
}
OUTPUT:
1
2
3
4
5
6
7
8
9
10
The continue jump statement like any other jump statement interrupts or changes the flow of control during
the execution of a program. Continue is mostly used in loops.
Rather than terminating the loop it stops the execution of the statements underneath and takes control to
the next iteration.
Similar to a break statement, in the case of a nested loop, the continue passes the control to the next
iteration of the inner loop where it is present and not to any of the outer loops.
Let’s implement an example to understand how continue statement works in C language.
Syntax for continue statement is: Any loop
{
statement_1; statement_2;
.....
continue;
......
}
next_statement;
Flowchart:
Example:
#include <stdio.h> int main() {
int i, j;
for (i = 1; i < 3; i++) { for (j = 1; j < 5; j++) { if (j == 2)
continue; printf("%d\n", j);
}
}
return 0;
}
Output:
1
3
4
1
3
4
In this program, we see that the printf() instruction for the condition j=2 is skipped each time during the
execution because of continue. We also see that only the condition j=2 gets affected by the continue. The
outer loop runs without any disruption in its iteration.
Flowchart:
Example1:
/*To print numbers from 1 to 10 using goto statement*/ #include <stdio.h>
int main()
{
int number; number=1; repeat:
printf("%d\n",number); number++; if(number<=10)
goto repeat; return 0;
}
OUTPUT:
1
2
3
4
5
6
7
8
9
10
Syntax2:
statements;
if(any-test-condition) goto label-name; statement1; statement2;
label-name: Other statements;
end:
printf("Bye Bye !!!"); return 0;
}
OUTPUT:
Enter an integer number: 0 Bye Bye !!!
In this program, we have two functions that have a return type but only one function is returning a
value[func()] and the other is just used to terminate the function[main()].
The function func() is returning the character value of the given number(here 110). We also see that the
return type of func() is char because it is returning a character value.
The return in main() function returns zero because it is necessary to have a return value here because main
has been given the return type int.
Exit :
The C library function void exit(int status) terminates the calling process immediately. This function does
not return any value.
Output:
Start of the program....
Exiting the program....
ARRAYS
Arrays: One and Two Dimensional arrays, creating, accessing and manipulating elements of arrays.
Searching: Introduction to Searching, Linear Search and Binary Search.
ARRAYS
So far we have used only single variable name for storing one data item. If we need to store multiple copies
of the same data then it is very difficult for the user. To overcome the difficulty a new data structure is
used called arrays.
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of elements are stored contiguously in the
memory under one variable name.
An array can be declared of any standard or custom data type.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100 variables named
as roll1, roll2, roll3, roll100 which is very difficult job. Concept of C
programming arrays is introduced in C which gives the capability to store the 100 roll numbers in the
contiguous memory which has 100 blocks and which can be accessed by single variable name.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
1. When Big Block of memory is reserved or allocated then that memory block is called as Contiguous
Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.
3. Suppose inside memory we have reserved 1000-1200 memory addresses for special purposes then we can
say that these 200 blocks are going to reserve contiguous memory.
1. Two registers are used while implementing the contiguous memory scheme. These registers are base
register and limit register.
2. When OS is executing a process inside the main memory then content of each register are as
Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non- contiguous
allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address from base register
and then it will refer relative address of memory location with respect to base address.
Since an array provides a convenient structure for representing data, it is classified as one of the data
structures in C.
Types of Arrays :
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multi-dimensional arrays.
ONE-DIMENSIONAL ARRAYS:
A list of items can be given one variable name using only one subscript and such a variable is called a
single-subscripted variable or a one-dimensional array.
Like any other variable, arrays must be declared before they are used so that the compiler can
allocate space for them in memory.
Syntax:
The type specifies the type of element that will be contained in the array, such as int, float or char.
● The size indicates the maximum number of elements that can be stored inside the array
For Ex: int number[5];
Declares the number to be an array containing 5 elements. Any subscripts 0 to 4 are valid and the computer
reserves five storage locations as shown below
number[0]
number[1]
number[2]
number[3]
number[4]
Note :
1. Any reference to the arrays outside the declared limits would not necessarily cause an error. Rather, it
might result in unpredictable program results.
2. The size should be either a numeric constant or a symbolic constant.
After an array is declared, its elements must be initialized. Otherwise, they will contain “garbage”. An
array can be initialized at either of the following stages:
● At Compile time
● At run time
COMPILE TIME INITIALIZATION :
We can initialize the elements of arrays in the same way as the ordinary variables when they are declared.
Syntax:
type array-name[size]={list of values};
The values in the list are separated by commas. For example, the statement
int number [5] = { 35, 40, 50, 20, 25 };
Will declare the variable number as an array of size 5 and will assign the value to each element as follows
number[0] number[1] number[2] number3] number[4]
If the number of values in the list is less than the number of elements, then only that many elements will
be initialized. The remaining elements will be set to zero automatically if the array type is numeric and
NULL if the type is char.
For e.g:- float total[5]={0.0,5.2,-10};
Will initialize the first three elements to 0.0, 5.2 and -10.0 and the remaining two elements to zero. If we
have more initializes than the declared size, the compiler will produce an error.
int number[3]={10,20,30,40}; is illegal in C.
The size may be omitted in the declaration statement. In such cases, the compiler allocates enough
space for all initialized elements.
For e.g.-int count[ ]={1,1,1,1};
Will declare the count array to contain four elements with initial values 1. This approach works fine as
long as we initialize every element in the array.
Character arrays may be initialized in a similar manner. Thus the statement char
name[]={‘h’,’e’,’l’,’l’,’o’,’\0’};
Declares the name to be array of five characters, initialized with the string “hello” ending
with the null character. Alternatively we can assign the string literal directly as
char name[]=”hello”;
An array can be explicitly initialized at run time. This approach is usually applied for initializing large
arrays. For example, consider the following segment of C program
for(i=0;i<100;i=i+1)
{ if(i<50)
sum[i]=0.0; else sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to 0 while the remaining 50 are initialize to 1.0
at run time.
We can also use a read function such as scanf to initialize an array. For example, the statements
int x[3];
scanf(“%d%d%d”,&x[0],&x[1],&x[2]);
will initialize array elements with the values entered through the key board.
EXAMPLE PROGRAMS :
1. C Program for deletion of an element from the specified location from an Array #include<stdio.h>
int main()
{
int arr[30], num, i, loc;
printf("\n Enter no of elements:");
scanf("%d", &num);
//Read elements in an array
printf("\n Enter %d elements :", num);
scanf("%d", &loc);
/* loop for the deletion */ while (loc < num)
{
arr[loc - 1] = arr[loc]; loc++;
}
num--;
// No of elements reduced by 1
//Print Array
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);
return (0);
}
Output:
}
return (0);
}
Output:
#include<stdio.h>
int main() {
int arr[30], element, num, i, location;
printf("\n Enter no of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
printf("\n Enter the element to be inserted:");
scanf("%d", &element);
printf("\n Enter the location");
scanf("%d", &location);
//Create space at the specified location
for (i = num; i >= location; i--)
{
arr[i] = arr[i - 1];
} num++;
arr[location - 1] = element;
//Print out the result of insertion
Output:
Enter no of elements: 51 2 3 4 5
Enter the element to be inserted: 6 Enter the location: 2
162345
#include<stdio.h>
int main()
{
int a[30], ele, num, i;
printf("\n Enter no of elements:");
scanf("%d", &num);
printf("\n Enter the values :");
for (i = 0; i < num; i++)
{
scanf("%d", &a[i]);
}
//Read the element to be searched
printf("\n Enter the elements to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location i = 0;
while (i < num && ele != a[i])
{
i++;
}
//If i < num then Match found if (i < num) {
printf("Number found at the location = %d", i + 1);
} else {
printf("Number not found");
}
return (0);
}
Output:
Enter no of elements: 511 22 33 44 55
Enter the elements to be searched: 44 Number found at the location = 4
#include<stdio.h>
int main() {
int arr1[30], arr2[30], i, num;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Accepting values into Array
printf("\n Enter the values:");
for (i = 0; i < num; i++)
{
scanf("%d", &arr1[i]); }
/* Copying data from array 'a' to array 'b */
for (i = 0; i < num; i++)
{
arr2[i] = arr1[i];
}
//Printing of all elements of array
printf("The copied array is:");
for (i = 0; i < num; i++)
printf("\narr2[%d] = %d", i, arr2[i]);
return (0);
}
Output:
Enter no of elements: 5
Enter the values: 11 22 33 44 55 The copied array is: 11 22 33 44 55
Programs for Practice
type array-name[row_size][column_size];
→
Ro ---- 310 275 365
w
0
[1][0] [1][1] [1][2]
→ 10 190 325
Ro ----
w
1
INITIALIZING 2D ARRAYS:
Like the 1D arrays, 2D arrays can be initialized by following their declaration with a list of initial
values enclosed in braces. For example
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of the first row to zero and the second row to one. The initialization is done
row by row. The above statement is equivalently written as int table[2][3]={{0,0,0},{1,1,1}};
by surrounding the elements of each row by braces.
We can also initialize a two-dimensional array in the form of a matrix as shown below:
int table[2][3]={ {0,0,0}, {1,1,1} };
When the array is completely initialized with all values, explicitly, we need not specify the size of
the first dimension. That is, the below statement is permitted. int table[][3]= ]={ {0,0,0}, {1,1,1}
};
If the values are missing in an initialize, they are automatically set to zero.
For example int table[2][3]={ {1,1},{2}};
Will initialize the first two elements of the first row to one, the first element of the second row to
two, and all other elements to zero. When all the elements are to be initialized to zero, the following
short-cut method may be used.
int m[3][5]={{0},{0},{0}};
the first element of each row is explicitly initialized to zero while other elements are automatically
initialized to zero.
Example program:
#include<stdio.h>
void main()
{
int disp[2][3]; int i, j;
for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf("Enter value fordisp[%d][%d]:",i,j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
Printf(“\n Two Dimension Array:”);
for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf("%d", is p[i][j]);
if(j==2)
{
printf("\n");
}
}
}
}
Multidimensional arrays :
C Allows arrays of three or more dimensions. The exact limit is determined by the compiler.
Syntax:
type array-name [s1][s2][s3][sm];
Example Programs:
1.Develop a program to Find the Largest Two Numbers in a given Array and also Calculate their
average
include <stdio.h>
#define MAX 4
void main()
{
}
for (i = 0; i < MAX; i++)
{
printf("%5d", array[i]);
}
printf("\n");
/* assume first element of array is the first larges t*/
largest1 = array[0];
/* assume first element of array is the second largest */
largest2 = array[1];
if (largest1 < largest2)
{
temp = largest1; largest1=largest2; largest2 = temp;
}
for (i = 2; i < 4;i++)
{
if (array[i] >= largest1)
{
largest2= largest1; largest1= array[i];
}
else if (array[i] > largest2)
{
largest2 = array[i];
}
}
Output:
Enter 4 integer numbers 80
23
79
58
Input integer are 80 23 79 58
80 is the first largest 79 is the second largest
Average of 80 and 79 = 79
#include <stdio.h>
void main()
{
int n, c, d, a[100], b[100];
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for (c = 0; c < n ; c++)
scanf("%d", &a[c]);
for (c = n - 1, d = 0; c >= 0; c--, d++)
b[d] = a[c];
for (c = 0; c < n; c++)
a[c] = b[c];
printf("Reverse array is\n");
for (c = 0; c < n; c++)
printf("%d\n", a[c]);
}
3.Program to add two matrices
#include<stdio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],r1,r2,c1,c2,i,j;
printf("\n enter r1,c1,r2,c2");
scanf("%d %d %d %d",&r1,&c1,&r2,&c2);
if(r1==r2&&c1==c2)
{
printf("\n matrix addition possible");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("\n enter a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("\n enter b[%d][%d]:",i,j);
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\n sum of matrix c:");
for(i=0;i<r1;i++)
{
printf("\n"); for(j=0;j<c1;j++)
{ printf("\t%d",c[i][j]);
}
} else
{
printf("\n matrix multiplication is not possible");
} getch();
}
4.Program to multiply two matrices
#include<stdio.h>
#include<conio.h> void main()
{
int a[5][5],b[5][5],c[5][5],r1,r2,c1,c2,i,j,k;
printf("\n enter r1,c1,r2,c2");
scanf("%d %d %d %d",&r1,&c1,&r2,&c2); if(r1==r2&&c1==c2)
{
printf("\n matrix multiplication possible");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("\n enter a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("\n enter b[%d][%d]:",i,j);
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
SEARCHING:
Searching is a technique of finding an element from the given data list or set of the
elements like an array, list, or trees. It is a technique to find out an element in a sorted or
unsorted list. For example, consider an array of 10 elements. These data elements are
stored in successive memory locations. We need to search an element from the array. In
the searching operation, assume a particular element n is to be searched. The element n
is compared with all the elements in a list starting from the first element of an array till
the last element. In other words, the process of searching is continued till the element is
found or list is completely exhausted. When the exact match is found then the search
process is terminated. In case, no such element exists in the array, the process of
searching should be abandoned.
LINEAR SEARCH:
Linear search technique is also known as sequential search technique. The linear search
is a method of searching an element in a list in sequence. In this method, the array is
searched for the required element from the beginning of the list/array or from the last
element to first element of array and continues until the item is found or the entire
list/array has been searched.
Algorithm:
Step 1: set-up a flag to indicate
“element not found”
Step 2: Take the first element in
the list
Step 3: If the element in the list is equal to the desired element
⮚ Set flag to “element found”
⮚ Display the message “element found in the list”
⮚ Go to step 6
Step 4: If it is not the end of list,
⮚ Take the next element in the list
⮚ Go to step 3
Step 5: If the flag is “element not found”
Display the message “element not found”
Step 6: End of the Algorithm
Advantages:
1. It is simple and conventional method of searching data. The linear or sequential
name implies that the items are stored in a systematic manner.
2. The elements in the list can be in any order. i.e. The linear search can be applied on
sorted or unsorted linear data structure.
Disadvantage:
1. This method is insufficient when large number of elements is present in list. 2. It consumes
more time and reduces the retrieval rate of the system.
Time complexity: O(n)
BINARY SEARCH:
Binary search is quicker than the linear search. However, it cannot be applied on unsorted
data structure. The binary search is based on the approach divide-and-conquer. The binary
search starts by testing the data in the middle element of the array. This determines target
is whether in the first half or second half. If target is in first half, we do not need to check
the second half and if it is in second half no need to check in first half. Similarly we repeat
this process until we find target in the list or not found from the list. Here we need 3
variables to identify first, last and middle elements.
To implement binary search method, the elements must be in sorted order. Search is performed
as follows:
4.Repeat the procedure for lower (or upper half) of array until the element is found.
Recursive Algorithm:
Binary Search (a,key,lb,ub) begin Step
1:[initialization] lb=0,ub=n-1;
Step 2:[search for the item] Repeat through step 4 while lower bound(lb) is less than upper bound.
Step 3:[obtain the index of middle value] mid = (lb+ub)/2
Step 4:[compare to search for item] if(key < a[mid]) then ub=mid-1
otherwise if( key > a[mid]) then lb=mid+1;
otherwise if(key==a[mid]) Write “match found” return (mid)
returnBinary_Search(a,key,lb,ub)
Step 5:[unsuccessful search] Write “match not found” Step 6:[end
of algorithm]
/* C program that searches a value in a stored array using linear search.*/
#include<stdio.h>
int linear(int [ ],int,int); void
main( )
{
int a[20], pos = -1, n, k, i; clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:"); for(i=0;
i<n ;i++)
scanf("%d",&a[i]);
printf("\nEnter the element to be searched:"); scanf("%d",&k);
pos=linear(a,n,k); if(pos
!= -1)
printf("\n Search successful element found at position %d",pos); else
printf("\n Search unsuccessful, element not found"); getch( );
}
int linear(int a[ ],intn,int k)
{
int i; for(i=0;i<n;i++)
{ if(a[i]==k)
return(i);
}
return -1;
}
Output:-
Enter the n value : 5
Enter elements for an array : 11 2 23 14 55
Enter the element to be searched: 14
Search successful element found at position : 3
/* C program for recursive binary search to find the given element within array. */
#include<stdio.h>
intbsearch(int [ ],int, int, int); void
main( )
{
int a[20],pos,n,k,i,lb,ub; clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the key value:");
scanf("%d",&k);
lb=0; ub=n-1;
pos=bsearch(a,k,lb,ub);
if(pos!=-1)
printf("Search successful, element found at position %d",pos); else
printf("Search unsuccessful, element not found"); getch( );
}
int bsearch(int a[ ], int k, intlb, intub)
{
int mid; while(ub>=lb)
{
mid=(lb+ub)/2; if(k<a[mid])
ub=mid-1; else if(k>a[mid])
lb=mid+1; else if(k==a[mid])
return(mid);
return(bsearch(a,k,lb,ub));
}
return -1;
}
OUTPUT:
Enter ‘n’ value : 6
Enter elements for an array : 10 32 25 84 55 78 Enter
the element to be searched : 78 Search
successful, Element found at Position : 5
#include<stdio.h>
int bsearch(int [],int,int);
void main( )
{
int a[20],pos,n,k,i; clrscr();
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the key value:");
scanf("%d",&k);
pos=bsearch(a,n,k);
if(pos!= -1)
printf("Search successful, element found at position %d",pos);
else
printf("Search unsuccessful, element not found");
getch( );
}
int bsearch(int a[ ],int n, int k)
{
intlb=0,ub,mid; lb=0; ub=n-1;
while(ub>=lb)
{
mid=(lb+ub)/2; if(k<a[mid])
ub=mid-1; else if(k>a[mid])
lb=mid+1; else if(k==a[mid])
return(mid);
}
return -1;
}
OUTPUT:
Enter n’ value :7
Enter elements for an array : 35 10 32 25 84 55 78
Enter the element to be searched : 25
Search successful, Element found at Position :3
UNIT III
Strings: Introduction to strings, operations on characters, basic string functions available in C - strlen,
strcat, strcpy, strrev, strcmp, String operations without string handling functions, arrays of strings.
The following reasons make functions extremely useful and practically essential:
● Enhances readability.
● Easy to understand.
● Allows Code reusability
● Structured organization.
● Achieves Modular programming
● Easy identification of bugs
● Data abstraction
● Reduction of code repetition so reduces lines of code.
● Best suited for large programs or complex programs.
● It is used to check logical conditions involving multiple objects and just returns the result.
Definition:
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
Main Function in C:
In C, the "main" function is treated the same as every function, it has a return type (and in some cases
accepts inputs via parameters called command line arguments).In C, program execution starts from the
main () function. The only difference is that the main function is "called" by the operating system when
the user runs the program. The main function can in- turn may call other functions. When main calls a
function, it passes the execution control to that function. The function returns control to main when a
return statement is executed or when end of function is reached.
Types of Functions:
Depending on whether a function is defined by the user or already included in C compilers, there are
two types of functions in C programming.
● Standard library functions
● User defined functions Standard.
Library functions:
A user can create their own functions for performing any specific task of program are called
user defined functions. To create and use these function we have to know these 3 elements.
A. Function Declaration
B. Function Definition
C. Function Call
1. Function declaration:
General syntax for function declaration is,
Like any variable or an array, a function must also be declared before it’s used. Function
declaration informs the compiler about the function name, parameters is accept, and its return type. The
actual body of the function can be defined separately. It's also called as Function Prototyping. Function
declaration consists of 4 parts:
● return type
● function name
● parameter list
● terminating semicolon
Return type:
When a function is declared to perform some sort of calculation or any operation and is
expected to provide with some result at the end, in such cases, a return statement is added at the end
of function body. Return type specifies the type of value (int, float, char, and double) that function is
expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
Function name:
Function name is an identifier and it specifies the name of the function. The function name is any valid C
identifier and therefore must follow the same naming rules like other variables in C language.
Parameter list:
The parameter list declares the type and number of arguments that the function expects when it is called.
Also, the parameters in the parameter list receives the argument values when the function is called. They are often
referred as formal parameters.
2. Function Definition:
Note: While defining a function, there is no semicolon (;) after the parenthesis in the function header,
unlike while declaring the function or calling the function.
Functionbody:
The function body contains the declarations and the statements (algorithm) necessary for
performing the required task. The body is enclosed within curly braces {...} and consists of three
parts.
3. Function Header:
The first line of code is called function Header. Intsum(int x, int y). It has three parts
▪ The name of the function i.e. sum
▪ The parameters of the function enclosed in parenthesis
▪ Return value type i.e. int
Signature of a function:
A function’s signature includes the function's name and the number, order and type of its formal
parameters.
Syntax:
return-type function-name (parameters)
{
Declarations
Statements
return value
}
return-type
function-name
parameters
Parameter: The term parameter refers to any declaration within the parentheses following the function
name in a function declaration or definition.
Argument: The term argument refers to any expression within the parentheses of a function call.
Ex:sum(num1, num2); //Call Function Sum With Two Parameters
Calling function: The function which is making a call to any function is called calling function
Called function: The function which is being executed due to function call is known as called function.
Example:
A function depending on whether arguments are present or not and whether a value is returned or not
may belong to any one of the following categories:
When a function has no arguments, it does not receive any data from the calling function.
When a function does not return a value, the calling function does not receive any data from the called
function. Functions that don’t return a value are known as void functions. That is there is no data transfer
between the calling function and the called function.
Example:
#include<stdio.> void add();
void main()
{
add();
}
void add ()
{
int z, a, b ;
printf(“enter values of a and b:\n”);
scanf(“%d%d”,&a,&b);
z=x+y;
printf ("The sum of two numbers is :%d",z);
}
Output:
When a function has arguments data is transferred from calling function to called function. The called
function receives data from calling function and does not send back any values to calling function. Because
it doesn’t have a return value.
Example:
int a, b;
printf(“enter values of a and b:\n”); scanf(“%d%d”,&a,&b);
add(a,b);
}
void add (int x, int y)
{
int z ;
z=x+y;
printf ("The sum of two numbers is :%d", z);
}
Output:
Enter values of a and b: 3 5
The sum of two numbers is: 8
This data is transferred between calling and called function. That means called function receives data
from calling function and called function also sends the return value to the calling function.
Output:
Enter values of a and b: 3 5
The sum of two numbers is: 8
Example
Output:
Enter values of a and b: 3 5
The sum of two numbers is: 8
Call by value:
In call by value a copy of actual arguments is passed to respective formal arguments.
#include<stdio.h>
void swap(int,int); int main ()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(x, y);
printf("After Swapping\nx = %d\ny = %d\n",
return 0;
}
void swap(int a, int b)
{
int temp; temp = a;
a = b;
b = temp;
printf("Values of a and b is %d %d\n",a,b);
}
Output:
Enter the value of x and y 2 3
Before Swapping x= 2, y = 3
After Swapping x= 3, y = 2
Call by reference:
In call by reference the location (address) of actual arguments is passed to formal arguments,
hence any change made to formal arguments will also reflect in actual arguments.
Output:
Enter the value of x and y 2 3
Before Swapping x = 2 y = 3
Values of a and b is 3 2
After Swapping x = 3 , y = 2
Call by Value vs Call by Reference:
Parameters vs Arguments in C:
The term parameter (sometimes called formal parameter) is often used to refer to the variable
as found in the function definition, while argument (sometimes called actual parameter) refers to the
actual input supplied at function call.
To process arrays in a large program, we need to pass them to functions. We can pass arrays in two
ways:
1. Passing individual elements
2. Passing the whole array.
One-dimensional Arrays:
We can pass individual elements by either passing their data values or by passing their
addresses. We pass data values i.e.; individual array elements just like we pass any data value. As
long as the array element type matches the function parameter type, it can be passed. The called
function cannot tell whether the value it receives comes from an array, a variable or an expression.
Ex: Program using call by value
Two-dimensional Arrays:
The individual elements of a 2-D array can be passed in the same way as the 1-D array. We
can pass2-D array elements either by value or by address.
Ex: Program using call by value
void fun1(int ); void main()
{
int a[2][2]={1,2,3,4};
fun1(a[0][1]);
}
void fun1(int x)
{
printf(“%d”,x+10);
}
Passing whole array (idea of call by reference)
As array name is a constant pointer pointing to first element of array (storing the base address),
Passing array name to a function itself indicates that we are passing address of first element of array.
Program:
Two-dimensional array:
When we pass a 2-D array to a function, we use the array name as the actual parameter. The formal
parameter in the called function header, however, must indicate that the array has two dimensions.
Rules:
Program:
#include<stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n1);
else
return 1;
}
Output
Enter a positive integer: 6
Factorial of 6 = 720
Example 2: C program to generate Fibonacci series using recursive functions.
#include<stdio.h>
Void fibo_rec(int n, int f1, int f2);
Void main()
{
int f1=0, f2=1,n;
printf("Enter any number to print the fibonacci series:");
scanf("%d",&n);
if(n<=0)
printf("Enter a valid number\n");
else if(n==1)
printf("fibonacci series is: %d",f1);
else if(n==2)
printf("fibonacci series is: %d %d",f1,f2);
else
{
printf("fibonacci series is: %d %d ",f1,f2);
fibo_rec(n-2,f1,f2);
printf("\n\n");
}
}
Void fibo_rec(int n, int f1, int f2)
{
int f3;
if(n==0)
return;
f3=f1+f2;
printf("%3d ",f3);
fibo_rec(n1,f2,f3);
}
Both recursion and iteration are used for executing some instructions repeatedly until some
condition is true. The same problem can be solved with recursion as well as iteration but still there
are several differences in their working and performance that I have mentioned below.
Recursion Iteration
Definitio Recursion refers to a situation Iteration refers to a situation
n where a function calls itself where some statements are
again and again until some executed again and again using
base condition is reached loops until
Some condition is true
Perform It is comparatively slower Its execution is faster because it
ance because before each function doesn’t use a stack.
call the current state of the
function is stored in the stack.
After the return statement the
previous function state is again
restored from the stack.
Memory Memory usage is more as stack Memory usage is less as it doesn’t
is use
used to store the current stack.
function state.
Code Size of code is comparatively Iteration makes the code size
Size smaller in recursion. bigger.
Limitations of recursion:
o Slower than its iterative solution.
o For each step we make a recursive call to a function. ...
o May cause stack-overflow if the recursion goes too deep to solve the problem.
o Difficult to debug and trace the values with each step of recursion.
Storage classes in C:
Variables in C differ in behavior. The behavior depends on the storage class a variable may assume.
From a C compiler's point of view, a variable name identifies some physical location within the
computer where the string of bits representing the variable's value is stored. There are four storage
classes in C. Storage classes specify the scope of objects .We define the storage class of an object using
one of four specifiers.
Keyword Auto
Storage Memory
Default initial An unpredictable value, which is often called a garbage value.
value
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is
defined
Following program shows how an automatic storage class variable is declared, and the fact that if the
variable is not initialized it contains a garbage value.
Ex:
Void main( )
{
auto int i, j ;
printf ("\n%d %d", i, j) ;
}
When you run this program you may get different values, since garbage values are unpredictable. So
always make it a point that you initialize the automatic variables properly, otherwise you are likely to
get unexpected results. Scope and life of an automatic variable is illustrated in the following program.
void main( )
{
auto int i = 1 ;
{
auto int i = 2 ;
{
auto int i = 3 ;
printf ("\n%d ",i) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
Output:
The features of a variable defined to have a static storage class are as under:
Keyword Static
Storage Memory
Default initial Zero.
value
Scope Local to the block in which the variable is defined.
Life Value of the variable persists between different function calls.
Keyword Extern
Storage Memory
Default initial Zero.
value
Scope Global
Life As long as the program execution does not come to end.
External variables differ from those we have already discussed in that their scope is global, not local. External
variables are declared outside all functions, yet are available to all functions that care to use them. Here is an
example to illustrate this fact.
Ex:
#include<stdio.h>
extern int i;
void main()
{
printf(“i=%d”,i);
}
Keyword Register
Storage CPU Registers
Default initial An unpredictable value, which is often called a garbage value.
value
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is
defined.
A value stored in a CPU register can always be accessed faster than the one that is stored in memory.
Therefore, if a variable is used at many places in a program it is better to declare its storage class as
register. A good example of frequently used variables is loop counters. We can name their storage class
as a register.
Ex:
void main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}
Scope rules in C.
Scope: Scope defines the visibility of an object.it defines where an object can be referenced. Scope of
a variable is the part of program in which it can be used
Scope rules
The rules are as under:
1. Use static storage class only if you want the value of a variable to persist between different function
calls.
2. Use register storage class for only those variables that are being used very often in a program.
Reason is, there are very few CPU registers at our disposal and many of them might be busy doing
something else. Make careful utilization of the scarce resources. A typical application of register
storage class is loop counters, which get used a number of times in a program.
3. Use extern storage class for only those variables that are being used by almost all the functions in
the program. This would avoid unnecessary passing of these variables as arguments when making a
function call. Declaring all the variables as extern would amount to a lot of wastage of memory space
because these variables would remain active throughout the life of the program.
4. If we don’t have any of the express needs mentioned above, then use the auto storage class. In fact
most of the time we end up using the auto variables, because often it so happens that once we have
used the variables in a function we don’t mind losing them
STRINGS
INTRODUCTION:
A string is a sequence of characters that is treated as a single data item. Any group of
characters defined between double quotation marks is a string constant.
Example: “hello world”.
“123ase$”
The common operations performed on character strings include:
● Reading and writing strings
● Combining strings together
● Copying one strings to another
● Comparing strings for equality
● Extracting a portion of a string
● C does not support strings as a data type. However, it allows us to represent strings as character arrays.
The general form of declaration of a string variable is:
char string_name[size];
the size determines the number of characters in the string_name. for example
char city[10];
char name[30];
● when the compiler assigns a character string to a character array, it automatically supplies a null
character(‘\0’) at the end of the string. Therefore, the size should be equal to the maximum number of
characters in the string plus one.
● Like numeric arrays, character arrays may be initialized when they are declared. C permits a character
array to be initialized in either of the following two forms:
char city[9]=”NEW YORK”;
char city[9]={‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};
● C also permits us to initialize a character array without specifying the number of elements. In such
cases, the size of the array will be determined automatically, based on the number of elements
initialized.
For example
char string[]={‘G’,’O’,’O’,’D’,’\0’};
defines the array string as a five element array.
● We can also declare the size much larger than the string in the initialize. That is,the statement.
char str[10]=”GOOD”;
is permitted. In this case,the computer creates a character array of size 10, places the value “GOOD” in it,
terminates with the null character, and initializes all other elements to NULL.
G O O D \0 \0 \0 \0 \0 \0
However, the following declaration is illegal
char str2[3]=”GOOD”;
This will result in a compile time error.
Note: we cannot separate the initialization from declaration.
That is, char str[5]; Str=”GOOD” is not allowed.
Disadvantage: scanf terminates its input on the first white space it finds.
e.g.- if enters new York then only new will be read in array name.
We can also specify the field width using the form %ws in scanf for reading a specified number
of characters from the input string.
E.g.- scanf(“%ws”,name);
If w is equal or greater than the number of characters typed, then entire string will be stored in the variable
If w is less, then excess characters will be truncated and left unread.
E.g.-scanf(“%6s”,name)
griet---reads entire string
gokaraju--- reads only gokara
Reading a Line of Text:
%s and %ws can read only strings without whitespaces. That is, they cannot be used for reading a
text containing more than one word. However, C supports a format specification known as the edit
set conversion code%[..] that can be used to read a line containing a variety of characters, including
whitespaces. For example
char line[80];
scanf(“%[^\n]”,line);
printf(“%s”,line);
Will read a line of input from the keyboard and display the same on the screen.
Example:
#include<stdio.h>
void main()
{
char line[50],ch;
int i=0;
printf(“\n press enter at the end of input”);
do
{
ch=getchar();
line[i]=ch;
i++;
}
while(ch!=’\n’);
i=i-1;
line[i]=’\0’;
printf(“%s”,line);
}
another more convenient method of reading a string of text containing whitespaces is to use the library
function gets available in the <stdio.h> header file.
syntax:gets(str);
str is a string variable, gets function reads a characters into str from the keyboard until a new- line character
is encountered and then appends a null character to the string.
unlike scanf, it does not skip whitespaces.
Example: char line[80];
gets(line);
printf(“%s”,line);
The last two statements can be combined as follows printf(“%s”, gets(line));
We can also specify the precision with which the array is displayed. For instance, the specification %10.4
indicates that the first four characters are to be printed in a field width of 10 columns. Left- justified.
Features of %s specifications:
● When the field width is less than the length of the string, the entire string is printed.
● The integer value on the right side of the decimal point specifies the number of characters to
be printed.
● When the number of characters to be printed is specified as zero, nothing is printed.
● The minus sign in the specification causes the string to be printed left-justified.
● The specification %.ns prints the first n characters of the string.
Example:
Write a program to store the string and display the string under various format specifications.
#include<stdio.h>
void main()
{
char str[14]=”good morning”;
printf(“%14s”,str);
printf(“%4s”,str);
printf(“%14.4s”,str);
printf(“%-14.4s”,str);
printf(“%14.0s”,str);
printf(“%.3s”,str);
printf(“%s”,str);
}
Output:
good morning good morning good
good
goo
good morning
The function putchar requires one parameter. This statement is equivalent to:
printf(“%c”,ch);
We can use this function repeatedly to output a string of characters stored in an array using a loop.
Example:
Another and more convenient way of printing string values is to use the function puts declared in the header
file <stdio.h>.
Syntax:
puts(str); where str is a string variable containing a string value, this prints the value of
the string variable str and then moves the cursor to the beginning of the next
line on the screen.
ARITHMETIC OPERATIONS ON CHARACTERS:
C allows us to manipulate characters the same way we do with numbers. Whenever a character
constant or character variable is used in an expression, it is automatically converted into an integer value
by the system.
For e.g.-
x=‘a’;
printf(“%d”,x);
Will display the number 97 on the screen.
x=‘a’-1;
We can convert a character digit to its equivalent integer value using x= character-’0’
E.g.- int x ;
x= ‘7’-’0’;
printf(“%d”,x)
prints x=7 // ASCII value of 7 = 55
ASCII value of 0=48
The C library supports a function atoi (string) that converts a string of digits into their integer values
e.g.- number =“1988”;
year=atoi(number)
The function converts the string constant “1988”, to its numeric equivalent 1988.
Present in header file <stdlib.h>.
C does not provide operators that work on strings directly like :
str1=“ABC”;
str2=str1; is invalid
The C library supports a large number of string-handling functions that can be used to carry
out many of the string manipulations. Following are the most commonly used string-handling
functions.
Function Action
Strcat() Concatenates two strings
Strcmp() Compares two strings
Strcpy() Copies one string over another
Strlen() Finds the length of a string excluding null character
Strrev() Reverse a string
strcat() Function:
The strcat function joins two strings together. it takes the following form:
strcat(string1, string2);
String1 and string2 are character arrays. When the function strcat is executed, string2 is appended to
string1. It does this by removing the null character at the end of string1 and placing string2 from
there. The string at the string2 remains unchanged. For example consider the following three strings:
V E R Y \0 \0
str1
G O \0
str2
V E R Y G O \0
We must make sure that the size of str1 to which str2 is appended is large enough to accommodate
the final string. strcat function may also append a string constant to a string variable. the following
is valid:
strcat(str1,”good”);
C permits nesting of strcat functions. For example, the statement
strcat(strcat(str1,str2),str3);
Is allowed and concatenates all the three strings together. The resultant string is stored in str1.
strrev() function:
strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given below.
char *strrev(char *string);
Example:
string “Hello” is reversed using strrev( ) function and output is displayed as “olleH”.
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char s[100];
printf("Enter a string to reverse:\n"); gets(s);
strrev(s);
printf("Reverse of the string: %s\n", s);
}
Output:
Enter a string to reverse: rajesh
Reverse of the string: hsejar
strcmp() Function:
The strcmp function compares two strings identified by the arguments and has a value 0 if
they are equal. If they are not, it has the numeric difference between the first nonmatching characters
in the strings. It takes the form:
strcmp(str1,str2);
str1 and str2 may be string variables or string constants.
Ex:
#include<stdio.h>
#include <string.h>
int main()
{
char str1[20],str2[20];
printf("Enter 1st string:");
gets(str1); printf("Enter 2nd string:");
gets(str2); if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal")
return 0;
}
strcpy() Function:
The strcpy() function works almost like a string-assignment operator. It takes a form:
strcpy(str1,str2);
And assigns the contents of str2 to str1. Str2 may be a character array variable or a string constant. For example:
strcpy(city, “DELHI”); will assign the string “DELHI” to the string variable city.
Similarly, the statement strcpy(city1,city2) will assign the contents of the string variable city2 to the string
variable city1.
The size of the array city1 should be large enough to store the contents of city2
Ex:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "C programming";
char str2[20];
strcpy(str2, str1);
puts(str2);
return 0;
}
strlen() Function:
This function counts and returns the number of characters in a string. It takes the form
n=strlen(string)
Where n is an integer variable, which receives the value of the length of the string.
Example:
Write a program that reads 2 strings s1, s2, and check whether they are equal or not, if they
are not, join them together. Then copy the contents of s1 to the variable s3. At the end, the program
should print the contents of all the 3 variables and their lengths.
#include<stdio.h>
void main()
{
char s1[20],s2[20],s3[20];
int x,l1,l2,l3;
printf("\n enter two strings constants:");
scanf("%s%s",s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{
printf("\n strings are not equal");
strcat(s1,s2);
}
else
printf("\n strings are equal");
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf("\ns1=%slength=%d characters",s1,l1);
printf("\n s2=%s length=%d characters",s2,l2);
printf("\n s3=%s length=%d characters",s3,l3);
}
Output:
Enter two strings constants: welcome students strings are not equal
string length:
#include<stdio.h>
void main()
{
char str[30];
int i,len=0;
printf("\n enter the string");
gets(str);
for(i=0;str[i]!='\0';i++)
len++;
printf("\n the total no.of characters in the given string is:%d",len-1);
getch();
}
String concatenation
#include <stdio.h>
void main()
{
char str1[50], str2[50], i, j;
printf("\nEnter first string: ");
scanf("%s",str1);
printf("\nEnter second string: ");
scanf("%s",str2);
for(i=0; str1[i]!='\0'; ++i);
for(j=0; str2[j]!='\0'; ++j, ++i)
{
str1[i]=str2[j];
}
str1[i]='\0';
printf("\nOutput: %s",str1);
}
String copy
#include<stdio.h>
void main()
{
char str1[30],str2[30];
int i;
printf("enter the string 1:");
gets(str1);
for(i=0;str1[i]!='\0';i++)
str2[i]=str1[i];
str2[i]='\0';
printf("the string after copy is :");
puts(str2);
}
string reverse
#include<stdio.h>
void main()
{
char str1[20],str2[20];
int i,len=1,j=0;
printf("\n enter the string");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
{
len++;
}
printf("the length of the string is:%d",len);
for(i=len-1;i>=0;i--,j++)
str2[j]=str1[i];
str2[j]='\0';
printf("the reverse of a given string is %s",str2);
}
String comparison
#include<stdio.h>
void main()
{
char str1[30],str2[30];
int i,j,flag=0;
printf("enter the strings to be compared:");
scanf("%s %s",str1,str2);
for (i=0,j=0;str1[i]!='\0'||str2[i]!='\0';i++,j++)
{
if(str1[i]!=str2[j])
{
flag=1; break;
}
}
if(flag==0)
printf("the two strings are equal"); else
printf("the two strings are not equal");
}
Array of Strings:
We often use list of character strings, such as a list of the names of students in a class, list of the names
of employees in an organization etc. A list of names can be treated as a table of strings and a two-dimensional
character array can be used to store the entire list. For example, a character array city[5][15] may be used to
store a list of 30 city names, each of length not more than 15 characters. e.g.-
C H A N D I G A R h \0
M A D R A S \0
A H M E D A B A D \0
H Y D E R A B A D \0
B O M B A Y \0
This table can be conveniently stored in a character array city by using the following declaration:
char city[ ][ ]= { “CHANDIGARH”, “MADRAS”, “AHMEDABAD”, “HYDERABAD”, “BOMBAY”};
Example:
#include<stdio.h>
int main()
{
char city[20][20];
int i,n;
printf("Enter no. of cities:");
scanf("%d",&n);
printf("Enter %d cities names:\n",n);
for(i=0;i<n;i++)
scanf("%s",&city[i]);
printf("\nThe cities are:\n");
for(i=0;i<n;i++)
printf("%s\n",city[i]);
return 0;
}
Output:
Enter no. of cities: 4
Enter 4 city names: Madras
Hyderabad
Goa
Bangalore
Introduction to pointers:
Pointers are like special utilities, which make it easy to map around in a program
code. Unlike other variables, pointers store the addresses of other variables.
What are Pointers in C?
The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer. The size of the
pointer depends on the machine architecture.
1. If pointers are pointed to some incorrect location then it may end up reading a wrong
value.
2. Erroneous input always leads to an erroneous output
3. Segmentation fault can occur due to uninitialized pointer.
4. Pointers are slower than normal variable
5. It requires one additional dereferences step.
6. If we forgot to deallocate a memory then it will lead to a memory leak.
7. There is always a chance of dangling pointers and wild pointers.
CREATION OF POINTERS
A pointer is a variable that stores the memory address of another variable as its value.
A pointer variable points to a data type (like int) of the same type, and is created with the *
operator. The address of the variable you are working with is assigned to the pointer.
DECLARATION OF POINTER:
In C, every variable must be declared for its type before it is used in the program. Since
pointer variable contain addresses that belong to a specific data type, they must be declared
and initialized.
Declaration:
The declaration of a pointer variable takes the following form: data type *pointer_name;
This tells the compiler three things about the variable pointer_name:
INITIALIZATION OF POINTERS:
In C, there are two equivalent ways to access and manipulate a variable content –
1. Direct Access
2. Indirect Access
Direct access: We use directly the variable name to get its value.
Indirect access: We use a pointer to the variable and through an indirection operator access
the variable.
Example Program:
// ACCESSING VARIABLES THROUGH POINTER
#include <stdio.h>
int var = 1;
int *ptr; // declaration of pointer
int main( )
{
ptr = &var; //Initialization of pointer
printf("\nDirect access, var = %d", var);
printf("\nIndirect access, var = %d", *ptr); // accessing
/* Display the address of var two ways */
printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);
*ptr=48; // modifying by accessing indirectly
printf("\nIndirect access, var = %d", *ptr);
return 0;
}
Output:
Direct access, var = 1
Indirect access, var = 1
The address of var = 4202496
The address of var = 4202496
Indirect access, var = 48
Example:
int x; // the notation &x means "address of x"
//This is the best way to attach a pointer to an existing
variable: int * ptr; // a pointer
intnum; // an integer
ptr = # // assign the address of num into the pointer
// now ptr points to "num"!
Example Program:
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;
printf("value of number is %d, Address of number is %u",*p,p);
return 0;
}
Output
value of number is 50, address of number is fff4
Example Program:
// TO IMPLEMENT NULL POINTER IN C
#include <stdio.h>
int main()
{
// Null Pointer
int *ptr = NULL;
printf("The value of ptr is %p", ptr);
return 0;
}
Output :
The value of ptr is (nil)
Note:
Void Pointer:
Void pointer is a specific pointer type – void * – a pointer that points to some data location
in storage, which doesn’t have any specific type. Void refers to the type. Basically the type
of data that it points to is can be any. If we assign address of char data type to void pointer it
will become char Pointer, if int data type then int pointer and so on. “Any pointer type is
convertible to a void pointer hence it can point to any value.”
The void pointer in C is a pointer that is not associated with any data types. It points to some
data location in the storage. This means that it points to the address of variables. It is also
called the general purpose pointer or generic pointer. In C, malloc() and calloc() functions
return void * or generic pointers.
Note:
1. void pointers cannot be dereferenced.
2. It can however be done using typecasting the void pointer.
3. Pointer arithmetic is not possible on pointers of void due to lack of concrete value
and thus size.
Example Program:
// TO IMPLEMENT VOID POINTER IN C
#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;
void *ptr;//A void pointer
ptr = &x;
// (int*)ptr - does type casting of void
// *((int*)ptr) dereferences the typecasted
// void pointer variable.
printf("Integer variable is = %d", *( (int*) ptr) );
// void pointer is now float
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr)); return 0;
}
Output:
Integer variable is = 4
Float variable is=
5.500000
Refer void pointer article for details.
Dangling Pointer:
A pointer pointing to a memory location that has been deleted (or freed) is called dangling
pointer. There are three different ways where Pointer acts as dangling pointer.
Wild Pointer:
A pointer which has not been initialized to anything (not even NULL) is known as wild
pointer. A wild pointer is only declared but not assigned an address of any variable. They are
very tricky, and they may cause segmentation errors.
Example Program:
// TO IMPLEMENT WILD POINTER IN C
int main()
{
int *p; /* wild pointer */
int x = 10;
// p is not a wild pointer now
p = &x;
return 0;
}
What are the operations possible on pointers?
Pointers directly store address in them and they indirectly point to values stored by the
variables they point to.So the possible or allowed or valid operations on pointers is called
pointer arithmetic.
It is of two types –
1. Pointer address arithmetic – Pointer arithmetic
2. Pointer value arithmetic – Pointer Expressions
Address arithmetic is a method of calculating the address of an object with the help of
arithmetic operations on pointers and use of pointers in comparison operations.A pointer in c
is an address, which is a numeric value. Therefore, you can perform arithmetic operations on
a pointer just as you can on a numeric value. There are four arithmetic operators that can be
used on pointers: ++, --, +, and -
Valid operations:
The operations possible on addresses stored in pointers are –
Invalid operations:
#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;
p=p-3;
printf("After increment: Address of p variable is %u \n",p);
// in our case, p will get incremented by 4 bytes.
printf("After Decrement: Address of p variable is %u \n",p);
return 0;
}
Output:
Pointer Expressions:
Like other variables pointer variables can be used in expressions.
If p1 and p2 are properly declared and initialized pointers, then the following statements are
valid:
Y=*p1**p2;
Sum=sum+*p1;
Z=5*-*p2/*p1;
*p2=*p2+10;
*p1=*p1+*p2;
*p1=*p2-*p1;
Example Program:
#include <stdio.h>
int main()
{
int m = 5, n = 10, o = 0;
int *p1 ,*p2;
p1 = &m; //printing the address of m
p2 = &n; //printing the address of n
printf("\n *p1 = %d *p2 = %d",*p1,*p2);
o = *p1+*p2;
printf("\n *p1+*p2 = %d", o);
o = *p1-*p2;
printf("\n *p1 - *p2 = %d", o);
printf("\n *p1**p2 = %d", *p1**p2);
printf("\n ++*p1 = %d", ++*p1);
printf("\n *p2-- = %d", *p2--);
return 0;
}
Output:
*p1 = 5 *p2 = 10
*p1+*p2 = 15
*p1 - *p2 = -5
*p1**p2 = 50
++*p1 = 6
*p2-- = 10
What is pointer to pointer?
POINTER TO POINTER
Example Program:
//POINTER TO POINTER IN C
#include <stdio.h>
int main ( ) {
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var; /* take the address of var */
pptr = &ptr; /* take the address of ptr using address of operator & */
/* take the value using pptr */
printf("VARIABLE var = %d\n",var );
printf("POINTER : *ptr = %d\n",&ptr,ptr,*ptr );
printf("POINTER TO POINTER : **pptr = %d\n",**pptr);
return 0;
}
Output:
Illustration:
What is size of pointer?
Any Pointer stores address. Addresses are always numbers and it can’t be a character,
a string or real/floating/double numbers.The size of the pointer basically depends on
the architecture of the systemin which it is implemented. For example the size of a
pointer in 32 bit is 4 bytes (32 bit) and 8 bytes (64 bit) in a 64 bit machines.
Irrespective of their data types, the size of pointer is fixed / constant and same for all
types of pointers. Size of a pointer is fixed, it doesn't depend on the data type it is
pointing to. We can use size of operator to get the size of a pointer.
The size of pointer variable is independent of the data type of the variable it is
pointing to because at the end it is pointing to a memory location.
Hence the size of char pointer, int pointer, float pointer, NULL pointer etc are all
same.
Size of int pointer = Size of char pointer = Size of float pointer = Size
of any other type of pointer.
Example Program:
#include<stdio.h>
int main()
{
int *p1;
char *p2;
float *p3;
printf("\n The size of integer pointer = %d",sizeof(int *));
printf("\n The size of character pointer = %d",sizeof(p2));
printf("\n The size of float pointer = %d",sizeof(p3));
printf("\n The size of double pointer = %d",sizeof(double *));
return 0;
}
Output:
The size of integer pointer = 8
The size of character pointer = 8
The size of float pointer = 8
The size of double pointer = 8
These type of pointers are the one which cannot change address they are pointing to.
This means that suppose there is a pointer which points to a variable (or stores the address of
that variable). Now if we try to point the pointer to some other variable (or try to make the
pointer store address of some other variable), then constant pointers are incapable of this.
Note: However, these pointers can change the value of the variable they point to but cannot
change the address they are holding.A constant pointer which points to a variable cannot
be made to point to any other variable.
Example Program:
#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 0;
int *constptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
Output :
Error
In function ‘main’:
constptr.c:7: error: assignment of read-only variable ‘ptr’
We assigned an address to a constant pointer and then tried to change the address by
assigning the address of some other variable to the same constant pointer that results in an
error.
A pointer to constant is a pointer through which the value of the variable that the pointer
points cannot be changed. The address of these pointers can be changed, but the value of the
variable that the pointer points cannot be changed.
The qualifier const can be applied to the declaration of any variable to specify that its value
will not be changed. const keyword applies to whatever is immediately to its left. If there is
nothing to its left, it applies to whatever is immediately to its right.
As evident from the name, a pointer through which one cannot change the value of variable it
points is known as a pointer to constant. These type of pointers can change the address they
point to but cannot change the value kept at those address.
A pointer to constant is defined as:
const<type of pointer>* <name of pointer>
An example of definition could be :
const int* ptr;
Example Program:
#include<stdio.h>
int main(void)
{
int var1 = 0;
const int* ptr = &var1;
*ptr = 1;
printf("%d\n", *ptr);
return 0;
}
Output :
constptr.c: In function ‘main’:
constptr.c:7: error: assignment of read-only location ‘*ptr’
So we see that the compiler complains about ‘*ptr’ being read-only.This means that we
cannot change the value using pointer ‘ptr’ since it is defined a pointer to a constant.
Pointer as a function parameter is used to hold addresses of arguments passed during function
call.This is also known as call by reference.When a function is called by reference any
change made to the reference variable will effect the original variable.The actual arguments
are addresses of variables.The formal arguments are Pointers of specific data type like int,
char, float, structure, File etc.
Example Program:
#include <stdio.h>
intmain()
{
int a, b;
a = 5 ; b = 20 ;
swap (&a, &b) ;
printf (“\n a = %d, b = %d”, a, b);
}
void swap (int *x, int *y)
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}
Output
a = 20, b = 5
A function can also return a pointer to the calling function. In this case you must be careful,
because local variables of function doesn't live outside the function.They have scope only
inside the function.Hence if you return a pointer connected to a local variable, that pointer
will be pointing to nothing when the function ends that becomes a “dangling pointer “. If
local variables are to be returned then they should be static variables.
Example Program:
Output :
92 is larger.
Explanation:
x, y are pointers that store the addresses of the variables of main function a,b respectively.
*x refers to value of a and *y referes to value of b so if *x>*y we return the address of a that
is x
Otherwise, we return the address of b that is ySo that’s why the return type of the function is
an integer type pointer.
Category 5 functions: Multiple values modified by the sub program can be reflected back in
the main program not by the return statement but by using pointers.
The return” statement cannot return more than one value. If at any time we want more than
one value of a sub program need to be returned or reflected to calling function then it is
possible using the concept of call by reference. When a function is called by reference any
change made to the reference variable will effect the original variable. The actual
arguments are addresses of the output or resultant variables in addition to input variables.
The formal arguments are Pointers of specific data type.
Example Program:
#include <stdio.h>
void compute(int *,int *,int *,int *,int *);
int main( )
{
int a=5, b=10,sum,dif,prod;
compute(&a, &b,&sum,&dif,&prod);
printf (“\n a = %d \n b = %d \n Sum =%d \n Diff= %d \n Product = %d”, a,
b,sum,dif,prod);
}
void compute(int *,int *,int *,int *,int *)
{
*s=*x+*y;
*d=*x-*y;
*p=*x * *y;
}
Output :
a=5
b=10
Sum=15
Diff =-5
Product =50
Note:
Here we don’t use a return statement but using call by reference the values computed will be
reflected in main function. Thus we tend to show multiple value changes.
Declaration:
Return type (*pointer-name)(parameter);
Example :
int (*sum)(); //legal declaration of pointer to function
int *sum(); //This is not a declaration of pointer to function
Output:
Sum is 25
#include <stdio.h>
int sum(int x, int y) ; // function declaration
int multiply(int x, int y);
int main( )
{
int res;
int (*fptr)(int, int); // Declaration of fnptr
fptr = sum; // initialization
res = fptr(10, 15); // function call
printf(“\n Sum is %d", res);
fptr = multiply; // initialization
res = fptr(10, 15); // function call
printf(“\n Product is %d", res);
return 0;
}
int sum(int x, int y) // function definition
{
returnx+y;
}
int multiply(int x, int y) // function definition
{
return x*y;
}
Output :
Sum is 25
Product is 150
Pointer to arrays is a normal pointer of that data type. A pointer variable can store the
address of only one variable at a time. An array name is a constant pointer to the first
element of the array.
When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations. The base
address is the location of the first element (index 0) of the array. The compiler also defines the
array name as a constant pointer to the first element.
The array name “a” is a constant pointer pointing to first element of that array
&a[0] => a => (base address)
To access the value , a[i] = we use *(p+i)
To access the address ,&a[i] = we use (p+i)
Declaration:
datatype *ptr; Eg: int *p; char *r;
Initialization:
// Let us assume a is the name of the array then
ptr=a;
or
ptr=&a[0];
Accessing:
Each character a[i]is accessed as *(ptr+i).
Example Program:
// POINTERS TO 1 D ARRAYS
// W A C P TO READ AND WRITE THE ELEMENTS OF 1 D ARARY USING
POINTERS
#include <stdio.h>
int main()
{
int a[5],i;
int *p; // declaration of pointer to 1 d array
p=&a[0]; // p=a; initialization of 1 d ararys
for(i=0;i<5;i++)
{
printf("\n Enter a value into a[%d] :",i);
scanf("%d",(p+i)); //&a[i]
}
printf("\n Array Elements \n");
for(i=0;i<5;i++)
{
printf("\n a[%d] = %d",i,*(p+i) );//a[i]
}
return 0;
}
Output :
Enter a value into a[0] :1
Enter a value into a[1] :2
Enter a value into a[2] :3
Enter a value into a[3] :4
Enter a value into a[4] :5
Array Elements
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
Pointers to 2 Dimensional Arrays
When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations.
The elements of a 2 D array are stored row wise contagious,xi.e after first row ,the first
element of second row is stored and so on..
The base address is the location of the first element (index [0][ 0]) of the array.
The compiler also defines the array name as a constant pointer to the first element.
If ‘p’ is a Pointer to a Two Dimensional array ‘a’ then with ‘r’ rows and ‘c’ columns….
Example Program:
Output :
Enter order of matrix A :22
Enter a value into a[0][0] : 1
Enter a value into a[0][1] : 2
Enter a value into a[1][0] : 3
Enter a value into a[1][1] : 4
MATRIX A
12
34
To store, read ,write and access strings using pointers in C programming language is possible
as we know that a string is a sequence of characters which we save in contagious memory
locations. A pointer to a string in C can be used to point to the base address of the string
array, and its value can be dereferenced to get the value of the string.
To get the value of the string array is iterated using a while loop until a null character is
encountered.
Output:
We have already learned that a pointer is a variable which points to the address of another
variable of any data type like int , char, float etc. Similarly, we can have a pointer to
structures, where a pointer variable can point to the address of a structure variable. Yes ,
we can have pointers for structure.
To access the members of a structure using pointers we need to perform the following
operations:
Syntax:
Struct tagname
{
Data type member1;
Data type member2;
};
struct tag-name var; // create a
variable struct tag-name *ptr; // create a
pointer
ptr = &var; //assign structure variable address to structure pointer
To access members of a structure using pointers, we use the -> operator.
(*ptr).member1;
(or)
ptr->member1;
How to access data members of a structure using its pointer?
The parentheses around *ptr are necessary because the member operator “.” has a higher
precedence than the operator “*”
Accessing members:
using pointer to structures
For Example: In a linked list, one may refer to n->next->next for the second following node
(assuming that n->next is not null).
Example:
#include<stdio.h>
struct student
{
int HTNO;
char NAME[20];
float AVG;
};
int main()
{
struct student s1;
struct student *ptr;
ptr=&s1;
printf("Enter student details:");
scanf("%d%s%f",&ptr->HTNO,ptr->NAME,&ptr->AVG);
printf("HTNO=%d",ptr->HTNO);
printf("NAME=%s",ptr->NAME);
printf("AVERAGE MARKS=%f",ptr->AVG);
}
OUTPUT:
Enter student details:
301
ajay
56.78
HTNO=301 NAME=ajay AVERAGE MARKS=56.779999
STRUCTURES
Introduction to Structures
A structure is user defined data type in C. A structure creates a data type that can be used to group
items of possibly different types into a single type/entity. Structures are a way to group several
related variables into one place. Each variable in the structure is known as a member of the
structure. The key word that creates structures is struct.
C has built in primitive and derived data types. Still not all real world problems can be solved
using those types. You need custom data type for different situations.
For example, if you need to store 100 student record that consist of name, age and mobile
number.
● We need a method for packing together data of different types.
● Need a helpful tool to handle a group of logically related data items.
Advantages of Structures in C
1. Structures gather more than one piece of data about the same object together in the
same place.
2. It is helpful when you want to gather the data of similar data types and parameters
like first name, last name, etc.
3. It is very easy to maintain as we can represent the whole record by using a single name.
4. In structure, we can pass complete set of records to any function using a single parameter.
5. You can use an array of structure to store more records with similar types.
Disadvantages of Structures in C:
1. If the complexity of IT project goes beyond the limit, it becomes hard to manage.
2. Change of one data structure in a code necessitates changes at many other
places. Therefore, the changes become hard to track.
3. Structure is slower because it requires storage space for all the data.
Structure template is a collection of all the logically related data members of a structure into a
single unit.
It has an optional name called structure tag name.
All the data members of a structure are listed between { } and terminated with (semicolon);
It has no memory allocated to it.
It is a collection of data members when variable for structure is created memory is allocated to it.
Structure Declaration
A structure is a collection of one or more variables of different data types, grouped together under
a single name. By using structures, variables, arrays, pointers etc..can be grouped together.
Before using any variable in c it must be declared to the compiler,likewise structures also must be
declared
struct student
{
int rollno;
char name[20];
int marks[6];
};
Example -2 :
struct Employee
{
int eid;
char name[20];
floatsal;
};
● The structure definition associated with the keyword typedef is called type-
defined structure.
● This is the most powerful way of defining the structure...
● Type defined structures are very handy in implementing Data structures in C.
● They also become useful in passing structures to functions.
● They enhance readability.
Example -2:
typedef struct
{
int eid;
char name[20];
int sal;
}Emp;
*Note : We cannot create variables along with template in this type-defined structure.
Memory is not reserved for the structure definition or structure template since no variables are
associated with the structure definition.
The members of the structure do not occupy any memory until they are associated with the
structure variables.
Structure variables are created after defining the structure template to allocate storage.
Creation of structure variables inside main() or inside any function making it local :
void main( )
{
struct tag name v1,v2,..vn;
// local
}
(or)
void function( )
{
struct tag name v1,v2,..vn;
}
Example:
struct book
{
char name[30];
int pages;
float price;
};
void main( )
{
struct book b1,b2,b3;
}
Example:
struct book
{
char name[30];
int pages;
float price;
};
struct book b1,b2,b3;
Creation of structure variables along with the structure template making it global:
Syntax:
struct TAG
{
Type varaible1;
……
……
Type variable-n;
} v1, v2, v3;
Example:
struct book
{
char name[30];
int pages;
float price;
}b1,b2,b3;
* Note: Here it becomes Global Declaration.
In C programming language (.) is used to access members of a structure directly through a normal
structure variable.
It is used to access members of a union directly through a normal union variable.
Yes, dot (.) is actually an operator in C/C++ which is used for direct member selection via object
name. It has the highest precedence in Operator Precedence and Associativity chart after the
Brackets.
How to access members of Structure?
Structures use a dot (.) operator also called period operator or member operator to refer its
elements.
Before dot, there must always be a structure variable. After the dot, there must always be a
structure element. The syntax to access the structure members as follows:
Examples:
s1.rollno
s2.name
S3.marks
e1.eid
e2.sal
e3.name
Can we Initialize Structures in C?
It is a process of giving some default values to structure data members through its variables.
● The rules for structure initialization are similar to the rules for array initialization.
● The initializers are enclosed in braces and separated by commas.
● They must match their corresponding types in the structure definition.
SYNTAX:
The syntax is shown below:
struct tag_name variable = { value1, value2,… value-n };
typedef struct
{
char name[5];
int rollno;
float avg;
} student ;
student s1= {“Ravi”, 10, 67.8};
//outside main global
void main( )
{
student s1= {“Ravi”, 10, 67.8}; // inside main local
--------------
}
Note: In this method we cannot initialize along with template Partial Initialization:
Yes, structure variable can be initialized with few values.
Example:
Points to remember:
● Initializers must match in type , order and number(count).
● String values are enclosed in “ “ and characters in ‘ ‘.
● Partial initialization is made for first few data members only.
● We cannot initialize structures members in random order and also with more initializers.
Points to remember:
● Use the data member names only like variable name. data member name
● Also do not use & for string members.
Example Program:
Write a C program to read and write structure in C?
struct Book
{
char Title[30];
int pages;
char Author[30];
int price;
};
void main( )
{
struct Book b1;
printf(“\n Enter Title , Pages , Author and Price of Book : ”);
scanf(“%s %d %s %d”, b1.Title,&b1.pages,b1.Author,&b1.price);
printf(“\n The details of the Book are:”);
printf(“\n Title : %s”, b1.Title);
printf(“\n Author : %s ”, b1.Author,);
printf(“\n Pages : %d \n Price : %d ”, b1.pages,b1.price);
}
Output:
Enter Title , Pages , Author and Price of Book :
Letusc250 Yaswanthkanitker 320
The details of the Book are :
Title :Letusc
Author :Yaswanthkanitker
Pages : 250
Price : 320
Write a C program to read and write the details of a student like name,roll number and
average?
Program:
#include<stdio.h>
struct student
{
char name [15];
int rollno;
float avg;
}s1;
void main( )
{
printf("\n Enter Name , Rollno and Average of a student :");
scanf("%s %d %f",s1.name,&s1.rollno,&s1.avg); //read
printf("%s %d %f",s1.name,s1.rollno,s1.avg); //write
}
Output:
Enter Name , Rollno and Average of a student :ARUNU IMA 563
87.67
ARUNIMA 563 87.669998
The operations on data members of a Structure depend upon the data type of that structure.
Depending on the data type all the operations are possible on that data type are allowed on that
data type. So all operation on integers are allowed on integer data members of a structure and so
on.
Example:
Example:
struct student
{
int rollno;
char name[20];
}s1={73,”Sindhu”}, s2;
But if we have e1 as an employee structure variable then e1=s1; is invalid as they are of different
structures
Here,
s2=s1;
Copies all values of s1 to s2.
So
Printf(“%d%s”,s2.rollno,s2.name);
Output : 73 Sindhu
Though we can copy one structure variable to another in C, we cannot compare one structure
variable with another.
Example:
Struct Student
{
Int rollno;
char name[20];
}s1={73,”Sindhu”}, s2;
s2=s1; // valid
But when we have to compare
But it is Invalid
Example :
Struct Student
{
int rollno;
char name[20];
}s1={73,”Sindhu”}, s2;
s2=s1; // valid
// if(s1==s2) // invalid
Example: To store marks of a student in six subjects then we can have the following as a data
member of a structure.
int marks[6];
Example: To store name of each student then we can have the following as a data member of a
structure.
char name[20];
Working with array of structures:
Declaration:
They are declared just as normal data members of structures.
Example :
To store the details of a student we can have the following as a template of a structure.
struct student
{
char name [20]; // character array to store name of student
int roll_number;
int marks [6]; // marks of 6 subjects of a
student float avg;
};
Initialization of arrays within Structures:
Then the initialization of the array marks done as follows:
struct student s1= {“Raghu”, 34, {60,70,80,40,90,85} };
The values of the member marks array are referred as follows:
s1.marks [0] --> will refer the 1 st value of marks.
s1.marks [1] --> will refer the 2 nd value of marks.
s1.marks [2] --> will refer the 3 rd value of marks.
Syntax:
Structure_variable_name.arraydatamembername[index];
Example :
Struct student s1;
//use a for loop from i=0 to n (size) and use s1.marks[i]
To Read:
To write:
int main( )
{
inti;
printf("\n Enter Name , Rollno");
scanf("%s %d",s1.name,&s1.rollno);
s1.total=0;
for(i=0;i<3;i++)//read
{
printf("\n Enter marks of subject %d:",i+1);
scanf("%d",&s1.marks[i]);
s1.total+=s1.marks[i];
}
printf("\nNAME: %s \nROLL NO: %d \nTOTAL: %d",s1.name,s1.rollno,s1.total); //write
return 0;
}
Output :
Enter Name , Rollno: ARUNIMA
501
NAME: ARUNIMA
ROLL NO: 501
TOTAL: 257
ARRAY OF STRUCTURES:
An array is a collection of elements of same data type that are stored in contiguous memory
locations. A structure is a collection of members of different data types stored in contiguous
memory locations. An array of structures is an array in which each element is a structure.
This concept is very helpful in representing multiple records of a file, where each record is a
collection of dissimilar data items. Used in implementing various operations on real time data like
employee, student, books etc.
Let’s take an example, to store the information of 3 students, we can have the following structure
definition and declaration,
struct student
{
char name[10];
int rno;
float avg;
};
struct student s[3]; // declaration of array of structure
Defines an array called s, which contains three elements. Each element is defined to be of type
struct student.
Initialization:
Array of structures can be declared as follows:
struct student
{
char name[10];
int rno;
float avg;
};
struct student s[3]; // declaration of array of structure
Defines an array called s, which contains three elements. Each element is defined to be of type
struct student.
PROGRAM:
Distinguish between Arrays within Structures and Array of Structures with examples.
Arrays within structure:
It is also possible to declare an array as a member of structure, like declaring ordinary variables.
For example, to store marks of a student in three subjects then we can have the following
definition of a structure.
struct student
{
char name [5];
int rollno;
int marks [3];
float avg;
};
Then the initialization of the array marks done as follows:
struct student s1= {“ravi”, 34, {60,70,80}};
The values of the member marks array are referred as follows:
s1. marks [0] --> will refer the 0th element in the marks s1. marks [1] --> will refer the 1st
element in the marks s1. marks [2] --> will refer the 2ndt element in the marks
Array of structures:
An array is a collection of elements of same data type that are stored in contiguous memory
locations. A structure is a collection of members of different data types stored in contiguous
memory locations. An array of structures is an array in which each element is a structure. This
concept is very helpful in representing multiple records of a file, where each record is a collection
of dissimilar data items.
Example:
An array of structures for structure employee can be declared as
struct employee emp[5];
Let‟s take an example, to store the information of 5 employees, we can have the following
structure definition and declaration,
struct employee
{
int empid;
char name[10];
float salary;
};
Defines array called emp, which contains five elements. Each element is defined to be of type struct
student.
For the student details, array of structures can be initialized as follows, struct employee emp[5] =
{{1,”ramu”25,20000},{2,”ravi”,65000},{3,”tarun”,82000},{4,”rupa”,5000},{5,”deep”,27000}};
NESTED STRUCTURES:
Yes it is allowed to nest structures in C.Like Loops, Nested structures in C are the Structures
inside the Structure. A structure can be used as a member of another structure.
In other words, the members of a structure can be of any other type including structure.
For example, we have two structures named Address and Employee.We can make Address
nested to Employee.
Nested structure in C is nothing but structure within structure.C provides us the feature of nesting
one structure within another structure by using which, complex data types are created. Using this
one structure can become a part of multiple structures.
For Example , Using this, we can create one structure called address and add door number, street
name, city members under it.
Now, we can call this address structure from the Employee, Student, and Person structures.
struct
Innerstructure
{
datatype dm1;
datatype dm2;
} Innervariable;
} <outervariable>;
In this method :
● Inner structure template and variable both are declared inside the outer structure template
itself.
● Also the inner structure is local to outer structure only.
● It means inner structure is not available outside.
● It can be used only along with outer structure.
Example:
struct Student
{
int rollno;
char name[20];
struct Address
{
int hno;
char street[20];
char city[20];
} ad;
int marks;
} s1;
In this method,Outer structure is Student whose members arerollno ,name and marks and
Also another structure as member i.e Address.So the inner structure is address whose members
are hno,street,city.Address is only accessed through student structure only.
Variable for inner structure must be created only along with template.
};
struct Outerstructure
{
datatype mem1;
datatype mem2;
structInnerstructureInnervariable;
} <outervariable>;
struct Innerstructure
{
datatype dm1;
datatype dm2;
};
struct Outerstructure
{
datatype mem1;
datatype mem2;
structInnerstructureInnervariable;
} <outervariable>;
In this method, Inner structure template is defined separately outside and above the outer
structure. Only variable of inner structure is created inside the outer structure template. Here the
inner structure can be used separately and also in any other structures as well as outer structure .
It means inner structure is available outside as well .
Example:
int marks;
} s1; Address
struct
{
int hno;
char street[20];
char city[20];
};
struct Student
{
int rollno;
char name[20];
struct Address ad;
In this method Outer structure is Student whose members arerollno ,name and marks and
Also another structure as member i.e Address.So the inner structure is address
Whose members are hno,street,city.Only variable for inner structure is created inside outer
structure. Template of inner structure must be created Outside and always above the outer
structure.
struct Student
{
introllno;
char name[20];
struct Address
{
inthno;
char street[20];
char city[20];
} ad;
int marks;
} s1={21,”Raghu”,{123”SBI Bank street”,”Hyderabed”},90};
Outerstructurevariable. Innerstructurevariable.nestedmembername;
Yes structures can be made as function arguments.A structure can be passed as an argument to a
function and also a function can return a structure type variable as well.Even a function in C can
have a pointer to structure as function argument and also return a pointer to structure as well.
Passing structures to functions is another way of sending multiple heterogeneous data at once to a
function.An entire record can be passed to a function for some processing.
Structures can be passed to functions and to do that we need to have a structure type variable.
In general since a structure variable can be copied into another variable of similar type it is
possible to do so.They can be passed in both Call by value and call by reference techniques.
● Passing normal Structure Variables => Pass by Value
● Passing Address of structure Variables => Pass by Reference
Even we can pass individual elements of a structure to a function.
Structures are more useful if we are able to pass them to functions and return them.
Structures are more useful if we are able to pass them to functions and return them.
Program:
#include<stdio.h>
typedef struct emp
{
char name[15];
intemp_no;
float salary;
}record;
void main ( )
{
return_typefunction_name (structure_variable_name);
data_typefunction_name(struct_typetag_name)
{
………
………
return(expression);
}
The called function must be declared for its type, appropriate to the data type it is expected to
return.The structure variable used as the actual argument and the corresponding formal argument
in the called function must be of the same struct type.The return statement is necessary only when
the function is returning some data back to the calling function. The expression may be any
simple variable or structure variable or an expression using simple variables.When a function
returns a structure, it must be assigned to a structure of identical type in the calling function. The
called functions must be declared in the calling function appropriately.
Program:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Yes a function can have a structure type variable as its return type.It can be structure type
variable or can also be a pointer to structure.
typedef struct
{
char name [15];
int emp_no;
float salary;
} record;
#include<stdio.h.>
#include<string.h
> void main ( )
{
record change (record);
record e1 = {"Smith", 2, 20000.25};
int main()
{
CMPLX c1,c2,c3;
printf("\n Enter real and imaginary parts of complex number c1:");
scanf("%d %d",&c1.rel,&c1.img);
printf("\n Enter real and imaginary parts of complex number c2:");
scanf("%d %d",&c2.rel,&c2.img);
c3=sum(c1,c2);
printf("\n SUMOF COMPLEX NUMBERS C1 AND C2 IS C3");
printf("\n COMPLEX NUMBER C3 = %d +i %d",c3.rel,c3.img);
return 0;
}
OUTPUT:
What is a Union?
A union is one of the User Defined data types.Union is a collection of variables referred under a
single name. The syntax, declaration and use of union is similar to the structure but
itsfunctionality is different.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
………………
} union_variable;
Example:
union techno
{
int comp_id;
char nm;
float sal;
} tch;
A union definition and variable declaration can be done by using any one of the following
Here :
int x = sizeof(struct Test);
int x = sizeof(t1); x => 16
=> 2 bytes for int + 10 bytes for string + 4 bytes for float
Size of Union:
It is the size of its largest data member.
int x= sizeof(union <tagname>);
(0r)
int x =sizeof(union variablename);
union Test{
int x;
char
str[10];
float y;
} t1;
Here :
int x = sizeof(union Test);
int x = sizeof(t1); x => 10
=>Maximum(2 bytes for int , 10 bytes for string , 4 bytes for float ).
union Test
{
int x; char
str[10];
}t1={7};
int main()
{
printf("\n x = %d",t1.x);
strcpy(t1.str,"Griet");
printf("\n str = %s",t1.str);
printf("\n Size of union = %d",sizeof(t1));
return 0; }
Output:
x = 7 str = Griet
Size of union =
10
It enables you to initialize several members It enables you to initialize only the
at once. first member of union.
Changing the value of one data member Changing the value of one data member
will not affect other data members in will change the value of other data
structure. members in union.
The total size of the structure is the sum of The total size of the union is the size of
the size of every data member. the largest data member.
It is mainly used for storing various data It is mainly used for storing one of the many
types. data types that are available.
It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.
You can retrieve any member at a time. You can access one member at a time in the
union.
Advantages of structures:
1. Structures gather more than one piece of data about the same subject together in the
same place.
2. It is helpful when you want to gather the data of similar data types and parameters
like first name, last name, etc.
3. It is very easy to maintain as we can represent the whole record by using a single name.
4. In structure, we can pass complete set of records to any function using a single parameter.
5. You can use an array of structure to store more records with similar types.
Advantages of union
1. It occupies less memory compared to structure.
2. When you use union, only the last variable can be directly accessed.
3. Union is used when you have to use the same memory location for two or more
data members.
4. It enables you to hold data of only one data member.
5. Its allocated space is equal to maximum size of the data member.
Disadvantages of structure
1. If the complexity of IT project goes beyond the limit, it becomes hard to manage.
2. Change of one data structure in a code necessitates changes at many other
places. Therefore, the changes become hard to track.
3. Structure is slower because it requires storage space for all the data.
4. You can retrieve any member at a time in structure whereas you can access one
member at a time in the union.
5. Structure occupies space for each and every member written in inner parameters while
union occupies space for a member having the highest size written in inner
parameters.
6. Structure supports flexible array. Union does not support a flexible array.
Disadvantages of union
UNIT-V
Files: Text and Binary files, Creating and Reading and writing text and binary files, Random access to
files, Error Handling in files Command line arguments, Enumeration data type.
Preprocessor: Commonly used Preprocessor commands like include, define, undef, if, ifdef, ifndef, elif.
File : A file is an external collection of related data treated as a unit. A file is a place on a disk
where a group of related data is stored and retrieved whenever necessary without destroying data.
The primary purpose of a file is to keep record of data. Record is a group of related fields. Field
is a group of characters which convey meaning. Files are stored in auxiliary or secondary storage
devices. The two common forms of secondary storage are disks (hard disk, CD and DVD) and
tapes.
Each file ends with an end of file (EOF) at a specified byte number, recorded in file structure.
A file must first be opened properly before it can be accessed for reading or writing. When a file
is opened an object (buffer) is created and a stream is associated with the object.
It is advantageous to use files in the following circumstances.
There are two kinds of files depending upon the format in which data is stored:
1) Text files
2) Binaryfiles
Textfiles:
A text file stores textual information like alphabets, numbers, special symbols, etc.
Actually the ASCII code of textual characters its stored in text files. Examples of some text
filesincludec,java,c++sourcecodefilesandfileswith.txtextensions.Thetextfilecontains
the characters in sequence. The computer process the text files sequentially and in forward
direction. One can perform file reading, writing and appending operations. These operations are
performed with the help of inbuilt functions of c.
Binary files:
Text mode is in efficient for storing large amount of numerical data because it occupies large
space. Only solution to this is to open a file in binary mode, which takes lesser space than the
text mode. These files contain the set of bytes which stores the information in binary form. One
main drawback of binary files is data is stored in human unreadable form. Examples of binary
files are .exe files, video stream files, image files etc. C language supports binary file operations
with the help of various in built functions
DATASTRUCTURE:
It is defined as FILE in the library of standard I/O function definitions. Therefore all files are
declared as type FILE.FILE is a define data type.
FILE *fp;
PURPOSE:
It defines the reason for which a file is opened and the mode does this job.
fp=fopen(“filename”,”mode”);
The read mode (r) opens an existing file for reading. When a file is opened in this mode, the. file
marker or pointer is positioned at the beginning of the file (first character).The file must already
exist: if it does not exist a NULL is returned as an error. If we try to write a file opened in read
mode, an erroroccurs.
Syntax:fp=fopen (“filename”,”r”);
“a” (append) mode: The append mode(a) opens an existing file for writing instead of creating
a new file.However,the writing starts after the last character in the existing file ,that is new
data is added, or appended, at the end of the file. If the file doesn‟t exist, new file is created and
opened . In this case,the writing will start at the beginning of thefile.
Syntax: fp=fopen (“filename”,”a”);
NOTE: To perform operations on binary files the following modes are applicable with an
extension b like rb,wb,ab,r+b,w+b,a+b,which has the same meaning but allows to perform
operationson binaryfiles.
Naming afile
Opening afile
Reading data
fromfile Writing data
intofile Closing aFile
In order to perform the basic file operations C supports a number of functions .Some of the
Important file handling functions available in the C library are as follows:
FUNCTION OPERATION
NAME
fopen() Creates a new file for use or Opens an existing file for use
Anameisgiventothefileusedtostoredata.Thefilenameisastringofcharactersthatmake up a
valid file name for operating system. It contains two parts. A primary name and an
Examples: Student.dat, file1.txt, marks.doc, palin.c The general format of declaring and
opening a file is
FILE *fp; //declaration
fp=fopen (“filename”,mode”); //statement to open file.
Here FILE is a data structure defined for files. fp is a pointer to data type FILE. filename
is the name of the file. mode tells the purpose of opening this file.
Reading data from file:
putc():This function writes a character to a file that has been opened in writemode.
Syntax: putc(c,fp);
Closing a file:
A file is closed as soon as all operations on it have been completed.Closing a file ensures that
all outstanding information associated with the file is flushed out from the buffers and all links
to the file are broken.Another instance where we have to close a file is to reopen the same file
in a different mode.
Library function for closing a file
Where fp is the file pointer returned by the call to fopen(). fclose() returns 0 on success (or)- 1 on error.
Once a file is closed, its file pointer can be reused for another file. Note: fcloseall() can be used to close all
the opened files at once.
#include<stdio.h>
int main()
{
FILE
*fp; char
ch;
fp=fopen("abcd.txt","w+"); //change w+ to w and see output
fputs(" lgriet",fp);
rewind(fp);
#include<stdio.h>
int main()
{
FILE
*fp; char
ch;
fp = fopen("abc.txt","w");
printf("enter the some characters and press @ to stop:\n");
while((ch=getchar())!='@')
{
putc(ch,fp);
}
fclose(fp);
fp = fopen("abc.txt", "a+"); //change a+ to a mode and see if u can read the content from file
fprintf(fp, "%s %s", "Arsenal",”Gunner");
rewind(fp);
printf("Appended file
content:\n"); while((ch =
fgetc(fp))!= EOF)
{
printf ("%c", ch);
}
fclose(fp);
return 0;
}File I/O functions:
In order to perform the file operations in C we must use the high level I/O functions which are
in C standard I/O library. Theyare
while((i=fgetc(fp))!=EOF)
{
printf("%c",i);
}
fclose(fp);
return(0);
}
putc()/fputc() -:
It is used to write a character contained in the character variable to thefile associated with the
FILE pointer fp. fputc() also returns an end-of –marker EOF, when an end of file has been
reached.fputc behaves like putc, but is a genuine function rather than a macro; it may therefore
be used as an argument. fputc runs more slowly than putc, but takes less space per invocation.
Syntax: putc(c,fp);
Example: char c; putc(c,fp);
int fputc(int char, FILE *pointer)
#include<stdio.h>
int main () {
char c;
printf("Enter character:");
c = getc(stdin);
printf("Character entered: ");
putc(c, stdout);}
Program using fgetc() and fputc():
#include<stdio. h>
void main()
{
FILE *fp;
char ch;
fp=fopen("input1.txt","w");
printf("\n enter some text and press@ to stop:\n");
while( (ch=getchar())!='@')
fputc(ch,fp);
fclose(fp);
fp=fopen("input1.txt","r");
printf("\n The entered text is : \n");
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
fprintf() andfscanf():
In order to handle a group of mixed data simultaneously there are two functions that are
fprintf()andfscanf().Thesetwofunctionsareidenticaltoprintfandscanffunctions,exceptthat they
work on files. The first argument of these functions is a file pointer which specifies the file to
beused.
fprintf(): The general form of fprintf() is
Syntax: fprintf(fp,”control string”,argument list);
where fp is a file pointer associated with a file that has been opened for writing . The control
string contains output specifications for the items in the list. .
Example:fprintf(fp,”%s%d”,name,age);
fscanf() : It is used to read a number of values from a file.
Syntax: scanf(fp,”control string”,argument list);
Example: fscanf(fp2,”%s%d”,item,&quantity);
like scanf , fscanf also returns the number of items that are successfully read. when the end of
file is reached it returns the valueEOF.
Program using fscanf() andfprintf():
#include <stdio.h>
int main ()
{
char str1[10], str2[10], str3[10];
int year;
char
dept[20]="CSE";
FILE * fp;
fp = fopen ("file", "w+");
fprintf(fp,"We are GRIETIANs 2022 %s",dept);
rewind(fp);
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("%s year value is %d",str3,year);
fclose(fp);
return(0);
}
getw() andputw():
The getw() and putw()are integer oriented functions .They are similar to the getc() and putc()
functionsandareusedtoreadandwriteintegervalues.Thesefunctionswouldbeusefulwhen we deal
with only integer data. The general form of getw() and putw()are:
Syntax:
putw (int num, FILE *fp);
int getw (FILE *fp);
A program that demonstrates getw and putw is given below −
#include<stdio.h>
int main()
{
FILE *fp;
int i;
fp = fopen ("num.txt", "w");
for (i =1; i<= 10; i++) {
putw (i, fp);
}
fclose (fp);
fp =fopen ("num.txt", "r");
printf ("file content is\n");
for (i =1; i<= 10; i++){
i=getw(fp);
printf ("%d ",i);
}
fputs() and fgets():
fgets(): It is used to read a string from a file pointed by file pointer. It copies the string to a
memory location referred by an array.
Syntax: char* fgets(char *s, int n, FILE *stream)
Example: fgets(text,50,fp1);
Example: fputs(text,fp);
#include<stdio.h>
int main()
{
char string[20];
printf("Enter the string: ");
fgets(string,200,stdin); //reading from stdin stream
printf("\nThe string is: %s",string);
return 0;
}
#include<stdio.h>
int main()
{
FILE *fp;
char text[300];
//reading from abc.txt
fp=fopen("abc.txt","r");
fgets(text,50,fp);
printf("%s",text);
fclose(fp);
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen(“abc.txt","w");
fputs("hello c programming",fp);
fclose(fp);
}
fread and fwrite:
Large amount of integers or float data require large space on disk in text mode and turns out to
be inefficient.fwrite and fread make task easier when you want to write and read blocks of data.
fread() andfwrite() syntax:
fwrite(void *buffer,int size,int count,FILE *fp);
fread (void *buffer, int size, int count, FILE *fp);
where,
count - is the number of elements, each one with a size of “size” bytes.
stream - is the pointer to a FILE object that specifies an output stream/input stream.
Following program demonstrates the use of fread and fwrite function to read
blocks of data:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char content[100];
fp=fopen("abc.txt","wb");
fwrite("Arsenal Football Club",sizeof(char),16,fp);
fclose(fp);
fp = fopen("abc.txt", "rb");
fread(&content, sizeof(char),7,fp);
printf("The file content is:\n %s\n",content);
fclose(fp);
return 0;
}
fwrite(): is also used for writing an entire structure block to a given file in binary mode.
Syntax:
fwrite(&structure variable,sizeof(structure variable),1,filepointer);
Example: fwrite(&stud,sizeof(stud),1,fp);
fread(): is also used for reading an entire structure block from a given file in binarymode.
Syntax:
fread(&structure variable,sizeof(structure variable),1,filepointer);
Example: fread(&emp,sizeof(emp),1,fp1);
#include<stdio.h>
struct player
{
char pname[50];
int age;
int runs;
};
int main()
{
struct player
p1,p2; FILE *f3;
f3=fopen("player.txt","wb+");
printf("\n Enter details of player name ,age and runs scored
:\n"); scanf("%s %d %d",p1.pname,&p1.age,&p1.runs);
fwrite(&p1,sizeof(p1),1,f3);
rewind(f3);
fread(&p2,sizeof(p2),1,f3);
printf("\nPLAYERNAME:=%s\nAGE:=%d\nRUNS:=%d",p2.pname,p2.age,p2.runs);
fclose(f3);
}
At times we needed to access only a particular part of a file rather than accessing all the data
sequentially, which can be achieved with the help of functions fseek, ftell and rewind functions.
ftell():-
ftell takes a file pointer and returns a number of type long, that corresponds to the current position.
This function is useful in saving the current position of the file, which can later be used in the
program.
syntax:n=ftell(fp);
n would give the Relative offset (In bytes) of the current position. This means that already n
bytes have a been read or written.
rewind():-
It takes a file pointer and resets the position to the start of the file.
Syntax:
rewind(fp);
n=ftell(fp);
would assign 0 to n because the file position has been set to start of the file by rewind().The first
byte in the file is numbered 0, second as 1, so on. This function helps in reading the file more than
once, without having to close and open the file.
Whenever a file is opened for reading or writing a rewind is done implicitly.
fseek():- fseek function is used to move the file pointer to a desired location within the
file. Syntax: fseek(file*ptr,offset,position);
file pointer is a pointer to the file concerned, offset is a number or variable of type long and position
is an integer number which takes one of the following values mentioned in the table. The offset
specifies the number of positions (Bytes) to be moved from the location specified by the position,
which can be positive implies moving forward and negative implies moving backwards.
Example: fseek(fp,10,0) ;
fseek(fp,10,SEEK_SET);// file pointer is repositioned in the forward direction 10 bytes. .
When the operation is successful fseek returns 0 and when we attempt to move a file beyond
boundaries fseek returns -1. Some of the Operations of fseek function are as follows
Examples Meaning
fseek(fp,0L,0); Go to beginning similar to rewind()
fseek(fp,0L,1); Stay at current position
fseek(fp,0L,2); Go to the end of file, past the last character of the file.
fseek(fp,m,0); Move to (m+1)th byte in the file.
fseek(fp,m,1); Go forward by m bytes
fseek(fp,-m,1); Go backwards by m bytes from the current position
fseek(fp,-m,2); Go backwards by m bytes from the end.(positions the file to the mth character from
the end)
#include <stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("myfile.txt","w+");
fputs("Invincibles Arsenal",fp);
fseek(fp,-7L,SEEK_END); // 2 or SEEK_END
fputs("GRIET",fp);
printf("current position of file pointer:%ld\n",ftell(fp));
rewind(fp);
while((ch=fgetc(fp))!=EOF)
{
printf("%c", ch);
}
fclose(fp);
}
Output:
current position of file
pointer:17 Invincibles GRIETal
#include<stdio.h>
int main()
{
FILE
*fp; char ch;
int i,pos;
fp=fopen("arsenal.txt","r"); //content of file: North London is Red
if(fp==NULL)
{
printf("File does not exist..");
}
fseek(fp,0,SEEK_END);
pos=ftell(fp);
Output:
Current postion of fp: 19
the reversed file content is:
deR si nodnoL htroN
ferror():The C library function int ferror(FILE *stream) tests the error indicator for the given
stream. If the error indicator associated with the stream was set, the function returns a non-zero
value else, it returns a zero value.
int ferror(FILE *stream);
fp==NULL: We know that whenever a file is opened using fopen function, a file pointer is
returned. If the file cannot be opened for some reason, then the function returns a nullpointer.
This facility can be used to test whether a file has been opened ornot.
Example
if(fp==NULL)
printf(“File could not be opened.\n”);
perror(): It is a standard library function which prints the error messages specified by the
compiler. Forexample:
if(ferror(fp)) perror(“Message:”);
#include <stdio.h>
#include<stdlib.h
> int main()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
//give unexisting file name and see error message
given by compiler
if(fp == NULL)
perror("Error Message:");
while(1)
{
c = fgetc(fp);
if(feof(fp))
{
perror("End of the file reached");
break;
}
printf("%c", c);
}
fclose(fp);
}
Program to demonstrate ferror function in error handling
#include <stdio.h>
#include<stdlib.h
> int main ()
{
FILE *fp;
char c;
fp = fopen("file.txt", "w"); //Opening file in w mode
fputs("Gunners",fp);
rewind(fp);
while((c=fgetc(fp))!=EOF) //trying to read the file
{
putchar(c);
}
if(ferror(fp)!=0)
{
perror("Error:");
exit(0);
}
fclose(fp);
return(0);
}
Output:
Error:: Bad file descriptor
StandardOutput:
Similarly, standard output is exactly where things go when you use printf(). In other words,
printf("Value = %d\n", val) is equivalent to the following fputs:
fputs(string,stdout);
Standard Error:
standard error stream (stderr) - used to log error or debug messages during run-time.
Standard error is normally associated with the same place as standard output; however,
redirecting standard output does not redirect standard error.
#include <stdio.h>
int main()
{
char string[256];
printf( "Please enter string: " );
fgets(string, 6, stdin); //enter Griet PPS lab and see the output
fputs(string,stdout);
return 0;
}
#include<stdio.h>
#include <stdlib.h>
int main()
{
int f;
printf("enter the number:");
scanf("%d",&f);
if (f==0)
{
printf("Division by Zero is not //observe output
allowed");
carefully
fprintf(stderr, "Division by zero!
Exiting...\n"); exit(0);
}
else
f = 200/ f;
printf("output is: %d", f);
}
}
#include<stdio. h>
int main()
{
FILE*f1;
char ch;
f1=fopen("data.txt","w");
printf("\n enter some text here and press @ to
stop:\n"); while((ch=getchar())!='@')
fputc(ch,f1);
fclose(f1);
printf(“\n the contents of file are \n:”);
f1 = fopen(“data.txt”,"r");
while((ch=fgetc(f1))!=EOF )
putchar(ch);
fclose(f1);
}
#include<stdio.h>
int main(){
FILE *f1,*f2;
char ch;
f1=fopen("mynew2.txt","w");
printf("\n enter some text here and press @ to stop
:\n"); while((ch=getchar())!='@')
fputc(ch,f1);
fclose(f1);
f1=fopen("mynew2.txt","r");
f2=fopen("dupmynew2.txt","w");
while((ch=getc(f1))!=EOF)
putc(ch,f2);
fcloseall();
printf(“\n the copied file contents are :”);
f2 = fopen(“dupmynew2.txt”,"r");
while(( ch = fgetc(f2))!=EOF )
putchar(ch);
fclose(f2);
}
Write a c program to merge two files into a third file?(Or)
Develop a c program for the following .there are two input files named “file1.txt”
and “file2.txt” .The files are to be merged. That is,copy the contents of first.txt
andthen second.txt to a new file named result.txt?
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE
*f1,*f2,*f3; char ch;
f1=fopen("file1.txt","w");
printf("\nEnter text into f1: \n");
while((ch=getchar())!='@')
putc(ch,f1);
fclose(f1);
f2=fopen("file22.txt","w");
printf("\nEnter text into f2: \n");
while((ch=getchar())!='@')
putc(ch,f2);
fclose(f2);
f1=fopen("result.txt","r");
if(f1==NULL)
{
printf("\ncannot open, file doesnot
exist"); exit(0);
}
f3=fopen("hai3.txt","w");
while((ch=getc(f1))!=EOF)
{
putc(ch,f3);
}
fclose(f1);
f2=fopen("hai2.txt","r");
while((ch=getc(f2))!=EOF)
{
putc(ch,f3);
}
fclose(f3);
fclose(f2);
#include<stdio.h>
int main()
{
FILE *fp1;
char ch;
fp1=fopen("sunday.txt","w");
printf("\n Enter some Text into file
:\n"); while((ch=getchar())!='@')
fputc(ch,fp1);
fclose(fp1);
fp1=fopen("sunday.txt","a+"); //to
append
printf("\n Enter some MORE Text into
file:\n"); while((ch=getchar())!='@')
fputc(ch,fp1);
rewind(fp1);
printf("\n The complete Text in file
is:\n"); while((ch=fgetc(fp1))!=EOF)
putchar(ch
);
fclose(fp1);
}
The arguments passed from command prompt are called command line arguments. These
arguments are handled by main() function.To support command line argument, you need
to change the structure of main() function as given below.
#include <stdio.h>
void main(int argc, char *argv[] )
{
printf("Program name is: %s\n",
argv[0]); if(argc < 2)
{
printf("No argument passed through command line.\n");
}
else
{
printf("First argument is: %s\n", argv[1]);}
}
}
Compile the above program in windows using following command:
gcc filename.c –o filename.exe
then execute using:
filename.e
xe
Example
2:
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("\n Number of arguments are:%d",argc);
if( argc < 2 )
{
printf("No argument passed through command line.\n");
}
else if( argc == 4 )
{
int i;
for(i=0;i<argc;i++)
printf("%s\t", argv[i]);
}
else
{
printf("wrong number of arguments.\n");
}
}
Following Program computes the sum of numbers passed through command line:
#include <stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int i=1,sum=0;
printf("\n The numbers are
:"); for(i=1;i<argc;i++){
sum+=atoi(argv[i]); //replace with sum+=*argv[i]; and observe change in
output
printf("\t %s",argv[i]);
}
printf("\n SUM = %d
",sum); return 0;
}
Enumertaion Datatype :
-
-
enum day{Monday…Sunday}week-f, week-end;
EXAMPLE 1:
// An example program to demonstrate working of enum in C
// Enum is used to assign names to the integral constants
// enum statrts its values from 0 (if not oinitialized) and every next value is 1 + its previous
value
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur=6, Fri, Sat, Sun};
int main()
{
enum week day; // variables of type enum and can assing the values
day = Wed;
printf("\n Mon=%d",Mon);
printf("\n Wed= %d",day);
printf("\n Fri=%d",Fri);
printf("\n Sun=%d",Sun);
return 0;
}
Outpu
t:
Mon=0
Wed= 2
Fri=7
Sun=9
EXAMPLE 2:
#include<stdio.h>
enum week{Mon=1, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
for(day=Mon;day<=Sun;day++)
{
printf("\n Day = %d",day);
}
return 0;
}
Output
: Day =
1
Day = 2
Day = 3
Day = 4
Day = 5
Day = 6
Day = 7 facts about initialization of enum:
Interesting
Two enum names can have same value. For example, in the following C program both ‘Failed’
and ‘Freezed’ have same value 0.
#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
int main()
{
printf("%d, %d, %d", Working, Failed,
Freezed); return 0;
}
Output
: 1, 0, 0
2. If we do not explicitly assign values to enum names, the compiler by default assigns
values starting from 0.
3. We can assign values to some name in any order. All unassigned names get value as
value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, Monday, tuesday = 5, wednesday, thursday = 10, friday,
saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday,
thursday, friday, saturday);
return 0;
}
Output:
1 2 5 6 10 11 12
4. All enum constants must be unique in their scope. For example, the following program fails in
compilation.
Output:
Compile Error: 'failed' has a previous declaration as 'state failed'
Enum vs Macro:
We can also use macros to define names constants. For example we can define ‘Working’ and
‘Failed’ using following macro.
#define Working 0
#define Failed 1
#define Freezed 2
There are multiple advantages of using enum over macro when many related named constants have integral
values.
a) Enums follow scope rules.
b) Enum variables are automatically assigned values.
Following is simpler enum state {Working, Failed, Freezed};
C Preprocessors:
The C Preprocessor is not part of the compiler but is a separate step in the compilation
process. In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct
compiler to do required pre-processing before actual compilation. We refer to the C
Preprocessor as the CPP. All preprocessor commands begin with # symbol.
Macros
Macros are pieces of code in a program that is given some name. Whenever this name is
encountered by the compiler, the compiler replaces the name with the actual piece of code.
The ‘#define’ directive is used to define a macro.
return0;
}
In the above program, when the compiler executes the word LIMIT, it replaces it with 5.
The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro
expansion.
Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do not
need a semi-colon to end.
Macros With Arguments: We can also pass arguments to macros. Macros defined with
arguments work similarly to functions. Let us understand this with a program:
#include <stdio.h>
// macro with parameter
#define AREA(l, b) (l * b)
int main()
{
int l1 = 10, l2 = 5,area;
area = AREA(l1, l2);
printf("Area of rectangle is: %d", area);
return 0;
}
We can see from the above program that whenever the compiler finds AREA(l, b) in the
program, it replaces it with the statement (l*b).
File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code
program. There are two types of files that can be included by the user in the program. Header
files or Standard files:
These files contain definitions of pre-defined functions like printf(), scanf(), etc.
Syntax: #include<filename.h>
where filename is the name of the file to be included. The ‘<‘ and ‘>’ brackets tell the
compiler to look for the file in the standard directory.
User-defined files: When a program becomes very large, it is a good practice to divide it
into smaller files and include them whenever needed. These types of files are user- defined
files. These files can be included as:
Syntax:#include"filename"
Conditional Compilation
Conditional Compilation directives are a type of directive that helps to compile a specific
portion of the program or to skip the compilation of some specific part of the program based
on some conditions.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
#endif
1. #ifdef
Returns true if this macro is defined.
2. #ifndef
Returns true if this macro is not defined.
3. #if
Tests if a compile time condition is true.
4. #else
The alternative for #if.
5. #elif
#else and #if in one statement.
6. #endif
Ends preprocessor conditional.
7. #undef
Undefines a preprocessor macro.
8. #error
Prints error message
#if,#elif,#elif and #else:
Syntax:
#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif
Example Program:
#include <stdio.h>
#define AGE 150
int main()
{
#if AGE <= 18
printf("NOT ELIGIBLE TO VOTE
\n"); #elif AGE > 18 && AGE<=100
printf("ELIGIBILE TO VOTE");
#else
printf("INVALID AGE");
#endi
f return
0;
#ifdef:
}
Syntax:
#ifdef MACRO
//successful code
#else
//else code
#endif
Example program using #ifdef macro:
#include <stdio.h>
#define INPUT 20
void main()
{
int a=0;
#ifdef
INPUT
printf("Value is: %d\n",
INPUT); #else
printf("Enter a:");
scanf("%d", &a);
printf("value is: %d\n",a);
#endif
}
#ifndef example:
#include <stdio.h>
#define INPUT 20
void main()
{
int a=0;
#ifndef INPUT
printf("Value is: %d\n",
INPUT); #else
printf("Enter a:");
scanf("%d", &a);
printf("value is: %d\n",a);
#endif
}
Predefined Macros
ANSI C defines a number of macros. Although each one is available for your use in
programming,
the predefined macros should not be directly modified.
5 STDC Defined as 1 when the compiler complies with the ANSI standard.
#include <stdio.h>
int main()
{
printf("File :%s\n", FILE );
printf("Date :%s\n", DATE
);
printf("Time :%s\n", TIME
);
printf("Line :%d\n", LINE
); printf("ANSI
:%d", STDC );
}Preprocessor Macro Continuation Operator
#include <stdio.h>
#define display(a, b) \
printf(#a" Football "#b)
int main()
{
display(Arsenal, club);
return 0;
}
Page114 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104
GR11D5104 I B. Tech I Semester
GR11D5104Subject Name: PROGRAMMING FOR PROBLEM SOLVING
GR11D5104
Q
UNIT-I Marks CO BL
No.
1 Design a flowchart and pseudo code for determining whether a 5 CO1 L3
number is even or odd.
2 Describe the process of translating an algorithm represented in 5 CO1 L3
pseudo code or a flowchart into C code, highlighting the key
considerations and steps involved.
3 Create a flowchart and design an algorithm to calculate the 5 CO1 L4
average of five numbers entered by the user. Translate the
flowchart into a C code.
4 How would you describe the purpose and importance of 5 CO1 L3
algorithms in programming, and how they enable efficient
problem-solving? Also list any two merits and demerits?
5 Can you explain the concept of pseudocode and how it is used to 5 CO1 L4
represent algorithms in a language-independent manner? Provide
an example of pseudocode for determine whether a number is
prime or not?
6 Sketch a flowchart to determine the roots of a Quadratic equation 5 CO1 L3
ax2 + bx +c .
7 Analyze the behaviour of formatted input and output functions in 5 CO1 L4
C, such as printf and scanf, discussing potential pitfalls related to
format specifiers, precision, and user input validation.
8 Design a C program that converts temperature in Fahrenheit to 5 CO1 L3
Celsius. Prompt the user for the Fahrenheit value and display the
equivalent Celsius value.
9 Can you explain the importance of error handling in C and 5 CO1 L3
discuss different techniques for detecting and handling errors in
a program defining various types of errors?
10 Differentiate between variables and constants in C with necessary 5 CO1 L3
examples?
11 How would you use the increment and decrement operators in C 5 CO1 L4
to modify the value of a variable and observe their pre-increment
and post-increment behaviours? What do you infer from it?
12 Write an algorithm to find roots of a quadratic equation ax2 + bx 5 CO1 L4
+c = 0 reading the values of a, b and c.
13 Evaluate the impact of different data types in C on memory usage 5 CO1 L4
and program efficiency, discussing the advantages and
disadvantages of using specific data types in different scenarios.
14 Analyze the process of compilation in C, discussing the various 5 CO1 L4
stages involved, such as pre-processing, compilation, assembly,
and linking.
15 Can you describe the basic syntax of a C program and the purpose 5 CO1 L3
of main() function?
Page115 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104
16 Can a C program be compiled or executed in the absence of a 5 CO1 L4
GR11D5104
main()?Justify
GR11D5104
17 Write a program in C to find largest and smallest of 3 positive 5 CO1 L3
GR11D5104
integer numbers using conditional operators.
18 Analyze the concept of type casting in C, discussing its role in 5 CO1 L4
converting data between different types and evaluating the
potential risks and benefits of type casting in program behavior
and memory usage.
19 Evaluate the impact of operator precedence and associativity in 5 CO1 L4
C, discussing their influence on the evaluation of expressions.
20 What is an expression? Evaluate the following expressions 5 CO1 L4
specifying the concept applied.
i) 100 % 20 < = 20 – 5 + 100 % 10 – 20 = = 5 > = 1 != 20
ii) a + = b * = C - = 5 where a=3 b=5 and c=8
21 Explain the basic structure of a C program, including the purpose 5 CO1 L4
of the main function. Can a C program have 2 main functions.
Justify
22 Explain the various datatypes available in C and give examples 5 CO1 L2
of when to use each. Mention the format specifiers and ranges of
basic types.
23 Create a C program that calculates the result of a complex 5 CO1 L3
arithmetic expression using operators with different precedences.
24 Write a C program that demonstrates the use of implicit and 5 CO1 L3
explicit type conversion by converting a float to an integer and
vice versa. Also differentiate between them.
25 Write a C program that evaluates an expression involving 5 CO1 L3
multiple operators, and explains how precedence and
associativity determine the result.
26 What are keywords in C? Provide examples of three keywords 5 CO1 L2
and explain their significance. Describe the difference between
variables and constants in C.
27 Explain the difference between formatted and unformatted I/O 5 CO1 L2
operations in C.
28 Discuss the importance of compiling and executing a program. 5 CO1 L2
What steps are involved in this process?
29 Explain the difference between an algorithm and a flowchart and 5 CO1 L2
pseudocode.
30 Write a pseudocode , algorithm and flowchart for checking if a 5 CO1 L3
given number is a prime number.
Q
UNIT-II Marks CO BL
No.
1 Write a C program that reads a given integer number and checks 5 CO2 L3
whether it is a palindrome or not. A palindrome is a number that
has the same value even when it is reversed. Eg: 12321 is a
palindrome
2 Implement a C program that finds the largest and smallest digit 5 CO2 L5
in a given number using a loop. Prompt the user for the input
number and display the results.
3 Illustrate a C program that reads from the user an arithmetic 5 CO2 L3
operator and two operands, perform the corresponding
arithmetic operation on the operands using switch statements.
Page116 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104
4 What does the following program do? 5 CO2 L4
GR11D5104 #include <stdio.h>
GR11D5104 int main()
GR11D5104 {
char ch;
intvcnt = 0, ccnt=0;
for ( ch = getchar(); ch != ‘\n’; ch=getchar()){
if(ch==’a’ || ch==’e’ || ch==’i’ || ch==’o’ || ch==’u’ ||
ch==’A’ || ch==’E’ || ch==’I’ || ch==’O’ || ch==’U’)
vcnt++;
else if((ch>= ‘a’ &&ch<= ‘z’) || (ch>= ‘A’ &&ch<= ‘Z’))
ccnt++;
}
printf( “ %d %d\n”, vcnt, ccnt);
}
Rewrite the above program using while and switch constructs.
5 Bob has placed N objects in a row which are marked with 5 CO2 L4
a number equal to their weight in Kg. He wants to check
whether the objects are in increasing order of their weights or
not. Write a C program to help Bob.
6 Show how break and continue statements are used in a C 5 CO2 L3
program, with example. Also illustrate the valid places where
the programmer can apply break and Control Statement?
7 Interpret the working of switch statement with syntax and 5 CO2 L3
suitable example. Point out the differences
between else if ladder and switch statements.
8 Sketch the need for selection statements? Write the syntax and 5 CO2 L3
flowchart of if, if else, and cascaded if-else.
9 List the differences between while loop and do-while loop. write 5 CO2 L3
a C program to find sum of Natural numbers from 1 to N using
them.
10 How would you present a C code to find summation of two 5 CO2 L3
matrices?
11 Implement a C program that prints the Pascal's triangle using 5 CO2 L5
nested loops. Prompt the user for the number of rows and
display the triangle.
12 Implement a C program that finds the common elements 5 CO2 L5
between two arrays of integers. Display the common elements.
13 Interpret the working of looping statements in C with syntax 5 CO2 L3
and suitable example.
14 Alex has the grades of the students test as follows: 30.5, 32.2, 5 CO2 L4
20.7, 20.6, 31.0, 41.0, 27.7,26.0, 21.5, 26.0.
Sketch a C program to find the best grade , worst grade and
average grade his students.
15 Model a C program to search an element using linear search 5 CO2 L3
technique. Also list its merits and demerits.
16 Write a C program to search an element using binary technique. 5 CO2 L3
Also list its merits and demerits.
17 Apply linear search on the data 32,77,16,10,25,19, to search for 5 CO2 L3
the value “25”.Also write the algorithm.
18 What actions would you take to perform binary search to find 5 CO2 L3
the value 20 and 45 on the data 12,20,34,38,45,50,67,89.
Page117 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104
19 Write a C program to multiply two matrices of order m*n and 5 CO2 L3
GR11D5104 p*q.
GR11D5104
20 Write a C program that generates all possible permutations of a 5 CO2 L5
GR11D5104
given set of numbers using recursion. Display each permutation.
21 Describe how elements in a one-dimensional array are accessed 5 CO2 L2
and manipulated in C with an example program.
22 Develop a C program to transpose a given two-dimensional 5 CO2 L3
array
23 Create a C program that takes a two-dimensional array as input 5 CO2 L3
and calculates the sum of each row and column.
24 What are the key differences between linear search and binary 5 CO2 L2
search?
25 What is the significance of the array index in C programming? 5 CO2 L2
Explain with an example.
26 How does a switch-case statement differ from an if-else 5 CO2 L2
statement? Provide an example.
27 What are the conditions under which an exit and return 5 CO2 L2
statements would be used in a C program?
28 Write a C program that demonstrates the use of continue and 5 CO2 L3
break statements inside a for loop.
29 Create a C program that uses nested if-else statements to 5 CO2 L4
categorize a person's age into child, teenager, adult, or senior
citizen based on user input. Also analyze why is it difficult to
implement the same using switch case.
30 Write a C program using a do-while loop to repeatedly prompt 5 CO2 L3
the user for a number until they enter a negative number. Also
print the final sum.
Q
UNIT-III Marks CO BL
No.
1 Write a C function to find the largest and smallest in a given list 5 CO3 L3
of integers of size n using call by reference:
void minmax( int list[ ], int n, int *min, int *max);
2 Is it mandatory to declare main() function with return type 5 CO3 L4
as void or int. What will be the effect if there is no return type
declared for main() function?
3 Compare and contrast call by value and call by reference with 5 CO3 L4
suitable examples.
4 Write a program which will read ’n’ positive integer numbers 5 CO3 L3
from the users and compute the sum if the number can be
expressed as power of 2. The test whether a number can be
expressed as power of 2 will be done using a function
power_of_two(int a).
5 Differentiate between Actual Parameters and Formal 5 CO3 L3
Parameters? Give example.
6 Ram is working on a project which requires returning 5 CO3 L4
multiple values from a function. He observed that a return
statement can only be used to return a single value from a
function. How the function should be implemented so that
multiple values can be returned by Ram?
7 Identify the bug in the following function written to return the 5 CO3 L4
swapped values of two integer variables given:
Page118 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104 int swap( int *x, int *y)
GR11D5104 {
GR11D5104 int *temp;
GR11D5104 temp = x, x=y, y = temp;
}
Rewrite the bug free code snippet.
8 Bob wrote a program using functions to find the sum of two 5 CO3 L4
numbers whereas Alex wrote the statements to find the sum of
two numbers in the main() function only. Which of the two
methods is efficient in execution? Justify.
9 Write a C function isprime(num) that accepts an integer 5 CO3 L3
argument and returns 1 if the argument is a prime or 0
otherwise. Write a program that invokes this function to
generate prime numbers between the given ranges.
10 Analyze the concept of scope and lifetime of various storage 5 CO3 L4
class variables in C, discussing the visibility and accessibility of
variables within different blocks, functions, and program
modules.
11 How would you explain with an example the concept of 5 CO3 L3
recursion? Also discuss its merits and demerits.
12 Complete the function described below: 5 CO3 L3
Function Name: summon
Input Params: base address of string
Return Type: base address of summoned string Description: A
magician wants to generate summoning charms.
Example: For input string “firebolt”, the function should
produce “summon firebolt”.Do not use any inbuilt string
handling functions.
13 Write a C program to check if a given string is a palindrome or 5 CO3 L3
not.
14 Ram is conducting a study which is based on counting 5 CO3 L4
the number of cars crossing the highway. Every hour
he generates a random string containing sequence of
characters <rbwbwr…>, where r represents red color,
w denotes white color and b denotes blue color cars. The
string is forwarded to Shyam for analysis who computes
the number of red, blue and white color cars crossing Ram every
hour. Assume that Ram works for 5 hours in a day, helpShyam
generate a daily report containing the following:
i. Total number of different colour cars crossing Ram in a day.
iii. Total number of red colour cars crossing Ram in an hour.
15 How would you develop a C program to present the concept of 5 CO3 L3
array of strings to search for a string in a list of strings?
16 Design a C program to replace each alphabet in a string with its 5 CO3 L3
next letter except for letters ‘z’,’a’,’Z’,’A’.
Example : Input : Crazy Programmer
Output: DsazzQsphsannfs
17 Write a C program that counts the frequency of each character in 5 CO3 L5
a given string. Display the character frequencies.
18 How would you develop a C program to copy a string that 5 CO3 L4
contains a combination of digits and alphabets to another string
with only alphabets? Also determine the length of both the
Page119 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104 strings?
GR11D5104
19 How string is declared and initialized? Explain any four string 5 CO3 L4
GR11D5104 manipulation functions with examples.
GR11D5104
20 How would you demonstrate the following string handling 5 CO3 L3
functions (i) strcmp() (ii)strcat() (iii)strcpy()
21 Develop a C program that takes a string as input and counts the 5 CO3 L3
number of vowels and consonants without using any string
handling functions.
22 Implement a C program that reads multiple strings into an array 5 CO3 L3
of strings and then sorts them alphabetically.
23 Create a C program to copy one string to another without using 5 CO3 L3
the strcpy() function.
24 Explain how the strcmp() function works to compare two 5 CO3 L2
strings.
25 Explain how strings are represented in C. Also write about its 5 CO3 L2
declaration and initialization.
26 Describe the components of a user defined function in C with an 5 CO3 L2
example.
27 Create a C program that passes an array of integers to a function 5 CO3 L3
and finds the maximum and minimum value in the array.
28 Create a recursive and non recursive C function to generate the 5 CO3 L3
Fibonacci series up to a given number of terms.
29 Write a C program that uses different storage classes and 5 CO3 L3
demonstrates their scope and lifetime.
30 Explain the difference between call by value and call by 5 CO3 L2
reference with examples.
Q
UNIT-IV Marks CO BL
No.
1 Analyze the advantages and disadvantages of using pointers in 5 CO4 L3
C when compared to other variable types like arrays or
structures.
2 Can you create a C function that reverses the elements of an 5 CO4 L4
array using pointers?
3 Given a 2D array in C, can you implement a function that finds 5 CO4 L3
the sum of all elements in the array using pointer arithmetic?
4 Critically analyze the potential issues and risks related to pointer 5 CO4 L4
misuse, such as dangling pointers, memory leaks, and accessing
invalid memory locations, and propose strategies to mitigate
these problems.
5 Compare and contrast pointers and arrays in C, highlighting 5 CO4 L4
their similarities and differences in terms of memory
representation, syntax, and usage.
6 Given an array and a target value, can you write a C program to 5 CO4 L3
find the index of the target value using pointer arithmetic?
7 Can you develop a C program that counts the number of vowels 5 CO4 L3
in a given string using pointers and pointer arithmetic?
8 Implement a C program that reverses the order of elements in an 5 CO4 L5
array using pointers. Use a function that prompts the user for
the array elements and display the reversed array.
9 Implement a C program that performs a circular shift on the 5 CO4 L5
elements of an array using pointers. Prompt the user for the
Page120 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104 array elements and display the shifted array.
GR11D5104
10 Investigate the concept of pointer arithmetic in C, including the 5 CO4 L4
GR11D5104
rules, limitations, and potential dangers associated with pointer
GR11D5104
arithmetic operations.
11 How would you implement a C function that finds the tallest 5 CO4 L3
student among a group of students represented by an array of
structures?
12 Compare and contrast structures and unions in C, highlighting 5 CO4 L4
their similarities and differences in terms of memory
representation, usage, and potential applications.
13 Can you develop a C program that creates a structure to 5 CO4 L3
represent a date with day, month, and year attributes, and then
validates if a given date is valid or not?
14 Analyze the concept of nested structures in C, discussing how 5 CO4 L4
nested structures can be used to represent complex data
hierarchies and how they impact memory organization and
access.
15 Write a program to maintain a record of ‘n’ employee detail 5 CO4 L4
using an array of structures with three fields(id, name , salary)
and print the details of employees whose salary is above 5000.
16 How would you define a union in C to represent a variable that 5 CO4 L3
can hold either an integer or a floating-point value? Also write
the program.
17 Examine the role of structures in handling large amounts of 5 CO4 L4
heterogeneous data discussing how structures can be used to
read and write them efficiently in comparison with arrays.
18 Implement a C program that stores information about employees 5 CO4 L5
(name, employee ID, and salary) using a structure. Sort the
employees based on their salaries in ascending order and display
the sorted list.
19 Write a C program that reads data for a customer (name, 5 CO4 L5
account number, and balance) using a structure. Allow users to
transfer money between two accounts and update the balances
accordingly.
20 Suppose you have a structure in C that represents a point in 2D 5 CO4 L3
space with x and y coordinates, how would you write a C
program to calculate the distance between two points?
21 What is a void pointer, and when would you use it in C 5 CO4 L2
programming?
22 Explain the significance of a null pointer in C. How is it 5 CO4 L2
different from an uninitialized pointer? Give an example.
23 Implement a C program that demonstrates the use of a pointer to 5 CO4 L3
a structure. Include accessing and modifying the structure
members.
24 Write a C program that demonstrates pointer arithmetic by 5 CO4 L3
calculating the difference between two pointers pointing to
elements in an array. Also print the array elements.
25 Develop a C program that uses a function pointer to call 5 CO4 L3
different functions based on user input.
26 What is the purpose of the typedef keyword when used with 5 CO4 L2
structures? Provide an example of how does it work to ease the
job.
Page121 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104
27 Explain the concept of nested structures with a brief example. 5 CO4 L2
GR11D5104
28 Write a C program that uses typedef to create an alias for a 5 CO4 L3
GR11D5104
structure representing a date (with day, month, and year fields)
GR11D5104
and uses it to declare and initialize a date variable. Also read
and print your date of birth.
29 Implement a C program that defines a nested structure to 5 CO4 L3
represent a book (with title, author, and a nested structure for
publication details including year and publisher)
30 Create a C program that passes a structure representing a point 5 CO4 L3
(with x and y coordinates) to a function, which calculates the
distance from the origin.
Q
UNIT-V Marks CO BL
No.
1 Evaluate the trade-offs between using sequential file access and 5 5 L4
random file access in C, discussing the advantages and
disadvantages of each approach in different scenarios.
2 Illustrate various file handling functions with examples? 5 5 L3
3 Can I create a customized Head File in C language? Support 5 5 L4
with suitable program?
4 Explain fseek( ) function with help of a C suitable program. 5 5 L3
Explain each of the parameter it takes in detail.
5 A file consists of binary data. Write a program to read and count 5 5 L4
the number of 0’s and 1’s in it. Write the individual count in a
separate file.
6 Write a program to find area of a circle, triangle and square 5 5 L4
using macros.
7 How would you write a C program to open a file, read its 5 5 L3
contents, and display them on the screen?
8 Implement a C program that copies the contents of one file to 5 5 L5
another file. Prompt the user for the input and output file names
through command line. Also print the number of characters in
the file.
9 How would you implement a C program that searches for a 5 5 L3
specific character in a text file, counts its occurrences, and
displays the result?
10 Analyze the advantages and disadvantages of using different file 5 5 L4
modes (e.g., "r," "w," "a") in C, discussing their implications for
reading, writing, and appending data.
11 Discuss the steps involved in opening and closing a file in C. 5 5 L4
Explain the significance of file pointers and their manipulation
during file operations.
12 Analyze the error handling techniques in C when working with 5 5 L4
files, discussing strategies for detecting and handling file-related
errors like file not found or permission issues.
13 Implement a C program that reads data from a file containing a 5 5 L5
matrix and calculates the transpose of the matrix. Write the
transposed matrix to another file.
14 Compare and contrast text files and binary files in C, discussing 5 5 L4
their differences in terms of storage efficiency, portability, and
ease of data manipulation.
Page122 of 194
CODE:GR24A1006 GR24
GR11D5104
GR11D5104
15 Given a C program that uses multiple header files, can you 5 5 L3
GR11D5104
explain the purpose of the #include directive and how it is used
GR11D5104 to include header files in a program?
GR11D5104
16 Can you explain the purpose and usage of the #define 5 5 L3
and #undef directive in C, and provide an example where it
would be useful?
17 Can you create a C program that uses the #define directive to 5 5 L3
create a symbolic constant for the value of pi and then uses it in
calculations to find area and circumference of a circle
?Also store the result in a file?
18 How would implement typedef ,enum in C 5 5 L3
19 Write a C program that accepts a file name as a command line 5 5 L3
argument, opens the file, reads its contents, and displays them
on the screen.
20 Given a C program that takes multiple command line 5 5 L3
arguments, can you implement a function to calculate the sum
of all numeric arguments and display the result?
21 Compare and contrast various file accessing modes. 5 5 L3
22 Implement a C program to display the contents of a file in 5 5 L3
reverse order. Read the filename from command line.
23 Illustrate the usage of fread() and fwrite() functions using an 5 5 L3
example program.
24 Differentiate between the following: 5 5 L3
i. Typedef vs #define
ii. Command line arguments vs Function arguments
25 Develop a C program to calculate area of a circle and rectangle 5 5 L3
using user defined header files?
26 Illustrate the use of #ifdef and #ifndef in managing conditional 5 5 L2
compilation.
27 Compare the usage of #include with double quotes ("") versus 5 5 L4
angle brackets (<>) in C.
28 Write a C program that uses #ifdef to include or exclude code 5 5 L3
segments based on whether a macro is defined.
29 Implement a C program that demonstrates the use of fseek() and 5 5 L3
ftell() for random access in a binary file.
30 Create a C program that writes an array of integers to a binary 5 5 L3
file and then reads them back into another array.
2818
Page123 of 194