0% found this document useful (0 votes)
5 views127 pages

Study Note For C Programming

The document outlines a C Programming course, detailing its objectives and unit contents, which cover fundamental concepts such as data types, control structures, functions, arrays, and pointers. It emphasizes the importance of C as a versatile and widely-used programming language, suitable for both systems and applications programming. Additionally, it provides insights into the history of C, its syntax, and the structure of a basic C program.

Uploaded by

Subham Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views127 pages

Study Note For C Programming

The document outlines a C Programming course, detailing its objectives and unit contents, which cover fundamental concepts such as data types, control structures, functions, arrays, and pointers. It emphasizes the importance of C as a versatile and widely-used programming language, suitable for both systems and applications programming. Additionally, it provides insights into the history of C, its syntax, and the structure of a basic C program.

Uploaded by

Subham Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Course Code: 103 Course Title: C Programming – I

1. Course Overview:

Course Objectives: However, the process of learning a computer language will also be emphasized.
Emphasis is also on semantics and problem solving. C is a powerful, flexible, portable and elegantly
structured
After completing this course, programming language. Since C combines the features of high students
will be able to -level language with the elements of the assembler, it is suitable for both systems and
applications programming and is undoubtedly the most widely used general-purpose language today.

Unit Contents

1 Introduction to C language
Origins of C, Character Set of C, C Tokens, Keywords and Identifiers, Constants, Variables,
Data types,
Declaration of variables, Declaration of variables as constant, Operators, Types of operators,
Precedence and associativity, Expression, Type conversions in expressions, Input and Output
functions - printf(), scanf(), getchar(), putchar(), Formatted input and formatted output.
2 Decision Control and looping
Introduction, Control Statements- Sequential, Selection, Iteration Statements, branching
structure- if statement, if-else statement, Nested if-else statement, else if Ladder, Conditional
operator, switch statement, Loop control structures- while loop, do-while loop, for loop,
nested for loop, Jump statements-break, continue, go to
3 Functions
Introduction, Purpose of function, Function declaration/ Function prototype, Function
definition, Function call, return statement, Function parameters, Types of functions, Call by
value, Storage classes, Recursion, Examples on recursive function
4 Arrays and Strings
Introduction to one-dimensional Array, Definition, Declaration, Initialization, Accessing and
displaying array elements, Arrays and functions, Introduction to two-dimensional Array,
Definition, Declaration, Initialization, Accessing and displaying array elements, Introductions
to Strings, Definition, Declaration, Initialization, Input, output statements for strings,
Standard library functions, Implementations with standard library functions. Structures and
union Introduction to structure, defining a structure, declaring structure variables, accessing
structure members, nested structure, Array of structure, Array within structure, Introduction
to union, Definition, Declaration, Differentiate between structure and union. Pointers
Introduction to pointer, Definition, Declaring and Initializing pointer variable, Indirection
operator and address of operator, Accessing variable through its pointer, Pointer arithmetic,
Dynamic memory allocation, Pointers & Functions, Pointers & Array, Pointers & Structures.
Algorithms

1
Introduction to C language
 Origins of C
 Character Set of C
 C Tokens, Keywords and Identifiers,
 Constants, Variables, Data types,
 Declaration of variables, Declaration of variables as constant,
 Operators, Types of operators,
 Precedence and associativity,
 Expression, Type conversions in expressions,
 Input and Output functions - printf(), scanf(), getchar(), putchar(), • Formatted input and formatted
output.

Origins and overview of C,

Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on
the DEC PDP-11 computer in 1972.

In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known
as the K&R standard.

The UNIX operating system, the C compiler, and essentially all UNIX application programs have been written
in C. C has now become a widely used professional language for various reasons −

• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Facts about C
• C was invented to write an operating system called UNIX.

• C is a successor of B language which was introduced around the early 1970s.

• The language was formalized in 1988 by the American National Standard Institute (ANSI).

• The UNIX OS was totally written in C.

• Today C is the most widely used and popular System Programming Language.

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

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

2
Why use C?
C was initially used for system development work, particularly the programs that make-up the operating
system. C was adopted as a system development language because it produces code that runs nearly as fast
as the code written in assembly language. Some examples of the use of C might be −

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

Hello World Example


A C program basically consists of the following parts −

• Pre-processor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Let us look at a simple code that would print the words "Hello World" −

#include<stdio.h>

int main()

/* my first program in C */

printf("Hello, World! \n");

return 0;

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

• The first line of the program #include <stdio.h> is a pre-processor command, which tells a C compiler
to include stdio.h file before going to actual compilation.

• The next line int main() is the main function where the program execution begins.

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

• The next line printf(...) is another function available in C which causes the message "Hello, World!" to
be displayed on the screen.

• The next line return 0; terminates the main() function and returns the value 0.

Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string
literal, or a symbol. For example, the following C statement consists of five tokens −

printf("Hello, World! \n");

The individual tokens are −

printf

"Hello, World! \n"

);

Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended
with a semicolon. It indicates the end of one logical entity.

Given below are two different statements −

printf("Hello, World! \n");


return0;
Comments
Comments are like helping text in your C program and they are ignored by the compiler. They start with
/* and terminate with the characters */ as shown below −

/* my first program in C */
You cannot have comments within comments, and they do not occur within a string or character literals.

4
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier
starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and
digits (0 to 9).

C does not allow punctuation characters such as @, $, and % within identifiers. C is a case sensitive
programming language. Thus, Manpower and manpower are two different identifiers in C. Here are some
examples of acceptable identifiers −

mohd zara abc move_name a_123 myname50


_temp j a23b9 retVal

Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or
variables or any other identifier names.
auto Else Long switch
break Enum Registe typedef
r
case extern Return union
char Float Short unsigned
const For Signed void
continue Goto Sizeof volatile
default If Static while
do Int Struct _Packed
double

Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally
ignores it.

Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace
separates one part of a statement from another and enables the compiler to identify where one element in
a statement, such as int, ends and the next element begins. Therefore, in the following statement −

int age;

there must be at least one whitespace character (usually a space) between int and age for the compiler to be
able to distinguish them. On the other hand, in the following statement −

fruit= apples + oranges;// get the total fruit

no whitespace characters are necessary between fruit and =, or between = and apples, although you are free
to include some if you wish to increase readability.
5
C - Data Types

Data types in c refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is
interpreted.

The types in C can be classified as follows −


[Link]. Types & Description

1
Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define variables that can only
assign certain discrete integer values throughout the program.
3
The type void
The type specifier void indicates that no value is available.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types
and (e) Function types.
The array types and structure types are referred collectively as the aggregate types. The type of a function
specifies the type of the function's return value. We will see the basic types in the following section, where as
other types will be covered in the upcoming chapters.

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

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

short 2 bytes -32,768 to 32,767


unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
To get the exact size of a type or a variable on a platform, you can use the sizeof operator. The expressions
sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get the size
of int type on any machine –

6
#include<stdio.h> #include<limits.h> int main(){

printf("Storage size for int : %d \n",sizeof(int));

return 0;

When you compile and execute the above program, it produces the following result on Linux −

Storage size for int: 4


Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and value ranges
and their precision −
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

The header file float.h defines macros that allow you to use these values and other details about the binary
representation of real numbers in your programs. The following example prints the storage space taken by
a float type and its range values −

#include<stdio.h>

#include<float.h>

int main()

printf("Storage size for float : %d \n",sizeof(float)); printf("Minimum float positive value: %E\n", FLT_MIN );

printf("Maximum float positive value: %E\n", FLT_MAX ); printf("Precision value: %d\n", FLT_DIG );

return0;

When you compile and execute the above program, it produces the following result on Linux −

Storage size for float : 4


Minimum float positive value: 1.175494E-38
Maximum float positive value: 3.402823E+38
Precision value: 6

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

[Link]. Types & Description

1 Function returns as void


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

2 Function arguments as void


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

3 Pointers to void
A pointer of type void * represents the address of an object, but not its type. For
example, a memory allocation function void *malloc( size_t size ); returns a pointer
to void which can be casted to any data type.
C - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in C has a specific type, which determines the size and layout of the variable's memory; the range of values
that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with
either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based
on the basic types explained in the previous chapter, there will be the following basic variable types −

[Link]. Type & Description

1 char: Typically a single octet(one byte). This is an integer type.

2 int: The most natural size of integer for the machine.

3 float: A single-precision floating point value.

4 Double: A double-precision floating point value.

5 void: Represents the absence of type.


C programming language also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study
only basic variable types.

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable
definition specifies a data type and contains a list of one or more variables of that type as follows −

type variable list;

8
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined
object; and variable_list may consist of one or more identifier names separated by commas. Some valid
declarations are shown here −

int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables
named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal
sign followed by a constant expression as follows −

type variable_name = value;


Some examples are −

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z. char x
x= 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized with NULL
(all bytes have the value 0); the initial value of all other variables are undefined.

Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given type
and name so that the compiler can proceed for further compilation without requiring the complete detail
about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs
actual variable definition at the time of linking the program.

A variable declaration is useful when you are using multiple files and you define your variable in one of the
files which will be available at the time of linking of the program. You will use the keyword extern to
declare a variable at any place. Though you can declare a variable multiple time in your C program, it can
be defined only once in a file, a function, or a block of code.

Example
Try the following example, where variables have been declared at the top, but they have been defined and
initialized inside the main function −

9
#include<stdio.h> //
Variable declaration:
Extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b; int c; float f;

/* actual initialization */
a =10; b =20; c = a+b;
printf("value of c : %d \n", c);
f=70.0/3.0;
printf("value of f : %f \n", f); return
0;
}When the above code is compiled and executed, it produces the following result −

value of c : 30 value of f : 23.333334


The same concept applies on function declaration where you provide a function
name at the time of its declaration and its actual definition can be given anywhere
else. For example −

// function declaration int


func();
int main(){ // function call
int i = func();
}

10
// function definition int
func()
{
return0;
}
Lvalues and Rvalues in C
There are two kinds of expressions in C −
• lvalue − Expressions that refer to a memory location are called "lvalue"
expressions. An lvalue may appear as either the left-hand or right-hand
side of an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some
address in memory. An rvalue is an expression that cannot have a value
assigned to it which means an rvalue may appear on the right-hand side
but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an
assignment. Numeric literals are rvalues and so they may not be assigned and
cannot appear on the left-hand side. Take a look at the following valid and invalid
statements −

int g = 20; // valid statement


10 = 20; // invalid statement; would generate compile-time error

C - Constants and Literals


Constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified
after their definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base
or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

11
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively.
The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −

212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −

85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and
an exponent part. You can represent floating point literals either in decimal form
or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or
both; and while representing exponential form, you must include the integer part, the
fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −

3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
12
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of
char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a backslash
for example, newline (\n) or tab (\t).
Here, you have a list of such escape sequence codes −

Following is the example to show a few escape sequences characters −

#include<stdio.h> int main(){

printf("Hello\tWorld\n\n"); return0;

}
When the above code is compiled and executed, it produces the following result −
Hello World

String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that
are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using
white spaces.
Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor.
• Using const keyword.
13
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −

#define identifier value


The following example explains it in detail −

#include<stdio.h>

#define LENGTH 10

#defineWIDTH 5

#define NEWLINE '\n'

int main(){ int area;

area= LENGTH * WIDTH;

printf("value of area : %d", area);

printf("%c", NEWLINE); return0;

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

value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows −

const type variable = value.


The following example explains it in detail −

14
#include<stdio.h>

int main()

Const int LENGTH=10; const int WIDTH=5; const char NEWLINE ='\n';

int area;

area= LENGTH * WIDTH;


printf ("value of area : %d", area);

printf("%c", NEWLINE);

return 0.

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

value of area: 50
Note that it is a good programming practice to define constants in CAPITALS.

C - Operators

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

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators

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

Show Examples

Operator Description Example

+ Adds two operands. A + B = 30

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

* Multiplies both operands. A * B = 200


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

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

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

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

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

Operator Description Example

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

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

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

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

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

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

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

Show Examples

Operator Description Example

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

|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is true.
the condition becomes true.

! Called Logical NOT Operator. It is used to reverse the logical state of its !(A && B) is true.
operand. If a condition is true, then Logical NOT operator will make it
false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows

p Q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100

B = 0000 1101

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

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

17
Show Examples

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12, i.e., 0000 1100
both operands.

| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 49, i.e., 0011 0001
but not both.

~ Binary Ones Complement Operator is unary and has the (~A ) = -60, i.e,. 1100 0100 in
effect of 'flipping' bits. 2's complement form.

<< Binary Left Shift Operator. The left operands value is moved A << 2 = 240 i.e., 1111 0000
left by the number of bits specified by the right operand.

>> Binary Right Shift Operator. The left operands value is A >> 2 = 15 i.e., 0000 1111
moved right by the number of bits specified by the right
operand.
Assignment Operators
The following table lists the assignment operators supported by the C language −

Show Examples

Operator Description Example

= Simple assignment operator. Assigns values from right C=A+B


side operands to left side operand will assign the value of A + B to C

+= Add AND assignment operator. It adds the right C += A is equivalent to C = C + A


operand to the left operand and assign the result to the
left operand.

-= Subtract AND assignment operator. It subtracts the C -= A is equivalent to C = C - A


right operand from the left operand and assigns the
result to the left operand.

*= Multiply AND assignment operator. It multiplies the C *= A is equivalent to C = C * A


right operand with the left operand and assigns the
result to the left operand.

18
/= Divide AND assignment operator. It divides the left C /= A is equivalent to C = C / A
operand with the right operand and assigns the result
to the left operand.

%= Modulus AND assignment operator. It takes modulus C %= A is equivalent to C = C % A


using two operands and assigns the result to the left
operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C<<2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternary


Besides the operators discussed above, there are a few other important operators including sizeof and ?
: supported by the C Language.

Show Examples

Operator Description Example

sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.

& Returns the address of a variable. &a; returns the actual address of the variable.

* Pointer to a variable. *a;

?: Conditional Expression. If Condition is true ? then value X : otherwise value Y

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

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.

19
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.

Show Examples

Category Operator Associativity

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


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

Multiplicative */% Left to right

Additive +- Left to right


Shift <<>> Left to right

Relational <<= >>= Left to right


Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

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

Comma , Left to right

Expressions:
• Expressions is a sequence of operators and operands that specifies computation of a value. An expression
may consist of single entity or some combination of such entities interconnected by one or more operators.
• All expression represents a logical connection that’s either true or false.
• Thus, logical type expression represents numerical quantities.

In C every expression evaluates to a value i.e., every expression results in some value of a certain type that
can be assigned to a variable. Some examples of expression are shown in the table given below.

20
A+b

3.14*r*r

a*a+2*a*b+b*b

EXAMPLE

1 #include<stdio.h>
2 #include<conio.h>
3 int main()
4 {
5 int a=123 , b;
6 b=a+2;
7 clrscr();
8 printf(“Value of a = %d\n”,a);
9 printf(“Value of b =%d”,b);

10 getch();

11 return 0;
12 }
Output:

Value of a = 123
Value of b = 125

C - Type Casting

Type casting is a way to convert a variable from one data type to another data type. For example, if you
want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the
values from one type to another explicitly using the cast operator as follows −

(type_name) expression
Consider the following example where the cast operator causes the division of one integer variable by another
to be performed as a floating-point operation −

#include<stdio.h>

main()

int sum =17, count =5;

21
double mean;

mean=(double) sum / count;

printf("Value of mean : %f\n", mean );

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

Value of mean : 3.400000


It should be noted here that the cast operator has precedence over division, so the value of sum is first
converted to type double and finally it gets divided by count yielding a double value.

Type conversions can be implicit which is performed by the compiler automatically, or it can be specified
explicitly through the use of the cast operator. It is considered good programming practice to use the cast
operator whenever type conversions are necessary.
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are
converted either to int or unsigned int. Consider an example of adding a character with an integer −

#include<stdio.h>

main()

{ int i=17; char c ='c';/* ascii value is 99 */

int sum; sum= i + c; printf("Value of sum :

%d\n", sum );

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

Value of sum : 116


Here, the value of sum is 116 because the compiler is doing integer promotion and converting the value of 'c'
to ASCII before performing the actual addition operation.

Usual Arithmetic Conversion


The usual arithmetic conversions are implicitly performed to cast their values to a common type. The
compiler first performs integer promotion; if the operands still have different types, then they are converted
to the type that appears highest in the following hierarchy −

22
The usual arithmetic conversions are not performed for the assignment operators, nor for the logical
operators && and ||. Let us take the following example to understand the concept −

#include<stdio.h> main(){
int i=17; char c ='c';/* ascii value is 99 */
float sum; sum= i + c; printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed, it produces the following result −

Value of sum: 116.000000


Here, it is simple to understand that first c gets converted to integer, but as the final value is double, usual
arithmetic conversion applies and the compiler converts i and c into 'float' and adds them yielding a 'float'
result.

23
Input and output functions

I/O FUNCTIONS DESCRIPTION


Scanf The usually used input statement in C is scanf () function.
getchar function will accept a character from the console or from a file, displays
Getchar
immediately while typing and we need to press Enter key for proceeding.
It is used to scan a line of text from a standard input device. The gets() function will
Gets
be terminated by a newline character.
The usually used output statement in C is printf () function.
Printf
Putchar putchar function displays a single character on the screen.
It is used to display a string on a standard output device.

Puts

Scanf() :

• This function is usually used as an input statement.

• The format string must be a text enclosed in double quotes. It contains the information for
interpreting the entire data for connecting it into internal representation in memory. Example:
integer (%d) , float (%f) , character (%c) or string (%s).
• The argument list contains a list of variables each preceded by the address list and separated by
comma.
• The number of argument is not fixed; however corresponding to each argument there should be a
format specifier. Inside the format string the number of argument should tally with the number of
format specifier.

Syntax : scanf(“format string”, argument list);

C – scanf() EXAMPLE PROGRAM :

if i is an integer and j is a floating-point number, to input these two numbers we may use

scanf(“%d%f”, &i, &j);

#include<stdio.h>
#include<conio.h>
int main()
{
char a;

24
int b;
float c;
double d;
clrscr();
printf(“Enter a character \n”);
scanf(“%c”,&a);
printf(“Enter an Integer \n”);
scanf(“%d”,&b);
printf(“Enter a SP float no: \n”);
scanf(“%f”,&c);
printf(“Enter a DP float no : \n”);
scanf(“%if”,&d);
getch();
return 0; }

Enter a character
X
Enter an integer
6
Enter a SP float no
3.140000
Enter a DP float no
15 3.1400000e+10

Getchar() :
getchar() function will accept a character from the console or from a file, displays immediately while typing and
we need to press Enter key for proceeding.

Syntax :
int getchar(void);
It returns the unsigned char that they [Link] end-of-file or an error is encountered it return EOF.

This function reads a single character from the standard input device, the keyboard being assumed because that
is the standard input device, and assigns it to the variable “a”.

C – EXAMPLE PROGRAM:
#include<stdio.h>
#include<conio.h>
intmain()
{
chara;
clrscr();
printf(“Enteracharacter\n”);
a=getchar();
printf(“Given character is%c\n”,a);
25
getch();
return0;
}
Gets :
Gets function is used to scan a line of text from a standard input device. This function will be terminated by
a newline character. The newline character won’t be included as part of the string. The string may include
white space characters.

Syntax :

char *gets(char *s);

This function is declared in the header file stdio.h. It takes a single argument. The argument must be a data item
representing a string. On successful completion, shall return a pointer to string s.

C – EXAMPLE PROGRAM :

#include<stdio.h>

#include<conio.h>

intmain()

char*str;

clrscr();

printf(“Enterastring\n”);

gets(str);

printf(“Given stringis %s”,str);

getch();

return0;

Output:

Enter a string
Good morning
Given string is Good morning

26
Printf :
The usually used output statement is printf (). It is one of the library functions.

Syntax : printf (“format string”, argument list);

Format string may be a collection of escape sequence or/and conversion specification or/and string constant.
The format string directs this function to display the entire text enclosed within the double quotes without
any change.

Escape sequence:
Escape sequence is a pair of character. The first letter is a slash followed by a character. Escape sequence
help us to represent within the format string invisible and non-printed character although there are
physically two characters in any escape sequence. It represents only one. The various escape sequences
are

Escape sequence Meaning


\n New line
\t Tab
\b Back space
\a Bell
\o Null character
\? To print question mark
\\ To print slash
\’ To print single quote
\” To print double quote
Conversion specification:
Conversion specification is also a pair of character. it is preceded by % and followed by a quote which may be
a character. The Conversion specification inscribes the printf () function that it could print some value at that
location in the text. The Conversion characters supported by C are Conversion

character Meaning

%d Data item is displayed as a signed decimal integer.

%i Data item is displayed as a single decimal integer.

%f Data item is displayed as a floating-point value without an exponent.

%c Data item is displayed as a single character.

27
%e Data item is displayed as a floating-point value with an exponent.

Data item is displayed as a floating-point value using either e-type


%g
or f-type conversion depending on value.

%o Data item is displayed as an octal integer, without a leading zero.

%s Data item is displayed as string.

%u Data item is displayed as an unsigned decimal integer.

%x Data item is displayed as a hexadecimal integer, without a leading 0x.

C – PRINTF EXAMPLE PROGRAM:

#include<stdio.h>
#include<conio.h>
intmain()
{
char a=’x’;
int b=10;
float c=3.14;
doubled=3.14e+10;
clrscr();
printf(“Charactera=%c\n”,a);
printf(“Integerb=%d\n”b);
printf(“SP floatno:c=%f\n”,c);
printf(“DP floatno:d=%e\n”,d);
getch();
return0;
}
Output :
Character a= x
Integer b= 10;
SP float no : 3.140000
DP float : 3.140000e+10

28
Unit-2 Decision Control and looping
Introduction, Control Statements- Sequential, Selection, Iteration Statements, Branching structure- if
statement, if-else statement, Nested if-else statement, else if Ladder, Conditional operator, switch statement,
Loop control structures- while loop, do-while loop, for loop, Nested for loop, Jump statements-break,
continue, go to

C - Decision Making
Decision making structures require that the programmer specifies one or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is determined
to be true, and optionally, other statements to be executed if the condition is determined to be false.

Show below is the general form of a typical decision-making structure found in most of the programming
languages −

C programming language assumes any non-zero and non-null values as true, and if it is either zero or null,
then it is assumed as false value.

C programming language provides the following types of decision making statements.

[Link]. Statement & Description

1 if statement
An if statement consists of a boolean expression followed by one or more statements.

2 if...else statement

An if statement can be followed by an optional else statement, which executes when


the Boolean expression is false.

29
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).

4 switch statement
A switch statement allows a variable to be tested for equality against a list of values.

5 nested switch statements


You can use one switch statement inside another switch statement(s).
C - if statement

An if statement consists of a Boolean expression followed by one or more statements.

Syntax
The syntax of an 'if' statement in C programming language is −

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be executed.
If the Boolean expression evaluates to false, then the first set of code after the end of the 'if' statement (after
the closing curly brace) will be executed.

C programming language assumes any non-zero and non-null values as true and

if it is either zero or null, then it is assumed as false value.

Flow Diagram

30
Example

#include <stdio.h> int

main () {

/* local variable definition */ int

a = 10;

/* check the boolean condition using if statement */ if(

a < 20 ) {

/* if condition is true then print the following */ printf("a

is less than 20\n" );

printf("value of a is : %d\n", a);

return 0;

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

a is less than 20;


value of a is : 10

C - if...else statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression
is false.
Syntax
The syntax of an if...else statement in C programming language is −

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will
be executed.

31
C programming language assumes any non-zero and non-null values as true, and if it is either
zero or null, then it is assumed as false value. Flow Diagram

Example
#include<stdio.h> int

main (){

/* local variable definition */ int

a =100;

/* check the boolean condition */ if(

a <20){

/* if condition is true then print the following */


printf("a is less than 20\n");

}else{

/* if condition is false then print the following */ printf("a

is not less than 20\n");

} printf("value of a is : %d\n",

a); return0;

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

a is not less than 20;


value of a is : 100

If...else if...else Statement


An if statement can be followed by an optional else if...else statement, which is very useful to test various
conditions using single if...else if statement.

When using if...else if..else statements, there are few points to keep in mind −

• An if can have zero or one else's and it must come after any else if's.

• An if can have zero to many else if's and they must come before the else.

• Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax
The syntax of an if...else if...else statement in C programming language is −

if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */ }
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */ }
else {
/* executes when the none of the above condition is true */ }

Example
#include<stdio.h> int

main ()

/* local variable definition */


int a =100;

/* check the boolean condition */

if( a ==10)

/* if condition is true then print the following */

printf("Value of a is 10\n");

33
}

elseif( a ==20)

/* if else if condition is true */

printf("Value of a is 20\n");

}elseif( a ==30)

/* if else if condition is true */ printf("Value

of a is 30\n");

}else

/* if none of the conditions is true */

printf("None of the values is matching\n");

printf("Exact value of a is: %d\n", a );

return0;

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

None of the values is matching


Exact value of a is: 100

C - Nested if statements

It is always legal in C programming to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).

Syntax
The syntax for a nested if statement is as follows –

34
if( boolean_expression 1)
{

/* Executes when the boolean expression 1 is true */


if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}}
You can nest else if...else in the similar way as you have nested if statements.

Example

#include <stdio.h> int

main ()

/* local variable definition

*/ int a = 100; int b = 200;

/* check the boolean condition */ if(

a == 100 )

/* if condition is true then check thefollowing */

if( b == 200 )

/* if condition is true then print the following */

printf("Value of a is 100 and b is 200\n" );

} }

printf("Exact value of a is : %d\n", a );


printf("Exact value of b is : %d\n", b );
return 0;
}
When the above code is compiled and executed, it produces the following result −

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200

35
C - Switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each switch case.

Syntax
The syntax for a switch statement in C programming language is as follows −

switch(expression){ case

constant-expression :

statement(s);

break;/* optional */

case constant-expression : statement(s);

break;

/* optional */

/* you can have any number of case statements

*/ default:/* Optional */ statement(s);

}
The following rules apply to a switch statement −

• The expression used in a switch statement must have an integral or enumerated type, or be of a class
type in which the class has a single conversion function to an integral or enumerated type.

• You can have any number of case statements within a switch. Each case is followed by the value to be
compared to and a colon.

• The constant-expression for a case must be the same data type as the variable in the switch, and it
must be a constant or a literal.

• When the variable being switched on is equal to a case, the statements following that case will execute
until a break statement is reached.

• When a break statement is reached, the switch terminates, and the flow of control jumps to the next
line following the switch statement.

• Not every case needs to contain a break. If no break appears, the flow of control will fall through to
subsequent cases until a break is reached.

• A switch statement can have an optional default case, which must appear at the end of the switch.
The default case can be used for performing a task when none of the cases is true. No break is needed
in the default case.

36
Flow Diagram

Example
#include<stdio.h>

int main ()

/* local variable definition

*/ char grade ='B';

switch(grade)

{ case'A':

printf("Excellent!\n");

break;

case'B':

case'C': printf("Well done\n");

break; case'D':

printf("You passed\n");

37
break; case'F':

printf("Better try

again\n"); break;

default:

printf("Invalid grade\n");

printf("Your grade is %c\n",

grade ); return 0;

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

Well done
Your grade is B

C - Nested switch statements


It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants
of the inner and outer switch contain common values, no conflicts will arise.

Syntax
The syntax for a nested switch statement is as follows −

switch(ch1)
{

case 'A':
printf("This A is part of outer switch" );

switch(ch2)
{ case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example

38
#include<stdio.h>
int main ()
{
/* local variable definition */
int a =100; int b =200;
switch(a)
{
case100: printf("This is part of outer switch\n", a );
switch(b)
{
case200: printf("This is part of inner switch\n", a );
}}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return0;}
When the above code is compiled and executed, it produces the following result −

This is part of outer switch


This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

The ?: Operator
We have covered conditional operator? In the previous chapter which can be used to replace

if...else statements. It has the following general form −

Exp1? Exp2: Exp3;


Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a? Expression is determined like this −

• Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire?
expression.

• If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

C - Loops
You may encounter situations, when a block of code needs to be executed several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first, followed
by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

39
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the
general form of a loop statement in most of the programming languages −

C programming language provides the following types of loops to handle looping requirements.

[Link]. Loop Type & Description

1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.

3 do...while loop
It is more like a while statement, except that it tests the condition at the end of the loop
body.

4 nested loops
You can use one or more loops inside any other while, for, or do..while loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.

C supports the following control statements.

40
[Link]. Control Statement & Description

1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

3 goto statement
Transfers control to the labeled statement.
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this
purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless
loop by leaving the conditional expression empty.

#include<stdio.h>
int main (){ for(;;){
printf("This loop
will run
forever.\n");
}return0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for (;;) construct to signify an infinite
loop.

NOTE − you can terminate an infinite loop by pressing Ctrl + C keys.

While loop in C

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

Syntax
The syntax of a while loop in C programming language is −

While (condition)
{
Statement;
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression,
and true is any nonzero value. The loop iterates while the condition is true.

41
When the condition becomes false, the program control passes to the line immediately following the loop.

Flow Diagram

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

Example

#include<stdio.h> int
main (){
/* local variable definition */ int
a =10;
/* while loop execution */
while( a <20)
{
printf("value of a: %d\n", a);
a++;
} return0;
}
When the above code is compiled and executed, it produces the following result −

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


a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18
value of a: 19

42
For loop in C

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

Syntax
The syntax of a for loop in C programming language is −

for ( init; condition; increment )

statement(s);

}
Here is the flow of control in a 'for' loop −

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

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

• After the body of the 'for' loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the condition.

• The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the 'for' loop terminates.

Flow Diagram

43
Example

#include<stdio.
h> int main ()
{
int a;
/* for loop
execution */
for( a =10; a <20; a = a +1)
{
printf("value of a: %d\n", a);
}
return;
}
44
When the above code is compiled and executed, it produces the following result −

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

Do...while loop in C

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C
programming checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

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

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

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

45
Example

#include<stdio.h> int

main ()

/* local variable definition */

int a =10;

/* do loop execution */

Do

printf("value of a: %d\n", a);

a = a +1;

}while( a <20);

return0;

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

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

46
value of a: 18
value of a: 19

Nested loops in C

r loop. The following section shows a few examples to illustrate the concept.

Syntax
The syntax for a nested for loop statement in C is as follows −

for ( init; condition; increment )


{

for ( init; condition; increment )


{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows −

while(condition)
{

while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −

do
{
statement(s);

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

}while( condition );

47
A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a
'for' loop can be inside a 'while' loop or vice versa.

Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −

Break statement in C
The break statement in C programming has the following two usages −

• When a break statement is encountered inside a loop, the loop is immediately terminated, and the
program control resumes at the next statement following the loop.

• It can be used to terminate a case in the switch statement (covered in the next chapter).

If you are using nested loops, the break statement will stop the execution of the innermost loop and start
executing the next line of code after the block.

Syntax
The syntax for a break statement in C is as follows −

break.
Flow Diagram

48
Example

#include<stdio.h> int

main (){

/* local variable definition */

int a =10;

/* while loop execution */ while( a <20)

printf("value of a: %d\n", a); a++;

if( a >15)

/* terminate the loop using break statement */


break;

return0;

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

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

Continue statement in C

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

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

49
Syntax
The syntax for a continue statement in C is as follows −

Continue;

Flow Diagram

Example

#include<stdio.h>
int main ()
{
/* local variable definition */
int a =10;
/* do loop execution */
do{ if( a ==15)
{
/* skip the iteration */
a = a +1;
continue;

} printf("value of a: %d\n", a);


a++;
}while( a <20);
return0;
}

goto statement in C

50
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement
in the same function.

NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult
to trace the control flow of a program, making the program hard to understand and hard to modify.
Any program that uses a goto can be rewritten to avoid them.

Syntax
The syntax for a goto statement in C is as follows −

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

Flow Diagram

51
Example

#include<stdio.h> int

main (){

/* local variable definition */ int

a =10;

/* do loop execution */

LOOP:do{ if( a ==15){

/* skip the iteration */

a = a +1;

goto LOOP;

}printf("value of a: %d\n", a); a++;

}while( a <20); return0;

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

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

52
Unit-3 Functions
• Introduction, Purpose of function,
• Function declaration/ Function prototype,
• Function definition, Function call, return statement,
• Function parameters, Types of functions,
• Call by value , Storage classes, Recursion, Examples on recursive function.

C - Functions
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.

You can divide up your code into separate functions. How you divide up your code among different functions
is up to you, but logically the division is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function.

The C standard library provides numerous built-in functions that your program can call. For example,
strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many
more functions.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function
The general form of a function definition in C programming language is as follows −

return_type function_name( parameter list ){ body of

the function

}
A function definition in C programming consists of a function header and a function body. Here are all the
parts of a function −

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

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

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

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

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

/* function returning the max between two numbers */ int

max(int num1,int num2){

/* local variable declaration */

int result;

if(num1 > num2)

result= num1;

else result=

num2; return

result;

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

A function declaration has the following parts −

return_type function_name( parameter list );


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

int max(int num1, int num2);


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

int max(int, int);


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

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you will
have to call that function to perform the defined task.

54
When a program calls a function, the program control is transferred to the called function. A called function
performs a defined task and when its return statement is executed or when its function-ending closing
brace is reached, it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along with the function name, and if the
function returns a value, then you can store the returned value. For example −

#include<stdio.h> /*

function declaration */

int max(int num1,int

num2); int main (){

/* local variable definition

*/ int a =100; int b =200;

int ret;

/* calling a function to get max value */

ret= max(a, b); printf("Max value is : %d\n",

ret ); return0;

/* function returning the max between two numbers */ int

max(int num1,int num2){

/* local variable declaration */ int

result;

if(num1 > num2)

result= num1;

else result= num2;

return result;

55
We have kept max() along with main() and compiled the source code. While running the final executable, it
would produce the following result −

Max value is : 200


Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parametersof the function.

Formal parameters behave like other local variables inside the function and are created upon entry into the
function and destroyed upon exit.

While calling a function, there are two ways in which arguments can be passed to a function −

[Link]. Call Type & Description

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

2 Call by reference
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the code within a function cannot
alter the arguments used to call the function.

C - Scope Rules

A scope in any programming is a region of the program where a defined variable can have its existence and
beyond that variable it cannot be accessed. There are three places where variables can be declared in C
programming language −

• Inside a function or a block which is called local variables.

• Outside of all functions which is called global variables.

• In the definition of function parameters which are called formal parameters.

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

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

main (){

/* local variable declaration

*/ int a, b; int c;

/* actual initialization */ a =10; b =20; c = a + b;

printf("value of a = %d, b = %d and c = %d\n", a, b, c);

return0;

Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold their
values throughout the lifetime of your program and they can be accessed inside any of the functions defined
for the program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout
your entire program after its declaration. The following program show how global variables are used in a
program.

#include<stdio.h>

/* global variable declaration */

int g; int main ()

/* local variable declaration */

int a, b;

/* actual initialization */ a =10; b =20; g = a + b;

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

return0;

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

57
#include<stdio.h>

/* global variable declaration */ int g =20; int

main (){

/* local variable declaration */ int g =10;

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

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

value of g = 10

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

#include<stdio.h>

/* global variable declaration */

int a =20; int main (){

/* local variable declaration in main function

*/ int a =10; int b =20; int c =0;

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

c =sum( a, b);

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

return0;

/* function to add two integers */ int

sum(int a,int b){ printf("value of a in

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

sum() = %d\n", b); return a + b;

58
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global
variables are initialized automatically by the system when you define them as follows −

Data Type Initial Default Value

int 0

char '\0'

float 0

double 0

pointer NULL
It is a good programming practice to initialize variables properly, otherwise your program may produce
unexpected results, because uninitialized variables will take some garbage value already available at their
memory location.

C - Storage Classes (extra)

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program.
They precede the type that they modify. We have four different storage classes in a C program −

• auto
• register
• static
• extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.

{ int mount; auto int month;

The example above defines two variables with in the same storage class. 'auto' can only be used within
functions, i.e., local variables.

59
The register Storage Class
The register storage class is used to define local variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size equal to the register size (usually one word) and
can't have the unary '&' operator applied to it (as it does not have a memory location).

register int miles;

The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'register' does not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during the life-time of
the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore,
making local variables static allows them to maintain their values between function calls.

The static modifier may also be applied to global variables. When this is done, it causes that variable's scope
to be restricted to the file in which it is declared.

In C programming, when static is used on a global variable, it causes only one copy of that member to be
shared by all the objects of its class.

60
#include<stdio.h>

/* function declaration */

void func(void);

static int count =5;/* global variable

*/ main()

{ while(count--)

func();

return0;

/* function definition */
void func(void)
{ static int i =5;/* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}

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

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1 i
is 10 and count is 0

The extern Storage Class


The extern storage class is used to give a reference of a global variable that is visible to ALL the program
files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a
storage location that has been previously defined.

When you have multiple files and you define a global variable or function, which will also be used in other
files, then extern will be used in another file to provide the reference of defined variable or function. Just
for understanding, extern is used to declare a global variable or function in another file.

61
The extern modifier is most commonly used when there are two or more files sharing the same global
variables or functions as explained below.

First File: main.c

#include<stdio.h>

int count ;

extern void write_extern ();

main()

count=5;

write_extern();

Second File: support.c

#include<stdio.h>

Extern int count;

void write_extern(void)

printf("count is %d\n", count);

Here, extern is being used to declare count in the second file, whereas it has its definition in the first file,
main.c. Now, compile these two files as follows −

$gcc main.c support.c


It will produce the executable program [Link]. When this program is executed, it produces the following result

count is 5

62
C - Recursion

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.

void recursion()

recursion();

/* function calls itself */

int main()

recursion();

}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into an
infinite loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of
a number, generating Fibonacci series, etc.

Number Factorial
The following example calculates the factorial of a given number using a recursive function −

63
#include <stdio.h>

unsigned long long int factorial(unsigned int i)

if(i <= 1)

return 1;

} return i * factorial(i - 1);

} int main()

int i = 12;

printf("Factorial of %d is %d\n", i, factorial(i));

return 0;

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

Factorial of 12 is 479001600

64
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −

#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{ return 1;
}

return fibonacci(i-1) + fibonacci(i-2);

}
int main()
{
int i; for (i = 0; i < 10; i++)
{
printf("%d\t\n", fibonacci(i));
}

return 0;

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

0
1
1
2
3
5
8
13
21
34

65
Unit-4Arrays and Strings
• Introduction to one-dimensional Array,
• Definition, Declaration, Initialization,
• Accessing and displaying array elements,
• Arrays and functions, Introduction to two-dimensional Array,
• Definition, Declaration, Initialization,
• Accessing and displaying array elements,
• Introductions to Strings, Definition, Declaration,
• Initialization, Input, output statements for strings,
• Standard library functions,
• Implementations with standard library functions

C - Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an array as a collection
of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers [0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and
the highest address to the last element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows −

type arrayName [ arraySize ];


This is called a single-dimensional array. The array Size must be an integer constant greater than zero and
type can be any valid C data type. For example, to declare a 10-element array called balance of type double,
use this statement −

double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays

66
You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};


The number of values between braces { } cannot be larger than the number of elements that we declare for
the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if
you write −

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};


You will create exactly the same array as you did in the previous example. Following is an example to assign
a single element of the array −

balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index
of their first element which is also called the base index and the last index of an array will be total size of
the array minus 1. Shown below is the pictorial representation of the array we discussed above −

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array. For example −

double salary = balance[9];


The above statement will take the 10th element from the array and assign the value to salary variable. The
following example Shows how to use all the three above mentioned concepts viz. declaration, assignment,
and accessing arrays −
#include<stdio.h>
int main ()
{
int n[10];/* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for( i =0; i <10; i++)
{
n[ i ]= i +100;/* set element at location i to i + 100 */ }
/* output each array element's value */
for(j =0; j <10; j++)

67
printf("Element[%d] = %d\n", j, n[j]);
} return0;
}

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

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Arrays in Detail
Arrays are important to C and should need a lot more attention. The following important concepts related
to array should be clear to a C programmer −

[Link]. Concept & Description

1
Multi-dimensional arrays
C supports multidimensional arrays. The simplest form of the multidimensional array is
the two-dimensional array.

2 Passing arrays to functions


You can pass to the function a pointer to an array by specifying the array's name without
an index.

68
3 Return array from a function
C allows a function to return an array.

4 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the array
name, without any index.

Multi-dimensional Arrays in C

C programming language allows multidimensional arrays. Here is the general form of a multidimensional
array declaration −

type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −

int threedim[5][10][4];

Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is a
list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write
something as follows −

type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional
array can be considered as a table which will have x number of rows and y number of columns. A two-
dimensional array a, which contains three rows and four columns can be shown as follows −

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the
name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an
array with 3 rows and each row has 4 columns.

69
int a[3][4]={

{0,1,2,3},/* initializers for row indexed by 0 */

{4,5,6,7},/* initializers for row indexed by 1 */

{8,9,10,11}/* initializers for row indexed by 2 */

};

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent
to the previous example −

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};


Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index
of the array. For example −

int val = a[2][3];


The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above
figure. Let us check the following program where we have used a nested loop to handle a two-dimensional
array −

#include<stdio.h> int

main ()

/* an array with 5 rows and 2 columns*/

int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};

int i, j;

/* output each array element's value */

for( i =0; i <5; i++){

for( j =0; j <2; j++){ printf("a[%d][%d]

= %d\n", i,j, a[i][j]);

} return0;

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

70
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1 a[1][1]:
2 a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely that most of
the arrays you create will be of one or two dimensions.

71
Passing Arrays as Function Arguments in C

If you want to pass a single-dimension array as an argument in a function, you would have to declare a
formal parameter in one of following three ways and all three declaration methods produce similar results
because each tells the compiler that an integer pointer is going to be received. Similarly, you can pass
multidimensional arrays as formal parameters.

Way-1
Formal parameters as a pointer −

void myFunction(int*param){

Way-2
Formal parameters as a sized array −

void myFunction(int param[10])

Way-3
Formal parameters as an unsized array −

void myFunction(int param[])

}
72
Example
Now, consider the following function, which takes an array as an argument along with another argument
and based on the passed arguments, it returns the average of the numbers passed through the array as
follows −

double get Average(int arr[],int size)

int i;

double avg;

double sum =0;

for(i =0; i < size;++i)

sum+= arr[i];

avg= sum / size;

return avg;

}
Now, let us call the above function as follows −

73
#include<stdio.h>

/* function declaration */

double getAverage(int arr[],int size);

int main ()

/* an int array with 5 elements

*/ int balance[5]={1000,2,3,17,50};

double avg;

/* pass pointer to the array as an argument */

avg= getAverage( balance,5);

/* output the returned value */

printf("Average value is: %f ", avg );

return0;

}
When the above code is compiled together and executed, it produces the following result −

Average value is: 214.400000

As you can see, the length of the array doesn't matter as far as the function is concerned because C performs
no bounds checking for formal parameters.

Return array from function in C

C programming does not allow to return an entire array as an argument to a function. However, you can
return a pointer to an array by specifying the array's name without an index.

If you want to return a single-dimension array from a function, you would have to declare a function
returning a pointer as in the following example −

int* myFunction(){

.
80
}

Second point to remember is that C does not advocate to return the address of a local variable to outside of
the function, so you would have to define the local variable as static variable.

Now, consider the following function which will generate 10 random numbers and return them using an
array and call this function as follows −
#include<stdio.h>

/* function to generate and return random numbers */

int* getRandom()

static int r[10];

int i;

/* set the seed */


srand((unsigned)time( NULL ));
for( i =0; i <10;++i){ r[i]= rand();

printf("r[%d] = %d\n", i, r[i]);


} return r;

/* main function to call above defined function */ int

main (){

/* a pointer to an int */

int*p;

int i;

p =getRandom();

for( i =0; i <10; i++)

printf("*(p + %d) : %d\n", i,*(p + i));

} return0;

}
When the above code is compiled together and executed, it produces the following result −

r[0] = 313959809

81
r[1] = 1759055877
r[2] = 1113101911
r[3] = 2133832223
r[4] = 2073354073
r[5] = 167288147
r[6] = 1827471542
r[7] = 834791014
r[8] = 1901409888
r[9] = 1990469526
*(p + 0) : 313959809
*(p + 1) : 1759055877
*(p + 2) : 1113101911
*(p + 3) : 2133832223
*(p + 4) : 2073354073
*(p + 5) : 167288147
*(p + 6) : 1827471542
*(p + 7) : 834791014
*(p + 8) : 1901409888
*(p + 9) : 1990469526

Pointer to an Array in C

It is most likely that you would not understand this section until you are through with the chapter 'Pointers'.

Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer
to the first element of the array. Therefore, in the declaration −

double balance[50];
balance is a pointer to & balance[0], which is the address of the first element of the array balance. Thus,
the following program fragment assigns p as the address of the first element of balance −

double *p; double balance[10];

p = balance;
It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate
way of accessing the data at balance[4].

Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1),
*(p+2) and so on. Given below is the example to show all the concepts discussed above −

82
#include<stdio.h>

int main (){


/* an array with 5 elements */ double

balance[5]={1000.0,2.0,3.4,17.0,50.0};

double*p;

int i; p =

balance;

/* output each array element's value

*/ printf("Array values using

pointer\n"); for( i =0; i <5; i++){

printf("*(p + %d) : %f\n", i,*(p + i));

} printf("Array values using balance as


address\n"); for( i =0; i <5; i++)

{
printf("*(balance + %d) : %f\n", i,*(balance + i));

} return0;

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

Array values using pointer


*(p + 0) : 1000.000000
*(p + 1) : 2.000000
*(p + 2) : 3.400000
*(p + 3) : 17.000000
*(p + 4) : 50.000000
Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000
In the above example, p is a pointer to double, which means it can store the address of a variable of double
type. Once we have the address in p, *p will give us the value available at the address stored in p, as we
have shown in the above example.

83
C - Strings

Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus, a null
terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."

char greeting [6] = {'H', 'e', 'l', 'l', 'o', '\0'};


If you follow the rule of array initialization, then you can write the above statement as follows −

char greeting [] = "Hello";


Following is the memory presentation of the above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C compiler automatically
places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned
string −

#include<stdio.h> int main (){ char

greeting[6]={'H','e','l','l','o','\0'}; printf("Greeting

message: %s\n", greeting ); return0;

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

Greeting message: Hello

C supports a wide range of functions that manipulate null-terminated strings −

84
[Link]. Function & Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
The following example uses some of the above-mentioned functions −

85
#include<stdio.h>

#include<string.h> int

main ()

char str1[12]="Hello";

char str2[12]="World";

char str3[12];

int len;

/* copy str1 into str3 */

strcpy(str3, str1);

printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */

strcat( str1, str2);

printf("strcat( str1, str2): %s\n", str1 );

/* total length of str1 after concatenation*/

len = strlen(str1); printf("strlen(str1) : %d\n", len );

return0;

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

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

86
Unit-5 Structures and union
• Introduction to structure,
• Defining a structure, Declaring structure variables,
• Accessing structure members, nested structure,
• Array of structure, Array within structure,
• Introduction to union, Definition, Declaration,
• Differentiate between structure and union

C - Structures

Arrays allow to define type of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C that allows to combine data items of different
kinds.

Structures are used to represent a record. Suppose you want to keep track of your books in a library. You
might want to track the following attributes about each book −

• Title
• Author
• Subject
• Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data type,
with more than one member. The format of the struct statement is as follows −

struct[structure tag]{

member definition;

member definition;

...

member definition;

}[one or more structure variables];

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

87
Struct Books{

char title[50];

char author[50];

char subject[100];

int book_id;

} book;

Accessing Structure Members


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

88
#include<stdio.h>

#include<string.h>

structBooks{ char

title[50]; char

author[50]; char

subject[100]; int

book_id;

};

int main()

{ structBooksBook1;/* Declare Book1 of type Book */

structBooksBook2;/* Declare Book2 of type Book */

/* book 1 specification */

strcpy([Link],"C Programming");

strcpy([Link],"Nuha Ali");

strcpy([Link],"C Programming Tutorial");

Book1.book_id =6495407;

/* book 2 specification */
strcpy([Link],"Telecom Billing");

strcpy([Link],"Zara Ali");

strcpy([Link],"Telecom Billing Tutorial");

Book2.book_id =6495700;

/* print Book1 info */

printf("Book 1 title : %s\n",[Link]);

printf("Book 1 author : %s\n",[Link]);

printf("Book 1 subject : %s\n",[Link]);

printf("Book 1 book_id : %d\n",Book1.book_id);

89
/* print Book2 info */

printf("Book 2 title : %s\n",[Link]);

printf("Book 2 author : %s\n",[Link]);

printf("Book 2 subject : %s\n",[Link]);

printf("Book 2 book_id : %d\n",Book2.book_id);

return0;

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

Book 1 title : C Programming


Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial Book 2

book_id : 6495700

Structures as Function Arguments


You can pass a structure as a function argument in the same way as you pass any other variable or pointer.

#include<stdio.h>

#include<string.h

> structBooks{

char title[50];

90
char author[50];

char subject[100];

int book_id;

};

/* function declaration */ void

printBook(structBooks book ); int main(){

structBooksBook1;/* Declare Book1 of type Book */

structBooksBook2;/* Declare Book2 of type Book */

/* book 1 specification */ strcpy([Link],"C

Programming"); strcpy([Link],"Nuha

Ali"); strcpy([Link],"C Programming

Tutorial");

Book1.book_id =6495407; /* book 2

specification */ strcpy([Link],"Telecom

Billing"); strcpy([Link],"Zara Ali");

strcpy([Link],"Telecom Billing Tutorial");

Book2.book_id =6495700; /*

print Book1 info */

printBook(Book1);

/* Print Book2 info */

printBook(Book2); return0;

void printBook(structBooks book ){ printf("Book


title : %s\n", [Link]);

91
printf("Book author : %s\n", [Link]);

printf("Book subject : %s\n", [Link]);

printf("Book book_id : %d\n", book.book_id);

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

Book title : C Programming


Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any other variable −

struct Books *struct_pointer;


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

struct_pointer =&Book1;

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

struct_pointer->title;

Let us re-write the above example using structure pointer.

#include<stdio.h>

#include<string.h>

structBooks

char title[50];
char author[50];
char subject[100];
int book_id;

92
};

/* function declaration */

void printBook(structBooks*book );

int main(){ structBooksBook1;

/* Declare Book1 of type Book */

structBooks Book2;

/* Declare Book2 of type Book */

/* book 1 specification */

strcpy([Link],"C Programming");

strcpy([Link],"Nuha Ali");

strcpy([Link],"C Programming Tutorial");

Book1.book_id =6495407;

/* book 2 specification */

strcpy([Link],"Telecom Billing");

strcpy([Link],"Zara Ali");

strcpy([Link],"Telecom Billing Tutorial");

Book2.book_id =6495700;

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

printBook(&Book1);

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

printBook(&Book2);

return0;

void printBook(structBooks*book )

{ printf("Book title : %s\n", book->title);

printf("Book author : %s\n", book->author);

93
printf("Book subject : %s\n", book->subject);

printf("Book book_id : %d\n", book->book_id);

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

Book title : C Programming


Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Bit Fields
Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is
at a premium. Typical examples include −

• Packing several objects into a machine word. e.g. 1 bit flags can be compacted.

• Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers.

C allows us to do this in a structure definition by putting :bit length after the variable. For example −

struct packed_struct {

unsigned int f1:1;

unsigned int f2:1;

unsigned int f3:1;

unsigned int f4:1;

unsigned int type:4;

unsigned int my_int:9;

} pack;

Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit my_int.

C automatically packs the above bit fields as compactly as possible, provided that the maximum length of
the field is less than or equal to the integer word length of the computer. If this is not the case, then some
compilers may allow memory overlap for the fields while others would store the next field in the next word.

94
C - Unions

A union is a special data type available in C that allows to store different data types in the same memory
location. You can define a union with many members, but only one member can contain a value at any
given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a structure.
The union statement defines a new data type with more than one member for your program. The format
of the union statement is as follows −

union[union tag]

member definition;

member definition;

...

member definition;

}
[one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as int i; or float
f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you
can specify one or more union variables but it is optional. Here is the way you would define a union type
named Data having three members i, f, and str −

Union Data

int i;

float f;

char str[20];

} data;

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It
means a single variable, i.e., same memory location, can be used to store multiple types of data. You can
use any built-in or user defined data types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest member of the union. For example,
in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space

95
which can be occupied by a character string. The following example displays the total memory size occupied
by the above union −

#include<stdio.h>

#include<string.h>

Union Data

int i; float f;

char str[20];

};

int main()

{ union Data data;

printf("Memory size occupied by data : %d\n",sizeof(data));

return0;

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

Memory size occupied by data : 20


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

96
#include<stdio.h>

#include<string.h>

Union Data

int i;

float f;

char str[20];

};

int main()
{
Union Data data;
data.i =10;
data.f =220.5;

strcpy( [Link],"C Programming");

printf("data.i : %d\n", data.i);

printf("data.f : %f\n", data.f);

printf("[Link] : %s\n", [Link]);

return0;

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

data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
[Link] : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final value assigned
to the variable has occupied the memory location and this is the reason that the value of str member is
getting printed very well.

Now let's look into the same example once again where we will use one variable at a time which is the main
purpose of having unions −

97
#include<stdio.h>
#include<string.h>
Union Data{
int i; float f;
char str[20];
};
int main()
{ union Data data;

data.i =10;
printf("data.i : %d\n", data.i);
data.f =220.5;
printf("data.f : %f\n", data.f);
strcpy( [Link],"C Programming");
printf("[Link] : %s\n", [Link]);
return0;
}

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

data.i : 10 data.f :
220.500000 [Link] : C
Programming
Here, all the members are getting printed very well because one member is being used at a time.

Array of structures:
An array in which each element is a structure. Just as arrays of any basic type of variable are allowed, so are
arrays of a given type of structures. Although structures contains many different types, the compiler never
gets to know this information because it is hidden away inside a sealed structures capsule, so it can believe
that all the elements in the array have the same type, even though that type is itself made up of lots of
different types.

The declaration statement is given below.


struct struct_name
{
type element 1;
type element 2;
……………..
type element n;

98
array name[size];

Example:
struct student
{

int rollno;
char name[25];
float totalmark;
} stud[100];

In this declaration stud is a 100-element array of structures. Hence, each element of stud is a separate
structure of type student. An array of structure can be assigned initial values just as any other array. So it
can hold information of 100 students.

example

#include <stdio.h>
#include <conio.h>
Int main()
{
Struct student
{
Int rollno;
Char name[25];
Int totalmark;
}
stud[100];
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of %d-th student\n",i+1);
printf("Name:\n");
scanf("%s",&stud[i].name);
printf("Roll number:\n");
scanf("%d",&stud[i].rollno);
printf("Total mark:\n");
scanf("%d",&stud[i].totalmark);
}
printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno); 30 printf("Name:%s\n",stud[i].name);

99
printf("Totel mark:%d\n",stud[i].totalmark);
}
getch();
return0;
}
Structure as structure member:( nested structure)
It can have one or more of its member as another structure, but a structure cannot be member
to itself when a structure is used as structure member. In such situation, the declaration of the
embedded structure must appear before the declaration of the outer structure. For example

#include <stdio.h>
#include <conio.h>
Int main()
{
Struct dob
{
Int day;
Int month;
Int year;
};
Struct student

{
Struct dob d ;
Int rollno;
Char name[25];
Int totalmark;
}
stud[25];
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter details of %d-th student\n\n",i+1);
printf("\nName:\n");
scanf("%s",&stud[i].name);
printf("\nRoll number:\n");
scanf("%d",&stud[i].rollno);
printf("\nTotal mark:\n");
scanf("%d",&stud[i].totalmark);
printf("\nDate of birth (Format:01 06 2010):\n");
scanf("%d%d%d",&stud[i].[Link],&stud[i].[Link],&stud[i].[Link]);
}

100
printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\n\nRoll number:%d\n\n",stud[i].rollno);
printf("Name:%s\n\n",stud[i].name);
printf("Totel mark:%d\n\n",stud[i].totalmark);
printf("Date of birth:%d / %d / %d \n\n",stud[i].[Link],stud[i].[Link],stud[i].[Link]);
}
getch();
return 0;
}
Array of Structure:
Like any other data type, array of structure can be defined, so that each array element can be of

structure data type. For Example, struct student s[100];

Which defines an array called s, that contains 100 elements, each element is defined to be of type struct
student.

C – ARRAY OF STRUCTURES EXAMPLE PROGRAM :

#include<stdio.h>
#include<conio.h>
Struct item
{
Int code;
Char name[20];
Float cost;
};
Void main()
{
Struct item it[100];
Int n,i;
Float *f,f1;
clrscr();
f=&f1;
*f=f1;
printf("Enter numer of records : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter Record : %d",i+1);
printf("\n\nEnter Item code : ");
scanf("%d",&it[i].code);
printf("Enter Item Name : ");
fflush(stdin);

101
gets(it[i].name);
printf("Enter Item cost : ");
scanf("%f",&it[i].cost);
}
clrscr();
printf("%-10s%-15s%s","CODE","NAME","COST");
printf("\n ");
for(i=0;i<n;i++)
{
printf("\n%-10d%-15s%.2f",it[i].code,it[i].name,it[i].cost);
}
getch();
}
The allocation of variables in heap contains 2 parts. One is for integral data types (int and char),
and the other is for float type. But it is different in case when we declare a structure.

When we define a structure with 3 data types, one is of integer, other is of character and
another is of float type, the memory for all the 3 types are allocated in integral part. When we
compile this type of programs we did not get any error but when we execute the program,

102
1 the program terminates abnormally. This is because the link fails when connecting floating
2 values to the structure.

3 To solve this problem, we must declare 2 float values, one is of pointer type and the other is
4 normal float value. The memory for float pointer is allocated in the integral part (because
5 pointer has 2 bytes of unsigned int memory) and the memory for another float variable is
6 allocated in the float part. This normal variable points to the float pointer (which resides in
7 integral part), and thus we will establish a link between integral part and float part of heap.
8 Thus, the programs executes normally.

9 C – ARRAY OF STRUCTURE EXAMPLE PROGRAM:

10 To accept student details and to calculate and display result using arrays

11 #include<stdio.h>
12 #include<conio.h>
13 #include<string.h>
14 struct student
15 {
16 Int sno,c,cpp,java,tot;
17 Float avg;
18 char sname[20],res[10],div[12];
19 };
20 Void main()
21 {
22 struct students[100];
23 int id=0,i;
24 clrscr();
25 while(1)
26 {
27 printf("\nEnter Student number : "); scanf("%d",&s[id].sno);

103
19 printf("Enter Student name : ");
20 fflush(stdin);
21 gets(s[id].sname);
22 printf("Enter marks in C : ");
23 scanf("%d",&s[id].c);
24 printf("Enter marks in CPP : ");
25 scanf("%d",&s[id].cpp);
26 printf("Enter marks in JAVA : ");
27 scanf("%d",&s[id].java);
28 s[id].tot=s[id].c+s[id].cpp+s[id].java;
29 s[id].avg=(float)s[id].tot/3;
30 if(s[id].c>=50&&s[id].cpp>=50&&s[id].java>=50)
31 {
32 strcpy(s[id].res,"PASS");
33 if(s[id].avg>=60)
34 strcpy(s[id].div,"FIRST");
35 else
36 strcpy(s[id].div,"SECOND");
37 }
38 else
39 {
40 strcpy(s[id].res,"FAIL");
41 strcpy(s[id].div,"NO DIVISION");
42 }
43 id++;
44 printf("\nDo u want to add another Record(y/n) : "); 45 fflush(stdin);
46 scanf("%c",&ch);
47 if(ch=='n'||ch=='N')
48 break;
49 }
50 for(i=0;i<id;i++)
51 {
52 clrscr();
53 printf("Student Details");
54 printf("\n ");
55 printf("\nStudent number : %d",s[i].sno);
56 printf("\nStudent name : %s",s[i].sname);
57 printf("\nMarks in C : %d",s[i].c);
58 printf("\nMarks in CPP : %d",s[i].cpp);
59 printf("\nMarks in JAVA : %d",s[i].java);
60 printf("\nTotal Marks : %d",s[i].tot);
61 printf("\nAverage Marks : %.2f",s[i].avg);
62 printf("\nResult : %s",s[i].res);
63 printf("\nDivision : %s",s[i].div);
64 printf("\n\nPress any key to continue........");

104
65 }
66 }

Passing structure as function argument:


Like any other data type a structure may also be used as function argument.

Returning structure :
A function can not only receive a structure as its argument, but also can return them.

105
1 #include<stdio.h>

2 #include<conio.h>

3 Struct student

4 { int sno;

5 char sname[20],course[20];

6 float fee;

7 };

8 Struct student accept()

9 { struct students; printf("Enter

10 Student Number : ");

11 scanf("%d",&[Link]);

12 printf("Enter Student Name : ");

13 fflush(stdin);

14 gets([Link]);

15 printf("Enter Course : ");

16 gets([Link]);

17 printf("Enter Fee : ");

18 scanf("%f",&[Link]); returns;

19 }

20 Void disp(struct students)

21 {

22 printf("\n\nSTUDENT DETAILS");

23 printf("\n ------------------ \n");

106
27 printf("\nStudent Number : %d",[Link]);

28 printf("\nStudent Name : %s",[Link]);

29 printf("\nCourse : %s",[Link]);

30 printf("\nFees : %.2f",[Link]);

31 }

32 Void main()

33 {

34 Struct student st;

35 clrscr ();

36 st=accept(); //returning structure

37 disp(st); //passing structure

38 getch();

39 }

107
Unit-5 Pointers
• Introduction to pointer,
• Definition, Declaring and Initializing pointer variable,
• Indirection operator and address of operator,
• Accessing variable through its pointer,
• Pointer arithmetic, Dynamic memory allocation, • Pointers & Functions, Pointers &
Array,
• Pointers & Structures.

C - Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with
pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers.
So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in
simple and easy steps.

As you know, every variable is a memory location and every memory location has its address defined which
can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the
following example, which prints the address of the variables defined −

#include<stdio.h> int main ()

int var1; char var2[10];

printf("Address of var1 variable: %x\n",&var1 );

printf("Address of var2 variable: %x\n",&var2 );

return 0;

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

Address of var1 variable: bff5a400


Address of var2 variable: bff5a3f6

108
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is −

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

int *ip; /* pointer to an integer */


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

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very frequently. (a) We
define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at
the address available in the pointer variable. This is done by using unary operator * that returns the value
of the variable located at the address specified by its operand. The following example makes use of these
operations −

#include<stdio.h> int main ()

Int var=20;/* actual variable declaration */

int*ip;/* pointer variable declaration */

ip=&var;

/* store address of var in pointer variable*/

printf("Address of var variable: %x\n",&var);

/* address stored in pointer variable */

printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */

printf("Value of *ip variable: %d\n",*ip );


109
Return 0;

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

Address of var variable: bffd8b3c


Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is
called a null pointer.

The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the
following program −

#include<stdio.h>

int main ()

int*ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0 ;

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

The value of ptr is 0


In most of the operating systems, programs are not permitted to access memory at address 0 because that
memory is reserved by the operating system. However, the memory address 0 has special significance; it
signals that the pointer is not intended to point to an accessible memory location. But by convention, if a
pointer contains the null (zero) value, it is assumed to point to nothing.

To check for a null pointer, you can use an 'if' statement as follows −

if(ptr) /* succeeds if p is not null */

if(!ptr) /* succeeds if p is null */

Pointers in Detail
Pointers have many but easy concepts and they are very important to C programming. The following
important pointer concepts should be clear to any C programmer –

110
[Link]. Concept & Description

1 Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -

2 Array of pointers
You can define arrays to hold a number of pointers.

3 Pointer to pointer
C allows you to have pointer on a pointer and so on.

4 Passing pointers to functions in C


Passing an argument by reference or by address enable the passed argument to be
changed in the calling function by the called function.

5 Return pointer from functions in C


C allows a function to return a pointer to the local variable, static variable, and
dynamically allocated memory as well.
C - Pointer arithmetic

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 -

To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address
1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −

ptr++
After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it
will point to the next integer location which is 4 bytes next to the current location. This operation will move
the pointer to the next memory location without impacting the actual value at the memory location. If ptr
points to a character whose address is 1000, then the above operation will point to the location 1001 because
the next character will be available at 1001.

Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant pointer. The
following program increments the variable pointer to access each succeeding element of the array –

#include<stdio.h>

111
const int MAX =3;

int main ()

Int var[]={10,100,200};

int i,*ptr;

/* let us have array address in pointer */

ptr=var;

for( i =0; i < MAX; i++)

printf("Address of var[%d] = %x\n", i, ptr );

printf("Value of var[%d] = %d\n", i,*ptr );

/* move to the next location */ ptr++;

Return 0;

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

Address of var[0] = bf882b30


Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38 Value of var[2] = 200

Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes
of its data type as shown below –

112
#include<stdio.h>

constint MAX =3;

int main ()

int

var[]={10,100,200};

int i,*ptr;

/* let us have array address in pointer */ ptr=&var[MAX-1];

for( i = MAX; i >0; i--)


{
printf("Address of var[%d] = %x\n", i-1, ptr);
printf("Value of var[%d] = %d\n", i-1,*ptr );
/* move to the previous location */ ptr--;

} return0;

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

Address of var[2] = bfedbcd8


Value of var[2] = 200
Address of var[1] = bfedbcd4
Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.

The following program modifies the previous example − one by incrementing the variable pointer so long
as the address to which it points is either less than or equal to the address of the last element of the array,
which is &var[MAX - 1] −

113
#include<stdio.h>

const int MAX =3;

int main ()

int var[]={10,100,200};

int i,*ptr;

/* let us have address of the first element in pointer */

ptr=var;

i =0;

while( ptr <=&var[MAX -1]){

printf("Address of var[%d] = %x\n", i, ptr );

printf("Value of var[%d] = %d\n", i,*ptr );

/* point to the previous location */


ptr++;
i++;

return0;

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

Address of var[0] = bfdbcb20


Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
Address of var[2] = bfdbcb28
Value of var[2] = 200

114
Programs for applying concepts of c language in lab sessions
Section A: Basic Programs:

Question A1: WAP to input roll number, name, marks and phone of a student and display the values.

Question A2: WAP to input roll number, name and marks of a student in 5 subjects and calculate the total and
average marks. Display all the values.

Question A3: WAP to find out the square of a given number.

Question A4: WAP to input a number and print its cube.

Question A5: WAP to input radius and calculate the area and circumference of a circle.

Question A6: WAP to input length and breadth of a rectangle and calculate the area and perimeter.

Question A7: WAP to input 4 integers a, b, c, d and check that the equation a3 + b3 +c3 = d3 is satisfied or not.

Question A8: WAP to input side of a square and calculate the area.

Question A9: WAP to input principle, rate and time from the user and calculate the simple interest and total
amount. Display all the values.

Question A10: WAP to input the number the days from the user and convert it into years, weeks and days.

Question A11: WAP to input a character and print its ASCII value.

Question A12: WAP to input a number and print its equivalent character code.

Question A13: WAP to find out the quotient and remainder of two numbers. ( Without using modulus ( % )
operator)

Question A14: WAP to input two numbers and print their quotient and remainder.

Question A15: WAP to input two numbers and print the greatest using conditional operator.
Question A16: WAP to input marks of a student and print the result (pass/fail) using conditional operator.

Question A17: WAP to input inches from the user and convert it into yards, feet and inches.

Question A18: WAP to find out the area of a triangle.

Question A19: WAP to find whether a given number is even or odd using conditional operator.

Question A20: WAP to find out the greatest of three numbers using conditional operator.

Question A21: WAP to input choice (1 or 2). If choice is 1 print the area of a circle otherwise print the
circumference of circle. Input the radius from user.

Question A22: WAP to input a number. If the number is even, print its square otherwise print its cube.

115
Question A23: WAP to input employee code, name and basic salary of an employee and calculate the following
values:

HRA 40 % of basic salary

DA 10 % of basic salary

CCA 5 % of basic salary

GS Basic + HRA + DA + CCA

PF 10 % of GS

IT 10 % of GS

NS GS – (PF + IT)

Display all the values.

Question A24: WAP to input the temperature in Fahrenheit and convert it into Celsius and vice versa.

Question A25: WAP to swap the values of two integer variables

(a) Using extra variable


(b) Without using extra variable Question A26: WAP to
print the system date.

Question A27: WAP to find the age of a person by the given date of birth.

Section B: Programs Based on Control Structures

Question B1: WAP to input the marks of a student and print the result (passing marks = 40 %).

Question B2: WAP to input the age of a person and check that he is eligible for license for not.

Question B3: WAP to check that a given year is a leap year or not.

Question B4: WAP to input a number and check whether it is even or odd.

Question B5: WAP to input a number and check that number is divisible by 7 or not.

Question B6: According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input
through the keyboard write a program to find out what is the day on 1st January of this year.

Question B7: WAP to input the name and age of a person and display “CHILD” or “TEENAGER” according to the
age.

Question B8: WAP to input the salary of a person and calculate the hra and da according to the following
conditions:
Salary HRA DA

5000-10000 10% 5%

10001-15000 15% 8%

116
Question B9: WAP to input marks in five subjects of a student and calculate the division according to the
following conditions:

Percentage Division

>=60 First

50-59 Second

40-49 Third

<40 Fail

Question B10: An electricity board charges according to the following rates:

For the first 100 units - 40 paisa per unit.

For the next 200 units - 50 paisa per unit.

beyond 300 units - 60 paisa per unit.

All users are charged meter charges also, which are Rs. 50/-

Question B11: WAP to input monthly salary from the user and calculate the income tax according to the
following rules:

Salary income tax


>=9000 40% of the salary
7500-8999 30% of the salary
<7500 20% of the salary

Question B12: WAP to input the selling price and cost price from the user and determine whether the seller
has made profit or incurred loss. Also display the value of profit or loss.

Question B13: WAP to input a character and check that it’s a small letter, capital letter, a digit or a special
symbol.

Question B14: WAP to input two integers and determine that first is multiple of second.

Question B15: WAP to input a character and check that it’s a vowel or a consonant.

Question B16: WAP to convert a small letter into capital letter and vice versa.

Question B17: WAP to input the marks of a student in five subjects and calculate the grade according the
following conditions:

Marks Grade
>90 S
76-90 A
61-75 B
51-60 C
40-50 D
<40 Fail

117
Question B18: WAP to input the sales made by a salesman and calculate the commission according to the
following conditions:

Sales Commission
1-10000 4%
10001-20000 5%
20001-30000 6%
>30000 7%
Question B19: WAP to convert the temperature according to the following conditions:

Choice Conversion
1 Fahrenheit to Celsius
2 Celsius to Fahrenheit
Question B20: WAP to find out the largest of three numbers.

Question B21: WAP to input three numbers and print them in descending order.

Question B22: WAP to input a number (1 to 7) and print the weekday name according to the given number.

Question B23: WAP to input a digit and print the digit in words.

Question B24: WAP to input two numbers and a choice and calculate the result according to the following
conditions:

Choice Result
1 Add
2 Subtract
3 Multiply
4 Divide
5 Remainder
Question B25: WAP to input two numbers and an operator and calculate the result according to the following
conditions:

Operator Result ‘+’ Add

‘-‘ Subtract
‘*’ Multiply
‘/’ Divide
‘%’ Remainder
Question B26: WAP to calculate the area of a circle, a rectangle or a triangle depending upon user’s choice.

Choice Area
1 Circle
2 Rectangle
3 Triangle

Question B27: WAP to input the marks in theory and practical and print the result.

Question B28: WAP to input a date (dd / mm / yyyy) and check for the validity of the date.

118
Question B29: WAP to print counting from 1 to 10.

Question B30: WAP to print counting from 10 to 1.

Question B31: WAP to print counting from 51 to 90.

Question B32: WAP to find out the sum and average of

all the numbers within the given range.

Question B33: WAP to print all the numbers falling between 2 numbers entered by the user.

Question B34: WAP to print all the even numbers between 1 and 50.

Question B35: WAP to print all the odd numbers between 1 and 50.

Question B36: WAP to print the sum and average of first n natural numbers.

Question B37: WAP to print the sum and average of first n odd numbers.

Question B38: WAP to print the sum and average of first n even numbers.

Question B39: WAP to print the table of a given number.

Question B40: WAP to input 2 numbers and find out the sum of all the even numbers which are not divisible
by 5 but divisible by 3 and lies between the given two numbers.

Question B41: WAP to input the name and age of a person and print the name as many times as age.

Question B42: WAP to print whole screen with any character.

Question B43: WAP to print the factorial of a given number.

Question B44: WAP to input a number through the keyboard until a ‘.’. Every time a number is entered. The
program should display whether it is greater than, less than or equal to the previous number.

Question B45: WAP to check that given number is prime or not.

Question B46: WAP to input a number and count its even and odd digits and find out their sum separately.

Question B47: WAP to generate divisors of an integer.

Question B48: If a number 972 is entered through the keyboard, your program should print “Nine Seven
Two”. Write the programsuch that it does this for any positive integers.

Question B49: A positive integer is entered through the keyboard, along with it the base of the numbering
system in which you want to convert this number. WAP to display the number entered, the base and the
converted number.

Question B50: WAP to input a number and separate the number in its individual digit and print the digits
separated from one another by three spaces each.

Question B51: WAP to convert a decimal number to equivalent binary number (fractions also).

Question B52: WAP to convert a decimal number to equivalent octal number.


119
Question B53: WAP to convert a decimal number to equivalent hexadecimal number.

Question B54: WAP to convert a binary number to the decimal number.

Question B55: WAP to convert a octal number to the decimal number.

Question B56: WAP to convert a hexadecimal number to the decimal number.

Question B57: WAP to convert a octal number to binary number.

Question B58: WAP to convert a hexadecimal number to the binary number.

Question B59: WAP to generate all combinations of 1, 2 and 3.

Question B60: WAP to find out the LCM and GCD of two given numbers.

Question B61: WAP to find out the least common divisor of two integers.

Question B62: WAP to check whether square root of a number is prime or not.

Question B64: Input two numbers from the keyboard. Write a program to find the value of one number raised
to the power of another.

Question B65: WAP to print all the ASCII values and their equivalent characters. The ASCII values vary from 0
to 255.

Question B66: WAP to check that given number is Armstrong number or not. ( if the sum of the cubes of each
digits of the number is equal to the number itself, then the number is called the Armstrong number. For
example, 153 = (1*1*1) + (5*5*5) + (3*3*3).

Question B67: 145 is a special number, since it satisfies the following relation:

145 = 1! + 4! + 5! = 1+24+120 =145

WAP to print all the numbers of this kind between 1 – 1000000.

Question B68: WAP to find out the sum of geometric series.

Question B69: WAP to print out all Armstrong numbers between 1 and 500.

Question B70: Square of 12 is 144. 21, which is a reverse of 12 has a square 441, which is same as 144 reversed.
There are few numbers which have this property. Write a program to find out whether any more such numbers
exist in the range of 10 to 100.

Question B71: WAP to find out the difference between two dates in terms of numbers of days.

Question B72: WAP to input n numbers and calculate the sum, average, maximum and minimum of the given
numbers. (Use only one variable to input the number and also find the second largest).

Question B73: WAP to print the sum of negative numbers, sum of positive even numbers and sum of positive
odd numbers from a list of numbers entered by the user.

Question B74: WAP to print the largest even number and largest odd number from the list of numbers entered
through keyboard.

120
Question B75: WAP to determine all Pythagorean triplets in the range 100 to 1000.

(A Pythagorean triplet is a set of three integers i, j, k such that i2 + j2 = k2)

Question B76: WAP to print the following series:

(1) 2, 4, 8, 16, 32, 64, 128, 256


(2) 1, 4, 7, 10, …………… 40 (3) 1, -4, 7, -10……………-40
(4) 1, 5, 11, 19, 29 ……..
(5) (1)+(1+2)+(1+2+3)+(1+2+3+4) ............ up to n terms (6)
(6) (2) + (2+4) + (2+4+6) + (2+4+6+8) ........... up to n terms.
(7) (1) + (1+3) + (1+3+5) + (1+3+5+7)............. up to n terms
(8) (12) + (12+32)+(12+32+52)+(12+32+52+72) ...... up to n terms
(9) (22) + (22+42) + (22+42+62)+(22+42+62+82) ....... up to n terms

Question B77: WAP to calculate the root of quadratic equation.

Question B78: Write a menu driven program which has following options:

1. Factorial of a number.
2. Prime or Not 3. Odd or even 4. Exit.
Question B79: WAP to input a number and print its reverse number. Also check that the number is palindrome
or not.

Question B80: WAP to input a number and find out the sum of its digits.

Question B81: WAP to find out the count of the digits of a given integer.

Question B82: WAP to print the Fibonacci series.

Question B83: WAP to input a name and print the name in the following pattern

R RAJAT
RA RAJA
RAJ RAJ
RAJA RA
RAJAT R

Question B84: WAP to print the following series:

1 1
12 22
123 333
1234 4444

1234 4444
123 333
12 22
1 1

121
5
54
543
5432
54321

A A
AB BB
ABC CCC
ABCD DDDD

ABCD DDDD
ABC CCC
AB BB
A A

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

ABCDEFGFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A

A B A

A B C B A

A B C D C B A

A B C B A

A B A

A
122
Question B85: WAP to print the truth table for XY+Z.

Question B86: WAP to print the factorial of all the numbers till the given number.

Question B87: WAP to print the tables of all the numbers till the given number.

Question B88: WAP to input month number and year and print the calendar for the given month.

Question B89: WAP to find out the difference between two dates, in terms of days, months and years.

Question B90: WAP to add number of days or number of months in a given date.

Question B91: WAP to print all the prime numbers till the given number.

Section C: Programs Based on Strings

Question C1: WAP to count the number of spaces, tabs and new line characters in a given string.

Question C2: WAP to input a character and a string. Each occurrence of a character in the string should be
converted to opposite case i.e. upper to lower case or vice versa.

Question C3: WAP to count the number of words and number of characters in a given line of text except the
spaces.

Question C4: WAP to input a multi word string and produce a string in which first letter of each word is
capitalized.

Question C5: WAP to count the numbers of vowels, consonants, digits and special symbols in a given string.

Question C6: WAP to count the lower case and upper case letters in a string.

Question C7: WAP to search a character in a given string.

Question C8: WAP to search a given string into another string and displays the position if found otherwise
displays 0.

Question C9: WAP to find a substring of given string.

Question C10: WAP to extract specified number of characters from a given position from a string.

Question C11: WAP to count all the occurrences of a character in a given string.

Question C12: WAP to calculate the length of a string.

Question C13: WAP to input two strings and print which one is lengthier.

Question C14: WAP to reverse a string.

Question C15: WAP to check a string for palindrome.

Question C16: WAP to copy a string into another string.


123
Question C17: WAP to concatenate two strings.

Question C18: WAP to compare two strings.

Question C19: WAP to replace every space in a string with a hyphen, tab with a hash and digit with a slash.

Question C20: WAP to input a string and replace every lower case letter with upper case letter, upper case
letter with a lower case letter, digit with a ‘#’ and a special symbol with a ‘%’. Display the new string.

Question C21: WAP to encrypt and decrypt a string using your own method of encryption and decryption.

Question C22: WAP to reverse all the strings stored in an array.

Question C23: WAP to swap two strings stored in an array.

Question C24: WAP to input 5 strings in an array of strings and display all the strings with their lengths.

Question C25: WAP to search a string in the array of strings.

Question C26: WAP to display all the palindrome strings from the array of strings.

Question C27: WAP to convert a string into upper case and vice versa.

Question C28: WAP to extract given number of characters from the left of the string.

Question C29: WAP to extract given number of characters from the right of the string.

Question C30: WAP to extract given number of characters, from the desired location from the string.

Question C31: WAP that will print out all the rotations of a string. For example the rotations of the word “abc”
areabc bca cab

Question C32: WAP that replaces two or more consecutive blanks in a string by a single blank.

Question C33: WAP to input 10 names in a 2D array of characters and replace the 1st name with 5th name and
display the resultant array.

Question C34: WAP to input two strings consists of maximum 80 characters. Examine both the strings and
remove all the common characters from both the strings. Display the resultant string.

Question C35: WAP to test whether a string of opening and closing parentheses is well formed or not.

Question C36: WAP to evaluate a postfix expression given by the user.

Question C37: WAP to evaluate a prefix expression given by the user.

Question C38: WAP to convert a given infix expression to prefix and postfix expression.

Question C39: WAP to convert a postfix expression to the prefix expression and vice versa.

Question C40: WAP to convert a postfix expression to infix expression.

Question C41: WAP to input an arithmetic expression comprising of numeric constants and operators and
evaluate the expression at the input.

124
Question C42: Write a function which has two strings x and y as arguments. The function finds out the first
symbol of x which does not occur in y.

Question C43: Write a program to check that any one of given n strings occur in a string s.

Section D: Programs based on arrays

Question D1: WAP to input the marks of 10 students in an array of integers and display the marks.

Question D2: WAP to search how many times a number is present in an array.

Question D3: WAP to subtract two arrays of the same size.

Question D4: WAP to input the sales made by a salesman in every month of a given year and find out the total,
average, maximum and minimum sales.

Question D5: WAP to calculate the average of 10 values stored in an array and display all those values which
are more than the calculated average.

Question D6: WAP which finds the locations and values of largest and second largest element in a one
dimensional array.

Question D7: WAP to reverse an array of floats.

Question D8: WAP to create a sorted list using arrays. Every time the element is entered in the array, the array
must remain sorted.

Question D9: WAP to rotate an integer array towards right by the given number of times.

Question D10: WAP to input 20 values in an integer array and count the negative, positive, odd and even values
in the array.

Question D11: Given an array named A with following elements:

3, -5, 1, 3, 7, 0, -15, 3, -7, -8

WAP to shift the negative numbers to the left and positive numbers to the right so that the

Resultant array look like the-5, -15, -7, -8, 3, 1, 3, 7, 0, 3

Question D12: WAP to copy the last 5 elements of array B after first 5 elements of array A. Assume length of A
and B is greater than 5.

Question D13: WAP to print all the palindrome numbers from an integer array and find out their sum.

Question D14: WAP to print all the prime numbers from an integer array and find out their sum.

Question D15: WAP to input 10 values in a float array and display all the values more than 75.

Question D16: WAP delete an element from the array and shift the elements

Towards [Link] left

125
Question D17: WAP to delete all the occurrences of a given value from the array and shift the remaining
elements to the left of the array.

Question D18: WAP to delete duplicate elements from an array.

Question D19: WAP to insert a value in the array at desired location.

Question D20: WAP to insert a value in the sorted array.

Question D21: WAP to sort an array.

Using bubble sort technique

Using selection sort technique

Using insertion sort technique.

Using Quick sort technique

Using Heap sort technique.

Question D22: WAP to check that given array is sorted in ascending / descending order.

Question D23: WAP to search a value in the array using

Linear search [Link] binary search technique.

Question D24: WAP to count the number of occurrences of a given number in an integer array.

Question D25: An array consists of 50 integers in the range of 1 to 25, write a program that prints the number
of times each integer occurs in the array.

Question D26: A, B, C are the arrays of integers of size a, b, a + b, Write a program to produce a third array C
containing all the elements of array A and B.

Question D27: WAP to merge two arrays according to the following conditions:

First array Second array Resultant array

(1) Ascending Ascending Ascending

(2) Ascending Ascending Descending

(3) Ascending Descending Ascending

(4) Ascending Descending Descending

(5) Descending Descending Ascending

(6) Descending Descending Descending

126
Question D28: WAP to add and multiply two large integers, which cannot be represented by built in data types.

QuestionD29: WAP to delete all elements in between and occupying two specified positions.

Question D30: WAP to search the first occurrence a given sub array within another array.

Question D31: WAP to merge 4 arrays a, b, c, d in one array. All the arrays are in ascending order.

Section E: Two Dimensional arrays:

Question E1: WAP to input the values in a two dimensional array of integers and display the values.

Question E2: WAP to display the values of a two dimensional array in the matrix form.

Question E3: WAP to find out the row sum and column sum of a two dimensional array of integers.

Question E4: WAP to double all the elements of a matrix.

Question E5: WAP to print the left and right diagonal of a square matrix and find out their sum separately.

Question E6: WAP to find out the sum of non-diagonal elements.

Question E7: WAP to display the upper and lower triangle of a matrix.

Question E8: WAP to find out the sum and difference of two matrices.

Question E9: WAP to find out the product of two matrices.

Question E10: WAP to find out the sum of negative, positive, odd and even integers separately from a two
dimensional array.

Question E11: WAP to display those elements of a two dimensional array which are divisible by 10. Also find
their sum.

Question E12: WAP to find out the sum of those numbers in the in a 2D array of integers which are divisible by
4 but less than 15.

Question E13: WAP to print all the prime numbers from a 2D array and find out their sum.

Question E14: WAP to transpose a square matrix.

Question E15: WAP to find the inverse of the matrix.

Question E16: WAP to find out the sum of the elements above and below the main diagonal of a square matrix.

Question E17: WAP to check the equality of two matrices.

Question E18: WAP to print all the elements of a square matrix except the diagonal elements.

Question E19: WAP to find the maximum, minimum and second maximum of a matrix.

Question E20: WAP to sort the elements of a matrix row- wise and column-wise.

Question E21: WAP to print squares of diagonal elements of a square matrix.

127
Question E22: WAP which finds the locations and values of largest and second largest element in a two
dimensional array.

Question E23: Using a two dimensional array A[n*n], write a program to prepare a one dimensional array B[n2]
that will have all the elements of A as if they are stored in column major form.

Question E24: Using a two dimensional array A[n*n], write a program to prepare a one dimensional array B[n2]
that will have all the elements of A as if they are stored in row major form.

Question E25: WAP that receives the month and year from the keyboard as integers and prints the calendar
of the given month. (According to the Gregorian calendar 01/01/1900 was Monday)

Question E26: WAP to print the lower half and upper half of a square matrix.

Question E27: WAP to construct a magic square.

Question E28: WAP to find out the trace of a matrix.

Question E29: WAP to compute the determinant of a square matrix of real numbers.

Question E30: Sparse Matrix.

Section F: Programs based on Functions:

Question F1: Write a function that takes one integer argument and returns its square.

QuestionF2: Write a function to calculate the cube of a number.

Question F3: Write a function to calculate the area of a circle where radius is passed to the function as
argument.

Question F4: Write a function to calculate the area of a rectangle where length and breadth are passed to the
function as argument.

Question F5: Write a function that has three arguments principle, rate and time and returns the simple interest.

Question F6: Write a function that accepts a character as argument and returns its ASCII value.

Question F7: Write a function to swap the values of two integer variables

Using Extra variable

Without using extra variable.

Question F8: Write a function that has one integer argument and returns 0 if number is even else returns 1.

Question F9: Write a function that has one character argument and displays that it’s a small letter, capital
letter, a digit or a special symbol.

Question F10: Write a function to print the sum and average of first n natural numbers where n is passed to
the function as argument.

Question F11: Write a function to print the sum and average of first n odd numbers where n is passed to the
function as argument.

128
Question F12: Write a function that returns the factorial of a number where number is passed to the function
as argument.

Question F13: Write a function that returns 1 if the number is prime and 0 if not prime. Number is passed to
the function as argument.

Question F14: Write a function that prints the sum of the digits, count of the digits and reverse of a number.
Number is passed to the function as argument.

Question F15: Write a function that returns the sum of the following series where x and n are passed to the
function as argument.

1 + x2/2! + x4/4! + x6/6! + …….xn/n!

1 - x2/2! + x4/4! - x6/6! + …….xn/n!

1 + x/2! + x2/4! + x3/6! + x4/8! + ......... xn/(2n)!

1 + x/1! + x3/2! + x5/3! + x7/4! +.......... x2n-1/n!

1 + x2/1! + x4/2! + x6/3! + x8/4! +… ....... x2n/n!

Question F16: Write a function that has two integer arguments and returns first number raised to the power
second number.

Question F17: Write a function called zero_small that has two integer arguments being passed by reference
and sets the smaller of two numbers to 0.

Question F18: Write a function that receives a string (character array) as argument and produces a string in
which first letter of each word is capitalized.

Question F19: Write a function that receives a string and a character as argument and returns 1 if the character
is found in the string else returns 0.

Question F20: Write a function to search a given string into another string and returns the position if found
otherwise returns 0. Both the strings are passed to the function as argument.

Question F21: Write a function to return the length of the string. String is passed to the function as argument.

Question F22: Write a function to reverse a string.

Question F23: Write a function to search a string in the array of strings. String and array of strings should be
passed to the function as parameters.

Question F24: Write a function to copy one string into another string. Both the strings are passed to the
function as argument.

Question F25: Write a function to compare two strings. The strings must be passed to the function as
argument. The function should return 0 if the strings are equal else returns 1.

Question F26: Write a function to extract given number of characters from the right of the string. String and
integer must be passed to the function as argument.

Question F27: Write a function to evaluate a prefix / postfix expression.


129
Question F28: Write a function to sort an array using:

bubble sort technique

selection sort technique

insertion sort technique

Array is passed to the function as argument.

Question F29: Write a function to delete an element from the array. Array, element to be deleted and size of
the array are passed to the function as argument.

Question F30: Write a function that receives an array and a number as argument and returns number of
occurrences of the number in the array.

Question F31: Write a function that receives an array and a number as argument and returns 1 if the number
is found in the array else returns 0. (Search the number using binary search)

Question F32: Write a function that has three arrays a, b, c as arguments of size m, n and m + n respectively.
The array a is in ascending order, b is in descending order and function should merge both the arrays and
stores them in c in descending order.

Question F33: Write a function that receives a 2D array of integers as argument and prints the sum of row
elements and column elements separately.

Question F34: Write a function to find out the product of two matrices. Matrices are passed to the function as
argument.

Question F35: Write a function to transpose a square matrix. Matrix is passed to the function as argument.

Question F36: Write a function to check the equality of two matrices. Matrices are passed to the function as
argument and function returns 1 if they are equal else returns 0.

Section G: Programs based on pointers:

Question G1: Write a function to swap the values of two integer variables. The addresses of the variables
should be passed to the function as argument.

• Using extra variable


• Without using extra variable
Question G2: Write a function which receives the addresses of two integer variables and returns the address
of the variable whichever is greater.

Question G3: Write a function that prints the sum of the digits, count of the digits and reverse of a number
using a pointer. Address of the number is passed to the function as argument.

Question G4: Write a function having one argument of string type and print the string in the following pattern
using pointers.

R RAJAT

130
RA RAJA
RAJ RAJ
RAJA RA RAJAT R

Question G5: Write a program to print the following patterns using pointers.

A A
AB BB
ABC CCC
ABCD DDDD

ABCD DDDD
ABC CCC
AB BB
A A

ABCDEFGFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A

Question G6: Write a function to count the number of spaces, tabs and new line characters in a given string
using pointers. The string must be passed to the function as argument.

Question G7: Write a function to count the numbers of vowels, consonants, digits and special symbols in a
given string using pointers. The string must be passed to the function as argument.

Question G8: Write a function to extract specified number of characters from a given position from a string
using pointers. The function has one string argument and two integer arguments.

Question G9: Write a function to concatenate two strings using pointers. Function has two string arguments.

Question G10: Write a function to compare two strings using pointers. Function has two string arguments and
returns 0 if strings are equal else returns 1.

Question G11: Write a function to encrypt and decrypt a string using pointers and use your own method of
encryption and decryption.

Question G12: WAP to reverse all the strings stored in an array using pointers

Question: Write a function to swap two strings stored in an array using pointers. The array of strings is passed
to the function as arguments.

Question G13: Write a function to display all the palindrome strings from the array of strings using pointers.
The array of strings is passed to the function as arguments.

Question G14: Write a function to reverse an array of floats using pointers. The array must be passed to the
function as argument.
131
Question G15: Write a function to print all the palindrome numbers from an integer array and find out their
sum using pointers. The array must be passed to the function as argument.

Question G16: Write a function to delete duplicate elements from the array using pointers. The array must be
passed to the function as argument.

QuestionG17: Write a function to sort an array using bubble sort technique using pointers. The array must be
passed to the function as arguments.

Question G18: Write a function to search a value in the sorted array using binary search technique using
pointers. The array and value must be passed to the function as argument and function should return 1 if found
else returns 1.

Question G19: Write a function to find out the row sum and column sum of a two dimensional array of integers
using pointers. The array must be passed to the function as argument.

Question G20: Write a function to find out the product of two matrices using pointers. The arrays must be
passed to the function as argument.

Question G21: Write a function to transpose a square matrix using pointers. The array must be passed to the
function as argument.

Question G22: Write a function to sort the elements of a matrix using pointers. The array must be passed to
the function as argument.

Section H: Programs based on recursion:

Question H1: WAP to calculate the GCD of two numbers using recursive function.

Question G2: WAP to find out the factorial of two numbers using recursive function.

Question H3: WAP to print Fibonacci series using recursive function.

Question H4: WAP to sort an array using Quick sort technique (recursive).

Question H5: WAP for the recursive Depth first search.

Question H6: WAP for the recursive Breadth first search.

Question H7: WAP to sort an array using recursive merge sort technique.

Question H8: Write a recursive merge sort algorithm.

Question H9: Write a recursive function to multiply two polynomials.

Section I: Programs based on structures:

Question I1: WAP to define a structure with the following specification

Structure name Emp


Ecode integer

Ename character array

132
Basic salary float

Hra float 40% of basic salary

Da float 20% of basic salary

Ta float 10% of basic salary

Gross salary float basic salary + hra + da + ta

It float 20 % of gross salary

Pf float 10% of gross salary

Net salary float gross salary – (it + pf)

Now perform the following operations:

(1) Take an object of the given structure, input the values for the ecode, ename, basic salary, calculate all
other values and display the values.

(2) Take an array of objects of size 10 of the given structure and input, calculate and display the values for
10 employees.

Question I2: WAP to declare a structure with the following specification:

Structure name abc

Arr array of 10 floats


Max float maximum of 10 values

Min float minimum of 10 values

Sum float sum of 10 values

Avg float average of 10 values


Take an object of structure type and input the values in arr and calculate all other values.

133

You might also like