[go: up one dir, main page]

0% found this document useful (0 votes)
15 views160 pages

PPS - 2

This document provides an introduction to C programming, covering its basics, structure, variables, data types, and memory storage. It explains the features of C, such as being a high-level, structured, and portable language, and details the components of a C program including functions, variable declarations, and program statements. Additionally, it discusses how different data types are stored in memory and the concept of tokens in C programming.

Uploaded by

musthakshaik999
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)
15 views160 pages

PPS - 2

This document provides an introduction to C programming, covering its basics, structure, variables, data types, and memory storage. It explains the features of C, such as being a high-level, structured, and portable language, and details the components of a C program including functions, variable declarations, and program statements. Additionally, it discusses how different data types are stored in memory and the concept of tokens in C programming.

Uploaded by

musthakshaik999
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
You are on page 1/ 160

MODULE -1

INTRODUCTION TO C PROGRAMMING
1.1 Basics of C Programming:
What is computer programming language?

Language is a means to communicate or interact. For example, in this course, English is being used as
the language to communicate or provide instructions to the learner. Similarly there are certain languages
which can be used to provide instructions to computers. These are called computer programming languages.
These languages provide a way to represent data (like numbers, text or images, etc.) and also provide a way
to represent instructions which manipulate or work with that data.

In 1972, AT&T (American Telephonic & Telegraphic) Bell Laboratories in New Jersey designed the
"C" programming language. "B" and "BCPL" languages had the biggest effect on it. A group of experts was
formed in 1983 by the American National Standard Institute (ANSI) to formalize the C language.

C is an Imperative programming language and supports Structured programming. A program in an imperative


programming language is constructed from a combination of functions as well as methods. If we want a
computer to print a greeting message on monitor, we will have to provide instructions to computer using a
computer programming language.
As an illustration, to print "Hello!" using C programming language, we will have to provide instructions as per
C programming language's grammar and vocabulary as given below:

The text given above is called source code or simply code. Since it is written in C, it is also called C code.
The code given above represents a simple C program which prints "Hello!”.
Features/Characteristics’of C Language:
• High Level language:
C is versatile enough to tackle any challenge because it combines Middle-level and High-level
language capabilities, the programming language
• Structured Programming language:
The„C‟programminglanguageiscalledasBlock/Module/Function/Structured oriented language, because
it divides the given problem into set of functions.
• Robust:
The„C‟programming language is robust because it consists of many language features like arrays,
functions, pointers, variety of operators and data types etc.
• Portable/Machine Independent :
In„C‟language the program designed in one machine can work in another machine with small
modifications.
• Efficient and Fast in Execution:
Because of language features like Dynamic Memory Management with Pointers ,the„C‟ programs are
1
efficient and fast in execution
• Ability to extend itself:
The„C‟programming language can extend it features by designing new Userdefined Library functions.

1.2 Structure of a C program:


Structure/ General form Program

Documentation/Comment Section /* to find perimeter of a circle */

#include<stdio.h>
Linkage/ Preprocessor directive /File
#define Pi 3.1415
Include Section
User defined Function / Subprogram
float perimeter();
prototype/Declaration Section
Global Variables Declaration Section float rad, res;
void main()
{
main () Section float m;
Local varaibles printf(“provide rad:“);
Executable statements scanf(“%f”,&rad);
m = perimeter();
printf(“perimeter : %f”,m);
}
User defined Function
/Sub Program float perimeter()
Definition/Implementati {
on Section Function 1() res = 2 * Pi * rad;
Local varaibles return (result);
Executable statements }
function2()
.....

Documentation Section: Comments are represented with statements enclosed between /* and */. The
statements specify the purpose of the program for better understanding. Any statements enclose within /* and
*/ are not executed by the compiler. This section is optional and if required can be used in any part of the
program.

Linkage/ Preprocessor directive /File Include Section: This section contains instructions which are
processed before the compiler executes the program statements. There are two types of pre-processor
directives namely File inclusion and Macro (constant) pre-processor directive

User defined Function / Subprogram Prototype/Declaration Section: This section serves the purpose of
declaring user defined functions that can be used in the program.

Global Variables Declaration Section: Variables declared here for its type can be used through out the
program.
2
main( ) Section: main( ) should be included in all programs. Every C program executes from main( ). The
main function consists of Local Declarations and Executable statements. For every program the above two
parts should be enclosed in flower braces with { denotes the starting point of the main( )and } denotes the end
of main( ).

Local variable declaration: Variables declared here for its type can be used only in the main() function.
Executable Statements: The statements can be an input or output or function call or assignment or return
statement.

User defined Function /Sub Program Definition/Implementation: Functions defined by the user.
These are placed mostly after the main() function or above the main() function.

1.3 Concept of a variable

• In C, a variable is the name assigned to a location in memory in which data can be stored by a program.
A unique identifier is required for every variable in order to uniquely identify the location of memory.
• The value saved using a variable's identifier can be stored and altered by a program. Before they can be
used in a program, variables need to be specified.
• A variable can have many values while a program is running.
• Constant can only take on a single value.
• .
Example:
int a; - a is an integer variable .
char c; - c is a charater variable
float p; - p is float variable
double q; - q is double variable
void h; - h is void type .
Rules regarding C Variable Names
• Underscore character, numbers, and letters may be combined to set up the variable name.
• It needs to start by including an underscore or a letter. (unable to start with digit)
• C considers lowercase and uppercase letters are different as C is case-sensitive.
• Donot include space between variables.
• The variables may contains up to 31 length.
• Do not use keywords as variables.
Declaration of Variable
In this case, variable_list can have any number of variable names divided by commas, and type has to be a
proper data type, such as char, float etc.
Syntax:
type variablename;
type variable_list;
or
type variablename1,variablename2,variablename3,…..;
For Example,

int a, y, sum1;
char h;
float m, sal_1;
3
double x;
1.4 Data types in C
• A data type specifies a collection of elements and the possible operations on them.
• It is utilized to declare functions or variables of different types.
• A variable's type impacts both the amount of storage space it takes up and how the arrangement of bits it
stores is processed.
Categories of data types:-
The „C‟ language Data type is categorized into:
1. Primary Data types: The aforementioned data types are the language's essential data types.
There are the following:
1. Float (or) real data type
2. Character data type
3. Integer data type
4. Double data type. and
5. Void data type
2. Derived Data types: These are designed from the fundamental data types. They are usually Arrays,
Structures, Unions, Functions etc,.
3. User defined Data types: The user created these for a particular purpose. Typedef and
enum are used in its design.

4
Integer Data type:
Integers are numbers without decimal point. The integer type supports three categories of integer data
type to support wide verity of values. They are long int, int and short int, can be either signed or unsigned
data type to support both positive and negative values.
Example: 435, -10500, +15, -25, 32767 etc.
The integer data type occupies one word of storage, and size of word machine/computer varies, the size of
the integer data type depends on the computer. A signed integer represents sign in one bit for sign and
magnitude in remaining bits. The table shows notation, size, range of values, data type character.
Float/Real Data type:
The float data type supports larger vales than integer data type and also supports more accuracy /
efficiency of value than integer. The float value has a integer part and fractional part that are separated by a
decimal point. It supports both decimal point notation and scientific notation to represent float values.

Example: 3.01234, 0.00034, 1234.0


Decimal point notation.
15.0e-04 (0.0015), 2.345e2 (234.5), 12e5 (1200000.0)
Scientific notation.

The float data type occupies generally 4 words of storage with 6-digits of precision (no. of digits of after
decimal point). The precision can be increased to increase accuracy.
Character data type:
One character value, such as a letter, number, or special character, can be stored using the character data
type. Every character has a single quote surrounding it. There are two possible character data types: signed
and unsigned. One byte is utilized for the character data type.
Example: „a‟, „2‟, „R‟, „;‟ etc.
The table shows notation, size, range of values, data type character.

Void data type:


The data type void does not consist of values. It is capable of representing any other data type value by
taking on a generic type role. Typically, the type of functions is specified using this void type. When a
function of a certain type returns null to the caller function, it is referred to be void.
1.5 Program statement

• Programs written in C consist of statements; each statement is an executable section that the program
uses to carry out certain tasks.
• Categories of Statement
– Jump Statements.
– Iterative Statements.
– Selection Statements
– Compound Statements.
– Expression Statements.

5
Jump Statements:
• These statements are unconditional and they are helpful for shifting control from one area of
the program to another.
Example:
Continue
goto
break
Iterative Statements:
• Another name for these is loops. Loops are used when we wish to run a software segment
repeatedly.
• A collection of fundamental loops:
do-while, for etc.
Selection Statements:
• Selection Statements are used in decisions making situations.
Example:
switch
Nested if
if…else
simple if
Compound Statements:
• A compound statement is made up of multiple expression statements combined.
• The Braces {} contain the Compound Statement.
• A semicolon is not required at the end of a compound statement, which is also known as a
block statement.
Ex
float x=9,y=5,m;
m = x + y;
printf(“m = %d”,m);
Expression Statements:
Function calls, operators, constants, variables and a semicolon are all combined in a statement.
Example:
P= Q + 10;
50 > 100;
x?y:z;
b = 30 + 40 * 2;
1.6 Declaration
• A declaration in programming is a statement that describes an identifier, like the
function_name or variable_name. It explains to the compiler or interpreter the meaning of an
identifying term and the appropriate use of an identified object.
• The necessity of a declaration varies based on the programming language. Variables cannot be
allotted values until they have been assigned with a specified data type.

6
1.7 Storing the data in memory
• Computer memory is comprised of several cells, each of which is made up of
semiconductors that has the ability to store energy.

• The computer communicates with its other components via machine language, or low-level
language, which is made up of the binary system. There are two bits in a binary system: 1 &
0. A bit (binary digit) is a tiny unit for data in a computer.
Storing The Integer In Memory :

65 (Integer)

The binary representation of 65 is (1000001) 2.


The number's positive or negative sign is indicated by the MSB (most significant bit) bit.
The MSB for a positive number is 0.
MSB for negative numbers is 1.
MSB will be zero as 65 is positive.
Binary representation of 65 can be saved in 32-bit memory as seen below.

Storing Negative Integers In Memory


• The computer stores negative numbers in the 2's complement format using a unique technique.
Steps to store negative integers
1‟s complement of a number
• Process of switching 0 to 1 and 1 to 0 is called 1‟s compliment of number.
Example: - 10
• (1010) 2 is the binary equivalent of 10
• 0101 is 1‟s compliment of 10
2‟s complement of a number
• Increase 1's complement of actual value by 1 is 2's complement of that number.
• The computer will store the 2's complement.

7
Storing float values in memory
In the computer, 4-byte (32-bit) memory will be set aside for the storage of a floating-point
number.
• sign -1 bit
• exponent part -8 bit
• Mantissa part -23 bit

Steps:
1.Binary equivalent of 10.75 is (1010.11) 2
2. To normalize the number, transform the binary number. We always normalize floating point
numbers in the following way:
1.significant bit * 2 exponent
Normalized form of 1010.11 is 1.01011 * 2 3.

8
3.Add bias to exponent
• In order to simplify implementation, bias value is typically added to exponent value, whether it is
positive or negative.
• The formula for determining the bias value is biasn = 2 n-1 - 1.
• The exponent has been assigned eight bits in this case. Thus, n = 8
• Consequently, 2 7 - 1 = 127
Therefore, the actual exponent plus the bias value, or 130 (3 + 127), will be the normalized
exponent value. (10000010) 2 is 130 in binary form.
Example
• Since 10.75 is a positive number, sign bit 0 is used. The exponent value is 130, or (10000010)2
• The significant value is 1.01011, thus we can remove 1 before the dot (.) since we will always
normalize any integer as 1. .

Thus, there's no need to keep the 1. Simply extract the 01011 bits that come after the dot (.).

Storing double values in memory


• The system will assign 8 bytes (8*8 bits) of memory to hold double.
sign -1 bit,
exponent -11 bit

9
Mantissa-52 bit

• The bias value is the only distinction between the double and float representations.
• The exponent in this case is 11 bits.
• Therefore, the bias value will be 211 - 1 - 1, or 210 - 1, or 1023.
• 1023 can be added to actual exponent in case of double. The rest of the procesure is similar to the
floating representation.
How character is stored in Memory?
• When trying to save the value of a character on a computer, the associated ASCII value is
stored instead of the character.

For instance, the corresponding ASCII value will be kept in the computer if we wish to save
the character "A" in computer.
• The capital A's ASCII value is 65.
• The computer will assign 1 byte (8 bits) of memory to hold character values.

10
• The binary representation of 65 is (1000001) 2.
• Eight-bit memory will then be used to hold 1000001.

1.8 TOKENS
C tokens are the individual units or basic building blocks that are utilized to develop C programs.
Types of C tokens:
i. Special characters
ii. Keywords
iii. Constants
iv. Identifiers
v. Operators

Special characters
The C character set includes:
Special symbols: ~ ! # $ % ^ & * ( ) [ ] { } “ / \ | ? „ . ,
Numbers: 0,1,..,9
Letters: A-Z
a-.z
Keywords:
• The compiler defines predefined words. Another name for these is reserved words.
•The C language has 32 keywords. They're –
for, while, do, struct, union, auto, static, register, extern, const, volatile, sizeof, return, goto,
continue, break, default, case, switch, else, if, enum, typedef, void, short, long, unsigned, signed,
double, float, int, Char.
Constants:
• Constants does not change its values during the execution.
• Fixed values that the program may not change while it is running are referred to as constants.
Literals are another term for these set values.
• Constants can be literal strings, floating-point numbers, character constants, or any of the
fundamental data types. Additionally, there are enumeration constants.
#define PI 3.14

11
• Constants are handled in the same way as ordinary variables, with the exception that once they
are defined, their values cannot be changed.

How to Define constants:


• Defining constants can be of 2 ways
 const keyword.
 #define preprocessor.
using #define Preprocessor:
Syntax
#define constantname value
Using CONST KEYWORD:
Syntax
const datatype variablename = value;
const m =1.8;
Types of constants
Integer constant
• A series of digits from 0 to 9 without decimal points, fractional parts, or any other symbols is
called an integer constant..
const int y = 123;
Real Constants
• The representation of Real Constants has a fractional component.
const float x = 6.3;
Single Character Constants
• One character enclosed in two quote marks is represented by a single character constant.
String Constants
• A group of characters surrounded by double quote marks is known as a string constant.
• For example, string constants in C: "Hello World", "123", etc.
Identifiers:
• Unique names assigned to variables, constants, and other program objects is referred as
Identifiers.
• Identifiers are defined by the users.
• The rules of identifiers are as same as variables.
• All variables are identifiers but all identifiers are not variables.
Const B =10; int a=15;
Const C=10;
Identifier rules:

1. Valid characters for identifiers are letters (both uppercase and lowercase), digits, and underscore _.
2. The first character must be a letter or an underscore.

12
3. Identifiers cannot have the same name as C keywords (reserved words). For example, you cannot
use int, while, if, etc., as identifiers.
4. It is not appropriate to redefine an identifier specified in a C Standard library.
Printf() scanf() main() sizeof(),type(),ftell(),fopen()
5.C is case-sensitive, so uppercase and lowercase letters are considered distinct
Ex:count and Count are different identifiers.

1.9 Operator
In the C programming language, operators are special symbols that represent computations or
operations on variables and values. C supports a variety of operators, which can be broadly
categorized into the following types:

 Conditional Operators
 Assignment Operators
 Bitwise Operators
 Logical Operators
 Relational Operators
 Arithmetic Operators
 Comma operator
 Increment and decrement operators
Conditional operator:

• Conditional operator is denoted by ? :.


• It is ternary operator because it contains three arguments.
Syntax
condition?statement_1:statement_2;
If condition is true, then statement_1 executes.
If condition is false, then statement_2 executes.
Ex:
1<10?6;9;
• If 1<10 is true ? it gives 6 : false it gives 9.

Assignment Operators:
• In C programming, the assignment operator is denoted by the equals sign
(=). It is used to assign a value to a variable.
• The general syntax is:
Variable =expression;
• Here, variable is the name of the variable that you want to assign a value to, and
expression is the value that you want to assign to the variable complex expression.
Example: len=5;

area = length * width

13
Bitwise Operators:

In C programming, bitwise operators are used to perform operations on individual bits of integer
operands. There are six bitwise operators in c:

Bitwise AND (&):


 The bitwise AND operator is denoted by &.
 It performs a bitwise AND operation between each pair of corresponding bits of the two
operands.
 Example: result = a & b; (Sets each bit to 1 if both bits are 1 in the corresponding operands).
Bitwise OR (|):
 The bitwise OR operator is denoted by |.
 It performs a bitwise OR operation between each pair of corresponding bits of the two
operands.
 Example: result = a | b; (Sets each bit to 1 if at least one bit is 1 in the corresponding operands).
Bitwise XOR (^):
 The bitwise XOR (exclusive OR) operator is denoted by ^.

14
 It performs a bitwise XOR operation between each pair of corresponding bits of the two
operands.
 Example: result = a ^ b; (Sets each bit to 1 if only one of the bits is 1 in the corresponding
operands).
Bitwise NOT (~):
 The bitwise NOT operator is denoted by ~.
 It performs a bitwise NOT operation on each bit of the operand, changing 1 to 0 and 0 to 1.
 Example: result = ~a; (Inverts each bit in the operand).
Left Shift (<<):
 The left shift operator is denoted by <<.
 It shifts the bits of the left operand to the left by a specified number of positions.
 Example: result = a << n; (Shifts the bits of a to the left by n positions).
Right Shift (>>):
 The right shift operator is denoted by >>.
 It shifts the bits of the left operand to the right by a specified number of positions.
 Example: result = a >> n; (Shifts the bits of a to the right by n positions).
Here A=60, B=13

Logical Operators:

• In C programming, logical operators are used to perform logical operations


on boolean values (true or false). The three main logical operators in C are:

15
• The logical AND operator returns true if both operands are true,otherwise it
returns false.
• The logical OR operator returns true if at least one of the operands is true;
otherwise, it returns false.
• The logical NOT operator is a unary operator that negates the value of its
operand. If the operand is true, the NOT operator returns false, and if the
operand is false, it returns true..

Relational operators
• • The symbols known as relational operators are employed to examine the relationship
among a variable and a constant, or among two variables.
• Six relational operators in C :

Here A=10, B=20

16
Arithmetic Operators:
There are five arithmetic operators in C. They are

Example: A=10 B=20

17
Increment And Decrement Operators:
In C programming, the increment and decrement operators are used to increase or decrease the value of
a variable by 1, respectively. These operators are commonly denoted as ++ (increment) and –
(decrement).
When the operators ++ or -- appear before the operands, they are called as the prefix operators. When
the operators ++ or -- appear after the operands, they are called as the postfix operators.When an
increment (++) or a decrement (--) operator is used as a prefix (i.e., applied before an operand) for
example, as ++i or --i, the value of the operand is changed first.
The changed value is then substituted in the expression. When an increment (++) or a decrement (--)
operator is used as a postfix (i.e.,applied after an operand) for example, as, i++ or i--, the original value
of the operand is first substituted in the expression and then the operand value is changed. After
understanding the prefix and postfix operators, select all the correct statements for the code given
below:

int main() {
int m, p,o, r;
m = 10;
p = -m;
o = m++;
r = ++m;
}

Comma operator

18
Two special operators are defined in c: the comma (,) and the sizeof .
The Comma(,) operator is used to declare multiple expressions in a single statement. (,) operator acts as
a separator between multiple expressions, in declaring multiple variables and in function call
parameters. Given below are a few examples of comma(,) operator:

sizeof operator
This operator is also called compile-time operator and it returns the size of the operand.. The format of
size of operator is:
sizeof(operand)
Ex:
float r;
sizeof(r);
size of r is 4 bytes.
OPERATORS PRECEDENCE IN C:
• Operator precedence in C determines the order in which operators are evaluated in an expression.
• Operators with higher precedence are evaluated before those with lower precedence. If operators
have the same precedence, the associativity of the operators comes into play.
• Here‟s a general overview of the operator precedence in c, from highest to lowest.

19
Associativity is relevant when operators of the same precedence appear in an expression. For example,
the addition operator + is left-associative, meaning that in the expression m+n+o, the leftmost + is
evaluated first i.e m+n
Expressions:
An expression is a set of operators, functions, variables and that results in a single value. Expressions
can be simple, like a variable or a constant, or complex, involving multiple operations. Here are some
examples of expressions in C:
Example:
r+s
l=m
x=y-1
a<=c

20
sum=sum+b[j]
s= = t
z++
r=d+*m
x=x+factorial(n)
1.10 Lvalues and Rvalues

Lvalue (left value) refers to an object that occupies some identifiable location in memory (i.e., it has
an address). An rvalue (right value) refers to a value that is stored at some address in memory or a
temporary value that doesn't have a persistent address. The terms "lvalue" and “rvalue” are often used
in the context of expressions and assignments.
Lvalues:
 An lvalue is an expression that refers to an object in memory, and it has an identifiable
location(address).
 Examples of lvalues include variables, array elements, and dereferenced pointers.
m=5; // m is lvalue
a=r+s; // a,r,s are lvalue

Rvalue:
 An rvalue is an expression that represents a value, but not necessarily an object with an
identifiable location in memory.
 Literal constants, results of expressions, and temporary values are examples of rvalues.
m=5; // 5 is rvalue
a=r+s; // r+s are rvalue

Understanding the distinction between lvalues and rvalues is important in C, especially when working
with pointers, references, and expressions involving values and addresses. It helps to grasp concepts
such as memory management, pointers, and the semantics of C expressions.

1.11 Type conversion in C:


• Type conversion in C involves converting a value from one data type to another. C supports
two types of type conversions: implicit (automatic) and explicit (manual).
• Implicit type conversion is performed by the compiler without any intervention from the
programmer. It occurs when values of one data type are automatically converted to another
data type.

21
Explicit type conversion:

Programmers execute explicit type conversion, commonly referred to as type casting. The desired data
type must be specified in parenthesis prior to the value to be transformed in order to accomplish this.

Syntax:

(type) expression

22
1.12 Basic screen and Keyboard I/O in c:

• I/O operations facilitate user interaction within a program.

• The standard C library for input-output operations is called C stdlib.

- Stdout is the standard output;

- Stdin is the standard input.

• Standard input, sometimes known as stdin, is a data stream that is used to receive input from
devices like keyboards.

• To provide output to a device like a monitor, utilize standard output, often known as stdout.

• Programmers need to include the stdio header file in their programs in order for I/O to function.

1.13 Formatted I/O Functions:

Formatted I/O functions in C are used to perform input and output in a formatted manner. The two
main functions for formatted I/O in C are printf for output and for input. These functions use format
specifiers to define the type and format of the data being read or written.

• Here are some commonly used format specifiers for printf and scanf:
List of some format specifiers :

23
formatted I/O functions are

• printf()

• scanf()

printf():

• Any value, such as a float, integer, character, string, etc., can be shown on the console screen in a C
application.

• The function is pre-defined and has been declared in the header file stdio.h.

Syntax 1:

• To print one or more varaiables

printf(“Format Specifier”, var1, var2, …., varn);

Ex:

24
Syntax 2:

• To print any string or a message

printf(“Enter the text to print ”);

Ex:

scanf()

It may read or take any value from the keyboard by the user and is used in C programs. It can take
many different data types, including float, integer etc.

25
This function is pre-defined and it is declared in the header file stdio.h. The &(address-of operator)
function in the scanf() function is used to store the value of the variable in the variable's memory
location.

Syntax:

• scanf(“format specifier”, &variable_1, &variable_2, …., &variable_n);

Unformatted Input/Output functions

• These functions are used to read a single user input at the console and allow the value to be displayed
at the console.

• Unformatted I/O functions are only used for character type or string and never be used other
datatype.

unformatted I/O functions are

1. gets()

2. getchar()

3. getche()

4. getch()

5. putch()

26
6. puts()

7. putchar()

gets():

• The user types a string or collection of characters on the keyboard, and the characters are read and
saved in a character array.

• We can write sentences or strings that are separated by spaces thanks to this function. The header file
stdio.h has the declaration for this function.

Syntax:

gets(str);

str is string.

Ex:

getchar():

• The getchar() function reads one character at a time until and unless the enter key is pressed, and
it is used to read only the initial single character from the keyboard, regardless of how many characters
the user types.

27
• The function is defined in the header file stdio.h.

Syntax

Variable-name = getchar();

getche():

• It takes one character from the keyboard, shows it on the console screen, and then quickly goes back
without hitting the enter key. The header file conio.h has this function declaration.

Syntax:

variable_name = getche();

or

getche();

Ex:

28
getch()

• The user can give input a single character into the keyboard, but the character is not displayed on the
console screen. It then returns to its original state without requiring the user to press the enter key.

• The header file conio.h has this function declaration.

Syntax:

variable-name = getch();

or

getch();

Ex:

29
putch()

• It displays a single character that the user enters, and that character publishes where the pointer
is currently located.
• The function is defined in the header file conio.h.

Syntax:

putch(variable_1);

Ex:

30
puts()

• Its purpose is to show a collection of characters or strings that have already been saved in a character
array.

• The header file stdio.h has the declaration for this function.

Syntax:

puts(variable_1);

putchar()

One character at a time can be displayed using the putchar() function, which can be called directly by
the character to be displayed or via a variable that already contains a character. the header file stdio.h
has this function declaration.

31
MODULE 2
CONTROL STATEMENTS AND INTRODUCTION TO PROBLEM SOLVING
2.1 CONTROL STATEMENTS

Introduction:
The instructions were carried out in the majority of C programs in identical sequence that they
existed in the program. Programs of this type are incorrectly simple because they lack features like
testing conditions to see if certain conditions are true or false, repeating the execution of a set of
statements, and selectively executing each set of statements. Each instruction was only carried out
once.
The majority of useful C programs heavily utilize the aforementioned characteristics. Generally
speaking, a realistic C program could need to include:
• Branching: This statement states that a logical test will be run first, and then, based on the results,
one of several possible actions will be run.
• Selection: Another unique type of branching is termed selection, where a single group of
statements is chosen from among other groups that are available.
• Looping: A program may occasionally need to carry out a set of instructions multiple times in
order to satisfy a logical condition. We call this as looping.

Control Statements: This section covers the different ways that C can regulate how logic flows
through a program. Control statements go into one of three categories: loop or iterative statements,
unconditional and conditional branch statements.

Conditional Statements: Occasionally, we need a program to choose one course of action from
among two or more options. This necessitates departing from the standard sequential execution order
of statements. These programs have to include two or more statements that can be performed, but they
also need to have a mechanism to choose only one choice from the list each time the program is run.
We call this conditional execution.

if statement:
if statement can be used to conditionally execute a statement or collection of statements. This tests a
logical condition that could be true or false. The next statement is executed if the logical test is true
(i.e., the value is not zero). The control moves to the following executable statement if the logical
condition is false.
simple if statement syntax :
if (test expression)
{
Statement1 ; //True statement block
}
Statement2;

32
Flowchart Segment:

if – else statement:
There is only one action that the if statement can perform. The if-else statement is used when two
statements need to be processed in a different order. A two-way branching is present in the if-else
expression.
if - else statement syntax :
if (test expression)
{
Statement1; //True statement block
}
else
{
Statement2; //False statement block
}
Statement3;
The else statement is a choice, and the statement can consist of one sentence, several statements, or
nothing at all. A scalar result, such as an, floating point type, integer etc., is produced by the
conditional rule. It's crucial to keep in mind that a C if statement can only run one statement on each
branch, T or F.

If we wish more than one statement to run on a branch, we have to block them all inside of a pair of {
and } statements to create a compound statement.
The syntax indicates that a statement is executed if it exists; if not, a false statement or block of
statements is executed, and the next statement is executed if it is true.

33
Flowchart Segment

Example:

Ex:

34
NESTED IF STATEMENT
Syntax:
if(test-expression)
{
if(test-expression)
Statement1;
else
Statement2;
}
else
{
Statement3;
}
statement4;
• From the syntax, we say that if condition becomes true then statement-1block of statements are
executed.
• otherwise statement-2 block of statements are executed, otherwise statement-3 block of
statements executes.
• The following statements are finally performed if the condition is not met.
FLOWCHART SEGMENT

35
EX:

36
ELSE IF LADDER STATEMENT
Synatx:
if(test-expression1)
{
Statement1;
}
else if(test-expression2)
{
Statement2;
}
.
.
else {
Statementn;
}
Statementn+1;

Flowchart Segment

Ex:

37
SWITCH STATEMENT:
• An alternative to the if else if..ladder statement that allows a block of code to be executed
based on the selection of several options.
• The C switch statement is a multiway decision-making tool that branches based on whether a
variable or expression matches any of a variety of constant integer values.
• The "break" statement ends the switch statement's execution and leaves the switch statement..
GENERAL FORM:
switch (test-expression)
{
case value1:
block_1;
break;
case value2:
block_2;
break;
.
.
case value-n:
block_n;
break;

38
default:
default block;
break;
}
Next statement

FLOWCHART SEGMENT

EX:

39
2.2 LOOPS/Iteration and repetitive execution:
Multiple executions of a code block are required. Statements are typically executed in a sequential
fashion, starting with the first statement in a function and going through the others in turn.
Different control structures are provided by programming languages, enabling more complex
execution pathways. We can run a statement or set of statements repeatedly by using a loop

40
statement. To meet looping needs, the C programming language offers the following kinds of
loops.

For loop:
Syntax:
for(initialization; condition; re-evalauation parameter)
{
Statement-1;
Statement-2;
….
}
EX:

41
While condition
Syntax :
while(test-expression)
{
Statement1;
Statement2;
.
.
}
• This while loop checks for test-expression and executes block of statements repetitively till the
test-expression is false.
• The loop is entry controlled.
• Note: While loop does not terminate with semicolon.
Ex:

Do while Loop:
Syntax :
do
{
Statement1;
Statement2;
.
} while(test-expression);

42
Flowchart Segment

• This loop statement executes the statement or block of statements atleast once irrespective of
the condition and executes the block of statements repetitively until the test condition is true
• It is exit controlled loop
• Note: The do..while loop terminates with semicolon.
Ex:

Difference between while do while:


while() statement
• In this statement, initially test-expression is evaluated then block of statement is executed.
• It is called as entry controlled loop.
• There is no guarantee that block of statement is executed atleast once.
Do .while() statement
• Do-.While loop statement executes the statement or block of statements atleast once
irrespective of the condition and executes the block of statements repetitively until the test
condition is true

43
• It is exit controlled loop
• Note: The do..while loop terminates with semicolon.
2.3 Specifying test condition for selection and iteration
Specifying test condition in selection statements
 To carry out a single statement or a set of statements in a specific circumstance.
Ex1:
If (test-expression)
{
Statement1; //True statement block
}
Statement2;
Ex2:
If the test condition is true, to execute one set of statements; if the test condition is false, to execute a
different set of statements

if (test-expression)
{
Statement1; //True statement block
}
else
{
Statement2; //False statement block
}
statement3;
Specifying test condition in iteration statements
Ex1:while(test-expression)
{
Statement-1;
Statement-2;
.
}
2.4 goto statement:
 The goto statement in C allows you to transfer control unconditionally from one point in a
program to another.
 However, it is generally considered bad practice and is often discouraged because it can lead to
code that is difficult to understand and maintain.
 Instead, structured programming constructs like loops and conditionals are recommended for
better code organization and readability.

44
Syntax

goto label;
...
..
...
...
label:
statement;
• The label is like a name.
•The program switches to label: and begins running the code when it encounters the goto expression.

 While there are some specific use cases where goto might be appropriate (like breaking out of
nested loops), it should be used sparingly and with caution. In modern C programming, it's
generally recommended to rely on structured control flow constructs for better code
organization and maintainability.
Ex:

45
Disadvantages of Using goto Statement
• Because the goto statement complicates program logic, its use is strongly discouraged.
• It is quite challenging to follow the program's flow when goto is used.
• Program analysis and verification (especially for loop-based applications) become extremely
challenging when goto is used.
• You can simply skip using goto by utilizing the break and continue statements instead.

2.5 Special control statements


• There are situations when you want to ignore a condition, skip an iteration, or totally exit the
loop.
• Loops and specific control statements can be used for this.
• Loop control statements alter the order in which operations are carried out.

46
• All automatically created objects inside a scope are destroyed upon exiting execution.
• The following control statements are supported by C:
Break Statement
Continue Statement
Break statement
• It is used to stop the loop immediately or exit from the loop.
Syntax
break;
Ex:

Continue statement
• It is used to skip the current iteration of the loop.
• It is used to halt the current iteration and start the next one.
Syntax
continue;
Ex:

47
Nested loops:
• A loop statement inside another loop statement is referred to as a nested loop.
• For this reason, "loop inside loops" is another term for nested loops. Any number of loops
inside of another loop can be defined.
Syntax
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
• The two permissible loop types are Outer_loop and Inner_loop, which can be either a "for,"
"while," or "do-while" loop..
2.6 Nested for loop
• Any loop type created inside the 'for' loop is referred to as a nested for loop.
for (initialization; testcondition; re-evaluation parameter)
{
for(initialization; testcondition; re-evaluation parameter)
{
// inner for.
}
// outer for.
}
EX:

48
Nested while loop
• Any loop type created inside the 'while' loop is referred to as a nested while loop.
while(test-expression)
{
while(test-expression)
{
// inner while
}
// outer while.
}
EX:

49
2.6 Introduction to Problem Solving:

Problem solving is a crucial skill in various aspects of life, including programming and computer
science. Here are some general steps you can follow when approaching problem-solving, particularly
in the context of programming.
Understand the problem:
• Clearly understand the problem statement. What is the input, and what is the expected output?
• Identify any constraints or requirements.
Break down the problem:

• Divide the problem into smaller, more manageable sub-problems.


• Break it down into logical steps or components.
Plan Your Approach
• Decide on the algorithm or approach you will use to solve the problem.
• Consider different data structures and algorithms that might be suitable.

50
Write Algorithm:

• Before jumping into coding, write algorithm to outline your solution


• Pseudocode is a high-level description of the algorithm, independent of programming language
syntax.

Implement the solution

• Write the actual code based on your pseudocode


• Test each part of your code as you implement it.
Debugging:

• If there are errors or unexpected behavior, use debugging techniques to identify and fix them.
• Print statements, debugging tools, and step-through debugging can be helpful.
Test thoroughly

• Test your solution with a variety of input cases, including edge cases.
• Ensure that your program handles different scenarios correctly.
How to Develop a Program:

• Program is a set of instructions designed for solving a problem. Program writing is not all about
coding only, and it is not a random process. Therefore,the program writing is a systematic process
and it requires the following steps.
1. Analyze the problem to identify inputs,outputs and processing requirements.
2. Identify various processing steps needed to solve the problem and represent them in either in
Algorithm, Pseudocode,or Flowchart,etc.
3. Refine step2 in a way that all the processing steps are detailed enough and convenient to
represent in a programming language.
4. Add the syntax of the programming language to the above representation and it becomes the
program.
5. Type the program and compile it to remove syntax related errors.
6. Execute or Run the program and check it with different types of inputs to verify its
correctness.If the results are incorrect for any combinations of inputs,then review all processing
steps.
2.7 Algorithm
• An algorithm is defined as the finite set of clearly stated steps for providing the solution to a
problem.
• An algorithm is generally represented in English like language, and it can be quite abstractor
quite detailed.
• An algorithm should be analyzed with respect to space and time complexity i.e.,with respect to
usage of computer memory and processing time.
Example: To calculate average marks.
Algorithm:-
1. Read marks in three subjects.
51
2. Compute Average
3. Display the value of Average
Characteristics/Properties of an Algorithm:
• The steps in the algorithm should be well-organized,pre-arranged.
• The steps in the algorithm should be simple and concise.
• The steps in the algorithm should not be ambiguous.
• There must be some condition(step)for termination.
• The algorithm should be accurate and truthful in defining the solution
Advantages of Algorithm:
• The Algorithm helps in breaking down the problem solution into sequential number of steps.
• It acts as blueprint for the problem solution.
• It helps in developing the solution by using the programming language.
• It is easy to identify and remove program logical errors.
2.8 Flowchart
• A Flowchart can be defined as the pictorial/diagrammatic/visual representation of a
process,which describes the steps in the algorithm/pseudocode.
• It increases the understandability of the process.
• It displays step-by-step solutions to a problem, algorithm, or process
• There are different symbols used to indicate the operational steps of an algorithm or
Pseudocode.
Flowchart symbols

Symbol Name Symbol Representation

Start/stop

Process

Decision

Input/output

52
Symbol Name Symbol Representation

Stored data

Document

Flow

Predefined process

Connector

Ex: Algorithm to read and display a

Ex:

53
2.9 Top down design

Top-down design is a software development approach that starts with a high-level overview of a
system and progressively refines it into more detailed levels. This method is also known as stepwise
refinement or decomposition. The process involves breaking down a complex problem into simpler,
more manageable sub problems or modules.
Overview of top down design:
Start with a High-level overview:
 Begin by understanding the overall problem or system at a high level.
 Identify the major components or modules that make up the system.
Decompose into sub-modules:
• Break down each major component into smaller, more manageable sub-modules
• Continue this process until the problem is divided into small, understandable parts.
Define interfaces:
• Clearly define the interfaces between different modules. This includes specifying how modules
will communicate with each other.
Detail each submodule:

• Focus on one sub-module at a time and detail its functionality


• Define the inputs, processes, and outputs of each sub-modules.
Repeat the process:

• Apply the same top-down design process to each sub-module, breaking them down into even
smaller units.
• Continue until the modules are small enough to be easily implemented
Implementation:

54
• Start implementing the smallest units, building up to the larger modules.
• Implement each module or sub-module in a way that it adheres to the defined interfaces
Testing and Integration:

• Test each module in isolation to ensure it performs as expected.


• Gradually integrate modules and test the entire system to ensure all components work together
seamlessly
Refinement and Iteration:

• Refine the design and implementation based on testing results and feedback.
• Iteratively improve the system, if necessary, by going back to earlier steps.
For example, to perform arithmetic operations on two integers
• compute addition.
• compute subtraction.
• compute product.
• compute quotient.
Ex :
1.algorithm for first step is −
• Read two integers x,y
• compute addition= x + y
• display addition
2. algorithm for second step −
• Read two integers x,y
• compute subtraction= x - y
• display subtraction
3. algorithm for third step is −
• Read two integers x,y
• compute product= x * y
• display product
2.10 Implementation of algorithms:
Converting the algorithm into program using programming language is called implementation of
algorithms.
Ex: Algorithm for printing sum of 1 to 10 numbers.
Step1: start
Step2: Read i
Step3: while( i<=10)
Step4: if i<=10 is true,
Step4.1: computes sum=sum+I;
Step4.2: computes i=i+1
Step5: if i<=10 is false,
Step5.1: it exits from the while loop
Step6: stop

55
• Implementing above program

2.11 program verification:


• An efficient program is worthless if it breaks or produces a wrong answer.
• Program verification is the process of checking whether program give correct output or not.
• If program output is wrong then check for logical errors.
• Check program output for different inputs.
• Program testing involves checking of syntax errors and semantic errors.
• Syntax errors are mistakes that happen when you write C syntax incorrectly.
• Another phrase for "logic error" is "semantic error," which refers to actually writing the incorrect
code.
Efficiency of algorithms
• Since computer resources are scarce, they must be used effectively.
• The quantity of computational resources an algorithm uses determines its efficiency.
• To find out how much resource an algorithm uses, analysis is required.
Method for determining Efficiency
• An algorithm's effectiveness is determined by how well it manages memory and time.
• An algorithm's time efficiency is determined by a number of parameters.
• Write a program for a predefined algorithm, for instance, run it in any programming language,
and note how long it takes to complete.
• There are several elements that could influence the execution time that you measure in this
situation, including:
1. The machine's speed
2. Compiler and additional systems Software instruments
3. The System Operations
4. Used programming language
5. Amount of data needed

56
UNIT-III ARRAYS AND STRINGS

Contents

Single and Multidimensional Arrays: Array Declaration and Initialization of arrays – Arrays as
function arguments. Strings: Initialization and String handling functions. Structure and Union:
Definition and Declaration - Nested Structures, Array of Structures, Structure as function
arguments, Function that return structure – Union.

ARRAYS
Introduction:
So far we have used only single variable name for storing one data item. If we need to store
multiple copies of the same data then it is very difficult for the user. To overcome the difficulty a
new data structure is used called arrays.
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of elements are stored
contiguously in the memory under one variable name.
An array can be declared of any standard or custom data type.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100
variables named as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C
programming arrays is introduced in C which gives the capability to store the 100 roll numbers
in the contiguous memory which has 100 blocks and which can be accessed by single variable
name.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays

The above array is declared as int a [5];


a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;
In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.
Index or Subscript Variable:
1. Individual data items can be accessed by the name of the array and an integer enclosed
in square bracket called subscript variable / index
2. Subscript Variables helps us to identify the item number to be accessed in the contiguous
memory.
What is Contiguous Memory?
1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.
3. Suppose inside memory we have reserved 1000-1200 memory addresses for special
purposes then we can say that these 200 blocks are going to reserve contiguous memory.
Contiguous Memory Allocation
1. Two registers are used while implementing the contiguous memory scheme. These
registers are base register and limit register.
2. When OS is executing a process inside the main memory then content of each register
are as

Register Content of register

Base register Starting address of the memory location where


process execution is happening

Limit register Total amount of memory in bytes consumed by


process

Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non-
contiguous allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address
from base register and then it will refer relative address of memory location with respect to
base address.
How to allocate contiguous memory?
1. Using static array declaration.
2. Using alloc ( ) / malloc ( ) function to allocate big chunk of memory dynamically.
Array Terminologies:
Size: Number of elements or capacity to store elements in an array. It is always mentioned in
square brackets [ ].
Type: Refers to data type. It decides which type of element is stored in the array. It is also
instructing the compiler to reserve memory according to the data type.
Base: The address of the first element is a base address. The array name itself stores address
of the first element.
Index: The array name is used to refer to the array element. For example num[x], num is array
and x is index. The value of x begins from 0.The index value is always an integer value.
Range: Value of index of an array varies from lower bound to upper bound. For example in
num[100] the range of index is 0 to 99.
Word: It indicates the space required for an element. In each memory location, computer can
store a data piece. The space occupation varies from machine to machine. If the size of element
is more than word (one byte) then it occupies two successive memory locations. The variables
of data type int, float, long need more than one byte in memory.
Characteristics of an array:
1. The declaration int a [5] is nothing but creation of five variables of integer types in
memory instead of declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from one
another with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the
other elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or
array variable of its type.
6. Array elements are stored in contiguous memory locations.
Array Declaration:
Array has to be declared before using it in C Program. Array is nothing but the collection of
elements of similar data types.
Syntax: <data type> array name [size1][size2].....[sizen];

Syntax Parameter Significance

Data type Data Type of Each Element of the array

Array name Valid variable name


Size Dimensions of the Array
Array declaration requirements
Requirement Explanation
Data Type specifies the type of the array. We can compute the size
Data Type
required for storing the single cell of array.

Valid identifier is any valid variable or name given to the array.


Valid Identifier
Using this identifier name array can be accessed.

Size of Array It is maximum size that array can have.


What does Array Declaration tell to Compiler?
1. Type of the Array
2. Name of the Array
3. Number of Dimension
4. Number of Elements in Each Dimension

Types of Array
1. Single Dimensional Array / One Dimensional Array
2. Multi Dimensional Array

Single / One Dimensional Array:


1. Single or One Dimensional array is used to represent and store data in a linear form.
2. Array having only one subscript variable is called One-Dimensional array
3. It is also called as Single Dimensional Array or Linear Array
Single Dimensional Array Declaration and initialization:
Syntax for declaration: <data type> <array name> [size];
Examples for declaration: int iarr[3]; char carr[20]; float farr[3];
Syntax for initialization: <data type> <array name> [size] = {val1, val2, …, valn};
Examples for initialization:
int iarr[3] = {2, 3, 4};
char carr[20] = “program”;
float farr[3] = {12.5, 13.5, 14.5};
Different Methods of Initializing 1-D Array
Whenever we declare an array, we initialize that array directly at compile time.
Initializing 1-D Array is called as compiler time initialization if and only if we assign certain set of
values to array element before executing program. i.e. at compilation time.

Here we are learning the different ways of compile time initialization of an array.
Ways of Array Initializing 1-D Array:
1. Size is Specified Directly
2. Size is Specified Indirectly
Method 1: Array Size Specified Directly
In this method, we try to specify the Array Size directly.
int num [5] = {2,8,7,6,0};
In the above example we have specified the size of array as 5 directly in the initialization
statement. Compiler will assign the set of values to particular element of the array.
num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;
As at the time of compilation all the elements are at specified position So This initialization
scheme is Called as “Compile Time Initialization“.
Graphical Representation:

Method 2: Size Specified Indirectly


In this scheme of compile time Initialization, We do not provide size to an array but instead we
provide set of values to the array.
int num[ ] = {2,8,7,6,0};
Explanation:
1. Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines
the Size of An Array.
2. After counting the number of elements inside the braces, The size of array is considered
as 5 during complete execution.
3. This type of Initialization Scheme is also Called as “Compile Time Initialization“
Example Program
#include <stdio.h>
int main()
int num[] = {2,8,7,6,0};
int i;
for (i=0;i<5;i++) {
printf(“\n Array Element num [%d] = %d”,i, num[i]); }
return 0; }
Output:
Array Element num[0] = 2
Array Element num[1] = 8
Array Element num[2] = 7
Array Element num[3] = 6
Array Element num[4] = 0

Accessing Array
1. We all know that array elements are randomly accessed using the subscript variable.
2. Array can be accessed using array-name and subscript variable written inside pair of
square brackets [ ].
Consider the below example of an array

In this example we will be accessing array like this


arr[3] = Forth Element of Array
arr[5] = Sixth Element of Array
whereas elements are assigned to an array using below way
arr[0] = 51; arr[1] = 32; arr[2] = 43; arr[3] = 24; arr[4] = 5; arr[5] =26;
Example Program1: Accessing array
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\nElement at arr[%d] is %d",i,arr[i]);
}
getch();
}
Output:
Element at arr[0] is 51
Element at arr[1] is 32
Element at arr[2] is 43
Element at arr[3] is 24
Element at arr[4] is 5
Element at arr[5] is 26
How a[i] Works?
We have following array which is declared like int arr[] = { 51,32,43,24,5,26};
As we have elements in an array, so we have track of base address of an array. Below things
are important to access an array.

Expression Description Example

arr It returns the base address of an array Consider 2000

*arr It gives zeroth element of an array 51


Expression Description Example

*(arr+0) It also gives zeroth element of an array 51

*(arr+1) It gives first element of an array 32

So whenever we tried accessing array using arr[i] then it returns an element at the location*(arr
+ i)
Accessing array a[i] means retrieving element from address (a + i).
Example Program2: Accessing array
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]);
}
getch();
}
Output:
51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
5 5 5 5
26 26 26 26
Operations with One Dimensional Array
1. Deletion – Involves deleting specified elements form an array.
2. Insertion – Used to insert an element at a specified position in an array.
3. Searching – An array element can be searched. The process of seeking specific
elements in an array is called searching.
4. Merging – The elements of two arrays are merged into a single one.
5. Sorting – Arranging elements in a specific order either in ascending or in descending
order.
Example Programs:
1. C Program for deletion of an element from the specified location
from an Array
#include<stdio.h>
int main() {
int arr[30], num, i, loc;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Read elements in an array
printf("\nEnter %d elements :", num);
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
//Read the location
printf("\nLocation of the element to be deleted :");
scanf("%d", &loc);
/* loop for the deletion */
while (loc < num) {
arr[loc - 1] = arr[loc];
loc++; }
num--; // No of elements reduced by 1
//Print Array
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5
Enter 5 elements: 3 4 1 7 8
Location of the element to be deleted: 3
3 4 7 8
2. C Program to delete duplicate elements from an array
int main() {
int arr[20], i, j, k, size;
printf("\nEnter array size: ");
scanf("%d", &size);
printf("\nAccept Numbers: ");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("\nArray with Unique list: ");
for (i = 0; i < size; i++) {
for (j = i + 1; j < size;) {
if (arr[j] == arr[i]) {
for (k = j; k < size; k++) {
arr[k] = arr[k + 1]; }
size--; }
else
j++; }
}
for (i = 0; i < size; i++) {
printf("%d ", arr[i]); }
return (0);
}
Output:
Enter array size: 5
Accept Numbers: 1 3 4 5 3
Array with Unique list: 1 3 4 5
3. C Program to insert an element in an array
#include<stdio.h>
int main() {
int arr[30], element, num, i, location;
printf("\nEnter no of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
printf("\nEnter the element to be inserted:");
scanf("%d", &element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified location
for (i = num; i >= location; i--) {
arr[i] = arr[i - 1]; }
num++;
arr[location - 1] = element;
//Print out the result of insertion
for (i = 0; i < num; i++)
printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5
1 2 3 4 5
Enter the element to be inserted: 6
Enter the location: 2
1 6 2 3 4 5
4. C Program to search an element in an array
#include<stdio.h>
int main() {
int a[30], ele, num, i;
printf("\nEnter no of elements:");
scanf("%d", &num);
printf("\nEnter the values :");
for (i = 0; i < num; i++) {
scanf("%d", &a[i]); }
//Read the element to be searched
printf("\nEnter the elements to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;
while (i < num && ele != a[i]) {
i++; }
//If i < num then Match found
if (i < num) {
printf("Number found at the location = %d", i + 1);
}
else {
printf("Number not found"); }
return (0);
}
Output:
Enter no of elements: 5
11 22 33 44 55
Enter the elements to be searched: 44
Number found at the location = 4
5. C Program to copy all elements of an array into another array
#include<stdio.h>
int main() {
int arr1[30], arr2[30], i, num;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Accepting values into Array
printf("\nEnter the values:");
for (i = 0; i < num; i++) {
scanf("%d", &arr1[i]); }
/* Copying data from array 'a' to array 'b */
for (i = 0; i < num; i++) {
arr2[i] = arr1[i]; }
//Printing of all elements of array
printf("The copied array is:");
for (i = 0; i < num; i++)
printf("\narr2[%d] = %d", i, arr2[i]);
return (0);
}
Output:
Enter no of elements: 5
Enter the values: 11 22 33 44 55
The copied array is: 11 22 33 44 55
6. C program to merge two arrays in C Programming
#include<stdio.h>
int main() {
int arr1[30], arr2[30], res[60];
int i, j, k, n1, n2;
printf("\nEnter no of elements in 1st array:");
scanf("%d", &n1);
for (i = 0; i < n1; i++) {
scanf("%d", &arr1[i]); }
printf("\nEnter no of elements in 2nd array:");
scanf("%d", &n2);
for (i = 0; i < n2; i++) {
scanf("%d", &arr2[i]); }
i = 0;
j = 0;
k = 0;
// Merging starts
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
res[k] = arr1[i];
i++;
k++; }
else {
res[k] = arr2[j];
k++;
j++; }
}
/*Some elements in array 'arr1' are still remaining where as the array
'arr2' is exhausted*/
while (i < n1) {
res[k] = arr1[i];
i++;
k++; }
/*Some elements in array 'arr2' are still remaining where as the array
'arr1' is exhausted */
while (j < n2) {
res[k] = arr2[j];
k++;
j++; }
//Displaying elements of array 'res'
printf("\nMerged array is:");
for (i = 0; i < n1 + n2; i++)
printf("%d ", res[i]);
return (0);
}
Enter no of elements in 1st array: 4
11 22 33 44
Enter no of elements in 2nd array: 3
10 40 80
Merged array is: 10 11 22 33 40 44 80

Programs for Practice


1 C Program to display array elements with addresses
2 C Program for Reading and printing Array Elements
3 C Program to calculate Addition of All Elements in Array
4 C Program to find Smallest Element in Array
5 C Program to find Largest Element in Array
6 C Program to reversing an Array Elements

1. C Program to display array elements with addresses


#include<stdio.h>
#include<stdlib.h>
#define size 10
int main() {
int a[3] = { 11, 22, 33 };
printf("\n a[0],value=%d : address=%u", a[0], &a[0]);
printf("\n a[1],value=%d : address=%u", a[1], &a[1]);
printf("\n a[2],value=%d : address=%u", a[2], &a[2]);
return (0);
}
Output:
a[0],value=11 : address=2358832
a[1],value=22 : address=2358836
a[2],value=33 : address=2358840
2. C Program for Reading and printing Array Elements
#include<stdio.h>
int main()
{
int i, arr[50], num;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Reading values into Array
printf("\nEnter the values :");
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
//Printing of all elements of array
for (i = 0; i < num; i++) {
printf("\narr[%d] = %d", i, arr[i]); }
return (0);
}
Output:
Enter no of elements : 5
Enter the values : 10 20 30 40 50
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50
3. C Program to calculate addition of all elements in an array
#include<stdio.h>
int main() {
int i, arr[50], sum, num;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Reading values into Array
printf("\nEnter the values :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
//Computation of total
sum = 0;
for (i = 0; i < num; i++)
sum = sum + arr[i];
//Printing of all elements of array
for (i = 0; i < num; i++)
printf("\na[%d]=%d", i, arr[i]);
//Printing of total
printf("\nSum=%d", sum);
return (0);
}
Output:
Enter no of elements : 3
Enter the values : 11 22 33
a[0]=11
a[1]=22
a[2]=33
Sum=66
4. C Program to find smallest element in an array
#include<stdio.h>
int main() {
int a[30], i, num, smallest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Consider first element as smallest
smallest = a[0];
for (i = 0; i < num; i++) {
if (a[i] < smallest) {
smallest = a[i]; } }
// Print out the Result
printf("\nSmallest Element : %d", smallest);
return (0);
}
Output:
Enter no of elements : 5
11 44 22 55 99
Smallest Element : 11
5. C Program to find largest element in an array
#include<stdio.h>
int main() {
int a[30], i, num, largest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Consider first element as largest
largest = a[0];
for (i = 0; i < num; i++) {
if (a[i] > largest) {
largest = a[i]; } }
// Print out the Result
printf("\nLargest Element : %d", largest);
return (0);
}
Output:
Enter no of elements : 5
11 55 33 77 22
Largest Element : 77
6. C Program to reverse an array elements in an array
#include<stdio.h>
int main() {
int arr[30], i, j, num, temp;
printf("\nEnter no of elements : ");
scanf("%d", &num);
//Read elements in an array
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
j = i - 1; // j will Point to last Element
i = 0; // i will be pointing to first element
while (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++; // increment i
j--; // decrement j
}
//Print out the Result of Insertion
printf("\nResult after reversal : ");
for (i = 0; i < num; i++) {
printf("%d \t", arr[i]); }
return (0);
}
Output:
Enter no of elements : 5
11 22 33 44 55
Result after reversal : 55 44 33 22 11

Multi Dimensional Array:


1. Array having more than one subscript variable is called Multi-Dimensional array.
2. Multi Dimensional Array is also called as Matrix.
Syntax: <data type> <array name> [row subscript][column subscript];

Example: Two Dimensional Arrays


Declaration: Char name[50][20];
Initialization:
int a[3][3] = { 1, 2, 3
5, 6, 7
8, 9, 0};
In the above example we are declaring 2D array which has 2 dimensions. First dimension will
refer the row and 2nd dimension will refer the column.
Example: Three Dimensional Arrays
Declaration: Char name[80][20][40];
The following information are given by the compiler after the declaration

Array Dimension No. of Elements in


Example Type
Name No. Each Dimension

1 integer roll 1 10

2 character name 2 80 and 20

3 character name 3 80 and 20 and 40

Two Dimensional Arrays:


1. Two Dimensional Array requires Two Subscript Variables
2. Two Dimensional Array stores the values in the form of matrix.
3. One Subscript Variable denotes the “Row” of a matrix.
4. Another Subscript Variable denotes the “Column” of a matrix.

Declaration and use of 2D Arrays:


int a[3][4];
for(i=0;i<row,i++)
for(j=0;j<col,j++) {
printf("%d",a[i][j]); }
Meaning of Two Dimensional Arrays:
1. Matrix is having 3 rows ( i takes value from 0 to 2 )
2. Matrix is having 4 Columns ( j takes value from 0 to 3 )
3. Above Matrix 3×4 matrix will have 12 blocks having 3 rows & 4 columns.
4. Name of 2-D array is „a„ and each block is identified by the row & column number.
5. Row number and Column Number Starts from 0.
Two-Dimensional Arrays: Summary with Sample Example:

Summary Point Explanation

No of Subscript Variables Required 2

Declaration a[3][4]

No of Rows 3

No of Columns 4

No of Cells 12

No of for loops required to iterate 2

Memory Representation:
1. 2-D arrays are stored in contiguous memory location row wise.
2. 3 X 3 Array is shown below in the first Diagram.
3. Consider 3×3 Array is stored in Contiguous memory location which starts from 4000.
4. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next
memory location i.e. Elements stored row-wise
5. After Elements of First Row are stored in appropriate memory locations, elements of
next row get their corresponding memory locations.
6. This is integer array so each element requires 2 bytes of memory.
Basic Memory Address Calculation:
a[0][1] = a[0][0] + Size of Data Type

Element Memory Location

a[0][0] 4000

a[0][1] 4002

a[0][2] 4004

a[1][0] 4006

a[1][1] 4008

a[1][2] 4010

a[2][0] 4012

a[2][1] 4014

a[2][2] 4016
Initializing 2D Array

Method 1: Initializing all Elements row wise


For initializing 2D Array we need to assign values to each element of an array using the below
syntax.
int a[3][2] = { {1, 4}, {5, 2}, {6, 5} };
Example Program
#include<stdio.h>
int main()
{
int i, j;
int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 } };
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]); }
printf("\n"); }
return 0;
}
Output:
1 4
5 2
6 5
We have declared an array of size 3 X 2, it contains overall 6
elements.
Row 1: {1, 4},
Row 2: {5, 2},
Row 3: {6, 5}
We have initialized each row independently
a[0][0] = 1
a[0][1] = 4
Method 2: Combine and Initializing 2D Array
Initialize all Array elements but initialization is much straight forward. All values are assigned
sequentially and row-wise
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
Example Program:
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]); }
printf("\n"); }
return 0;
}
Output:
1 4
5 2
6 5
Method 3: Some Elements could be initialized
int a[3][2] = { { 1 }, { 5 , 2 }, { 6 } };
Now we have again going with the way 1 but we are removing some of the elements from the
array. Uninitialized elements will get default 0 value. In this case we have declared and
initialized 2-D array like this
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1 }, { 5, 2 }, { 6 }};
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]); }
printf("\n"); }
return 0;
}
Output:
1 0
5 2
6 0
Accessing 2D Array Elements:
1. To access every 2D array we requires 2 Subscript variables.
2. i – Refers the Row number
3. j – Refers Column Number
4. a[1][0] refers element belonging to first row and zeroth column
Example Program: Accept & Print 2×2 Matrix from user
#include<stdio.h>
int main() {
int i, j, a[3][3];
// i : For Counting Rows
// j : For Counting Columns
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("\nEnter the a[%d][%d] = ", i, j);
scanf("%d", &a[i][j]); } }
//Print array elements
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d\t", a[i][j]); }
printf("\n"); }
return (0);
}
How it Works?
1. For Every value of row Subscript , the column Subscript incremented from 0 to n-1
columns
2. i.e. For Zeroth row it will accept zeroth, first, second column (a[0][0], a[0][1], a[0][2])
elements
3. In Next Iteration Row number will be incremented by 1 and the column number again
initialized to 0.
4. Accessing 2-D Array: a[i][j]  Element From ith Row and jth Column

Example programs for practice:


1. C Program for addition of two matrices
2. C Program to find inverse of 3 X # Matrix
3. C Program to Multiply two 3 X 3 Matrices
4. C Program to check whether matrix is magic square or not?

1. C Program for addition of two matrices


#include<stdio.h>
int main() {
int i, j, mat1[10][10], mat2[10][10], mat3[10][10];
int row1, col1, row2, col2;
printf("\nEnter the number of Rows of Mat1 : ");
scanf("%d", &row1);
printf("\nEnter the number of Cols of Mat1 : ");
scanf("%d", &col1);
printf("\nEnter the number of Rows of Mat2 : ");
scanf("%d", &row2);
printf("\nEnter the number of Columns of Mat2 : ");
scanf("%d", &col2);
/* before accepting the Elements Check if no of rows and columns of
both matrices is equal */
if (row1 != row2 || col1 != col2) {
printf("\nOrder of two matrices is not same ");
exit(0); }
//Accept the Elements in Matrix 1
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf("Enter the Element a[%d][%d] : ", i, j);
scanf("%d", &mat1[i][j]); } }
//Accept the Elements in Matrix 2
for (i = 0; i < row2; i++)
for (j = 0; j < col2; j++) {
printf("Enter the Element b[%d][%d] : ", i, j);
scanf("%d", &mat2[i][j]); }
//Addition of two matrices
for (i = 0; i < row1; i++)
for (j = 0; j < col1; j++) {
mat3[i][j] = mat1[i][j] + mat2[i][j];}
//Print out the Resultant Matrix
printf("\nThe Addition of two Matrices is : \n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf("%d\t", mat3[i][j]); }
printf("\n"); }
return (0);
}
Output:
Enter the number of Rows of Mat1 : 3
Enter the number of Columns of Mat1 : 3
Enter the number of Rows of Mat2 : 3
Enter the number of Columns of Mat2 : 3
Enter the Element a[0][0] : 1
Enter the Element a[0][1] : 2
Enter the Element a[0][2] : 3
Enter the Element a[1][0] : 2
Enter the Element a[1][1] : 1
Enter the Element a[1][2] : 1
Enter the Element a[2][0] : 1
Enter the Element a[2][1] : 2
Enter the Element a[2][2] : 1
Enter the Element b[0][0] : 1
Enter the Element b[0][1] : 2
Enter the Element b[0][2] : 3
Enter the Element b[1][0] : 2
Enter the Element b[1][1] : 1
Enter the Element b[1][2] : 1
Enter the Element b[2][0] : 1
Enter the Element b[2][1] : 2
Enter the Element b[2][2] : 1
The Addition of two Matrices is :
2 4 6
4 2 2
2 4 2
2. C Program to find inverse of 3 X 3 Matrix
#include<stdio.h>
void reduction(float a[][6], int size, int pivot, int col) {
int i, j;
float factor;
factor = a[pivot][col];
for (i = 0; i < 2 * size; i++) {
a[pivot][i] /= factor; }
for (i = 0; i < size; i++) {
if (i != pivot) {
factor = a[i][col];
for (j = 0; j < 2 * size; j++) {
a[i][j] = a[i][j] - a[pivot][j] * factor; } } } }
void main() {
float matrix[3][6];
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 6; j++) {
if (j == i + 3) {
matrix[i][j] = 1;}
else {
matrix[i][j] = 0; } } }
printf("\nEnter a 3 X 3 Matrix :");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%f", &matrix[i][j]); } }
for (i = 0; i < 3; i++) {
reduction(matrix, 3, i, i); }
printf("\nInverse Matrix");
for (i = 0; i < 3; i++) {
printf("\n");
for (j = 0; j < 3; j++) {
printf("%8.3f", matrix[i][j + 3]); } } }
Output:
Enter a 3 X 3 Matrix
1 3 1
1 1 2
2 3 4
Inverse Matrix
2.000 9.000 -5.000
0.000 -2.000 1.000
-1.000 -3.000 2.000
3. C Program to Multiply two 3 X 3 Matrices
#include<stdio.h>
int main() {
int a[10][10], b[10][10], c[10][10], i, j, k;
int sum = 0;
printf("\nEnter First Matrix : ");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &a[i][j]); } }
printf("\nEnter Second Matrix :");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &b[i][j]); } }
printf("The First Matrix is : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", a[i][j]); }
printf("\n"); }
printf("The Second Matrix is : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", b[i][j]); }
printf("\n"); }
//Multiplication Logic
for (i = 0; i <= 2; i++) {
for (j = 0; j <= 2; j++) {
sum = 0;
for (k = 0; k <= 2; k++) {
sum = sum + a[i][k] * b[k][j]; }
c[i][j] = sum; } }
printf("\nMultiplication Of Two Matrices : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", c[i][j]); }
printf("\n"); }
return (0);
}
Output:
Enter First Matrix :
1 1 1
1 1 1
1 1 1
Enter Second Matrix :
2 2 2
2 2 2
2 2 2
The First Matrix is :
1 1 1
1 1 1
1 1 1
The Second Matrix is :
2 2 2
2 2 2
2 2 2
Multiplication Of Two Matrices :
6 6 6
6 6 6
6 6 6
Multiplication is possible if and only if
i. No. of Columns of Matrix 1 = No of Columns of Matrix 2
ii. Resultant Matrix will be of Dimension – c [No. of Rows of Mat1][No. of Columns of Mat2]
4. C Program to check whether matrix is magic square or not?
What is Magic Square?
1. A magic square is a simple mathematical game developed during the
1500.
2. Square is divided into equal number of rows and columns.
3. Start filling each square with the number from 1 to num ( where
num = No of Rows X No of Columns )
4. You can only use a number once.
5. Fill each square so that the sum of each row is the same as the
sum of each column.
6. In the example shown here, the sum of each row is 15, and the sum
of each column is also 15.
7. In this Example: The numbers from 1 through 9 is used only once.
This is called a magic square.
#include<stdio.h>
#include<conio.h>
int main() {
int size = 3;
int matrix[3][3]; // = {{4,9,2},{3,5,7},{8,1,6}};
int row, column = 0;
int sum, sum1, sum2;
int flag = 0;
printf("\nEnter matrix : ");
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++)
scanf("%d", &matrix[row][column]); }
printf("Entered matrix is : \n");
for (row = 0; row < size; row++) {
printf("\n");
for (column = 0; column < size; column++) {
printf("\t%d", matrix[row][column]); } }
//For diagonal elements
sum = 0;
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++) {
if (row == column)
sum = sum + matrix[row][column]; } }
//For Rows
for (row = 0; row < size; row++) {
sum1 = 0;
for (column = 0; column < size; column++) {
sum1 = sum1 + matrix[row][column]; }
if (sum == sum1)
flag = 1;
else {
flag = 0;
break; } }
//For Columns
for (row = 0; row < size; row++) {
sum2 = 0;
for (column = 0; column < size; column++) {
sum2 = sum2 + matrix[column][row]; }
if (sum == sum2)
flag = 1;
else {
flag = 0;
break; } }
if (flag == 1)
printf("\nMagic square");
else
printf("\nNo Magic square");
return 0;
}
Output:
Enter matrix : 4 9 2 3 5 7 8 1 6
Entered matrix is :
4 9 2
3 5 7
8 1 6
Magic square
Sum of Row1 = Sum of Row2 [Sum of All Rows must be same]
Sum of Col1 = Sum of Col2 [Sum of All Cols must be same]
Sum of Left Diagonal = Sum of Right Diagonal

Limitations of Arrays:
Array is very useful which stores multiple data under single name with same data type.
Following are some listed limitations of Array in C Programming.
A. Static Data
1. Array is Static data Structure
2. Memory Allocated during Compile time.
3. Once Memory is allocated at Compile Time it cannot be changed during Run-time

B. Can hold data belonging to same Data types


1. Elements belonging to different data types cannot be stored in array because array data
structure can hold data belonging to same data type.
2. Example : Character and Integer values can be stored inside separate array but cannot
be stored in single array
C. Inserting data in an array is difficult
1. Inserting element is very difficult because before inserting element in an array we have
to create empty space by shifting other elements one position ahead.
2. This operation is faster if the array size is smaller, but same operation will be more and
more time consuming and non-efficient in case of array with large size.
D. Deletion Operation is difficult
1. Deletion is not easy because the elements are stored in contiguous memory location.
2. Like insertion operation , we have to delete element from the array and after deletion
empty space will be created and thus we need to fill the space by moving elements up in
the array.
E. Bound Checking
1. If we specify the size of array as „N‟ then we can access elements up to „N-1‟ but in C if
we try to access elements after „N-1‟ i.e. Nth element or N+1th element then we does not
get any error message.
2. Process of checking the extreme limit of array is called Bound Checking and C does not
perform Bound Checking.
3. If the array range exceeds then we will get garbage value as result.
F. Shortage of Memory
1. Array is Static data structure. Memory can be allocated at compile time only Thus if after
executing program we need more space for storing additional information then we cannot
allocate additional space at run time.
2. Shortage of Memory , if we don‟t know the size of memory in advance
G. Wastage of Memory
1. Wastage of Memory, if array of large size is defined

Applications of Arrays:
Array is used for different verities of applications. Array is used to store the data or values of
same data type. Below are the some of the applications of array –
A. Stores Elements of Same Data Type
Array is used to store the number of elements belonging to same data type.
int arr[30];
Above array is used to store the integer numbers in an array.
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Similarly if we declare the character array then it can hold only character. So in short character
array can store character variables while floating array stores only floating numbers.
B. Array Used for maintaining multiple variable names using single name
Suppose we need to store 5 roll numbers of students then without declaration of array we need
to declare following –
int roll1, roll2, roll3, roll4, roll5;
1. Now in order to get roll number of first student we need to access roll1.
2. Guess if we need to store roll numbers of 100 students then what will be the procedure.
3. Maintaining all the variables and remembering all these things is very difficult.
Consider the Array int roll[5]; Here we are using array which can store multiple values and we
have to remember just single variable name.
C. Array can be used for Sorting Elements
We can store elements to be sorted in an array and then by using different sorting technique we
can sort the elements.
Different Sorting Techniques are:
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Bucket Sort
D. Array can perform Matrix Operation
Matrix operations can be performed using the array. We can use 2-D array to store the matrix.
Matrix can be multi dimensional.
E. Array can be used in CPU Scheduling
CPU Scheduling is generally managed by Queue. Queue can be managed and implemented
using the array. Array may be allocated dynamically i.e at run time. [Animation will Explain more
about Round Robin Scheduling Algorithm | Video Animation]
F. Array can be used in Recursive Function
When the function calls another function or the same function again then the current values are
stores onto the stack and those values will be retrieving when control comes back. This is
similar operation like stack.

Arrays as Function arguments:


Passing array to function:
Array can be passed to function by two ways:
1. Pass Entire array
2. Pass Array element by element
1. Pass Entire array
Here entire array can be passed as a argument to function.
Function gets complete access to the original array.
While passing entire array address of first element is passed to function, any changes made
inside function, directly affects the Original value.
Function Passing method : “Pass by Address“
2. Pass Array element by element
Here individual elements are passed to function as argument.
Duplicate carbon copy of Original variable is passed to function.
So any changes made inside function do not affect the original value.
Function doesn‟t get complete access to the original array element.
Function passing method is “Pass by Value“
Passing entire array to function:
Parameter Passing Scheme : Pass by Reference
Pass name of array as function parameter.
Name contains the base address i.e. ( Address of 0th element )
Array values are updated in function.
Values are reflected inside main function also.
Example Program #1:
#include<stdio.h>
#include<conio.h>
void fun(int arr[ ])
{
int i;
for(i=0;i< 5;i++)
arr[i] = arr[i] + 10;
}
void main( )
{
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
printf("\nPassing entire array .....");
fun(arr); // Pass only name of array
for(i=0;i< 5;i++)
printf("\nAfter Function call a[%d] : %d",i,arr[i]);
getch();
}
Output :
Enter the array elements : 1 2 3 4 5
Passing entire array .....
After Function call a[0] : 11
After Function call a[1] : 12
After Function call a[2] : 13
After Function call a[3] : 14
After Function call a[4] : 15
Passing Entire 1-D Array to Function in C Programming:
Array is passed to function completely.
Parameter Passing Method : Pass by Reference
It is Also Called “Pass by Address“
Original Copy is Passed to Function
Function Body can modify Original Value.
Example Program #2:
#include<stdio.h>
#include<conio.h>
void modify(int b[3]);
void main()
{
int arr[3] = {1,2,3};
modify(arr);
for(i=0;i<3;i++)
printf("%d",arr[i]);
getch();
}
void modify(int a[3])
{
int i;
for(i=0;i<3;i++)
a[i] = a[i]*a[i];
}
Output:
1 4 9
Here “arr” is same as “a” because Base Address of Array “arr” is stored in Array “a”
Alternate Way of Writing Function Header:
void modify(int a[3]) OR void modify(int *a)
Passing Entire 2D Array to Function in C Programming:
Example Program #3:
#include<stdio.h>
void Function(int c[2][2]);
int main(){
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]); }
Function(c); /* passing multi-dimensional array to function */
return 0;
}
void Function(int c[2][2])
{
/* Instead to above line, void Function(int c[][2]) is also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);
}
Output:
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Passing array element by element to function:
1. Individual element is passed to function using Pass By Value parameter passing scheme
2. An original Array element remains same as Actual Element is never passed to Function.
Thus function body cannot modify Original Value.
3. Suppose we have declared an array „arr[5]‟ then its individual elements are
arr[0],arr[1]…arr[4]. Thus we need 5 function calls to pass complete array to a function.
Consider an array int arr[5] = {11, 22, 33, 44, 55};

Iteration Element Passed to Function Value of Element


1 arr[0] 11
2 arr[1] 22
3 arr[2] 33
4 arr[3] 44
5 arr[4] 55

Example Program #1:


#include< stdio.h>
#include< conio.h>
void fun(int num)
{
printf("\nElement : %d",num);
}
void main() {
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
printf("\nPassing array element by element.....");
for(i=0;i< 5;i++)
fun(arr[i]);
getch();
}
Output:
Enter the array elements : 1 2 3 4 5
Passing array element by element.....
Element : 1
Element : 2
Element : 3
Element : 4
Element : 5
Disadvantage of this Scheme:
1. This type of scheme in which we are calling the function again and again but with
different array element is too much time consuming. In this scheme we need to call
function by pushing the current status into the system stack.
2. It is better to pass complete array to the function so that we can save some system time
required for pushing and popping.
3. We can also pass the address of the individual array element to function so that function
can modify the original copy of the parameter directly.
Example Program #2: Passing 1-D Array Element by Element to function
#include<stdio.h>
void show(int b);
void main() {
int arr[3] = {1,2,3};
int i;
for(i=0;i<3;i++)
show(arr[i]);
}
void show(int x)
{
printf("%d ",x);
}
Output:
1 2 3

STRINGS

A string is a sequence of character enclosed with in double quotes (“ ”) but ends with
\0. The compiler puts \0 at the end of string to specify the end of the string.
To get a value of string variable we can use the two different types of formats.
Using scanf() function as: scanf(“%s”, string variable);

Using gets() function as : gets(string variable);

STRING HANDLING FUNCTIONS

C library supports a large number of string handling functions. Those functions are stored under
the header file string.h in the program.

Let us see about some of the string handling functions.


(i) strlen() function
strlen() is used to return the length of the string , that means counts the number
of characters present in a string.
Syntax
integer variable = strlen (string variable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
int strlength;
clrscr();
printf(‚Enter String:‛);
gets(str);
strlength=strlen(str);
printf(‚Given String Length Is: %d‛, strlength);
getch();
}
Output:
Enter String
Welcome
Given String Length Is:7

(ii) strcat() function


The strcat() is used to concatenate two strings. The second string will be appended to
the end of the first string. This process is called concatenation.

Syntax
strcat (StringVariable1, StringVariable 2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
printf(‚ Concatenation String is:%s‛, strcat(str1,str2));
getch();
}
Output:
Enter First String
Good
Enter Second String
Morning
Concatenation String is: GoodMorning
(iii) strcmp() function
strcmp() function is used to compare two strings. strcmp() function does a case
sensitive comparison between two strings. The two strings are compared character by
character until there is a mismatch or end of one of the strings is reached (whichever occurs
first). If the two strings are identical, strcmp( ) returns a value zero. If they‟re not, it returns the
numeric difference between the ASCII values of the first non-matching pairs of characters.

Syntax
strcmp(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmp(str1,str2);
printf(‚ Compare String Result is:%d‛,res);
getch();
}
Output:
Enter First String
Good
Enter Second String
Good
Compare String Result is: 0

(iv) strcmpi() function

strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.

Syntax
strcmpi(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmpi(str1,str2);
printf(‚ Compare String Result is:%d‛,res);
getch();
}
Output:
Enter First String
WELCOME
Enter Second String
welcome
Compare String Result is: 0
(v) strcpy() function:

strcpy() function is used to copy one string to another. strcpy() function copy the contents of
second string to first string.

Syntax
strcpy(StringVariable1, StringVariable2);

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
strcpy(str1,str2)
printf(‚ First String is:%s‛,str1);
printf(‚ Second String is:%s‛,str2);
getch();
}
Output:
Enter First String
Hello
Enter Second String
welcome
First String is: welcome
Second String is: welcome
(vi) strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.

Syntax
strlwr(StringVariable);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Lowercase String : %s‛, strlwr(str));
getch();
}
Output:
Enter String
WELCOME
Lowercase String : welcome
(vii) strrev() function:
strrev() function is used to reverse characters in a given string.

Syntax

strrev(StringVariable);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Reverse String : %s‛, strrev(str));
getch();
}
Output:
Enter String
WELCOME
Reverse String : emoclew
(viii) strupr() function:
strupr() function is used to convert all characters in a given string from lower case to
uppercase letter.

Syntax

strupr(Stringvariable);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);
gets(str);
printf(‚Uppercase String : %s‛, strupr(str));
getch();
}
Output:
Enter String
welcome
Uppercase String : WELCOME

STRUCTURES

Arrays are used for storing a group of SIMILAR data items. In order to store a group of
data items, we need structures. Structure is a constructed data type for packing different types
of data that are logically related. The structure is analogous to the “record” of a database.
Structures are used for organizing complex data in a simple and meaningful way.

Example for structures:

Student : regno, student_name, age, address

Book : bookid, bookname, author, price, edition, publisher, year

Employee : employeeid, employee_name, age, sex, dateofbirth, basicpay

Customer : custid, cust_name, cust_address, cust_phone

Structure Definition
Structures are defined first and then it is used for declaring structure variables. Let us
see how to define a structure using simple example given below:

struct book

int bookid;

char bookname[20];

char author[20];

float price;

int year;

int pages;

char publisher[25];

};
The keyword “struct” is used for declaring a structure. In this example, book is the name of the
structure or the structure tag that is defined by the struct keyword. The book structure has six
fields and they are known as structure elements or structure members. Remember each
structure member may be of a different data type. The structure tag name or the structure
name can be used to declare variables of the structure data type.

The syntax for structure definition is given below:

struct tagname

Data_type member1;

Data_type member2;

…………….

……………

};

Note:

1. To mark the completion of the template, semicolon is used at the end of the
template.
2. Each structure member is declared in a separate line.

Declaring Structure Variables

First, the structure format is defined. Then the variables can be declared of that structure type.
A structure can be declared in the same way as the variables are declared. There are two
ways for declaring a structure variable.

1) Declaration of structure variable at the time of defining the structure (i.e structure
definition and structure variable declaration are combined)

struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
} b1,b2,b3;

The b1, b2, and b3 are structure variables of type struct book.

2) Declaration of structure variable after defining the structure


struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};

struct book b1, b2, b3;

NOTE:
 Structure tag name is optional.

E.g.

struct
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
}b1, b2, b3;

Declaration of structure variable at a later time is not possible with this type of
declaration. It is a drawback in this method. So the second method can be preferred.

 Structure members are not variables. They don‟t occupy memory until they
are associated with a structure variable.

Accessing Structure Members


There are many ways for storing values into structure variables. The members of a
structure can be accessed using a “dot operator” or “period operator”.

E.g. b1.author -> b1 is a structure variable and author is a structure member.

Syntax

STRUCTURE_Variable.STRUCTURE_Members

The different ways for storing values into structure variable is given below:

Method 1: Using Simple Assignment Statement

b1.pages = 786;

b1.price = 786.50;

Method 2: Using strcpy function

strcpy(b1.title, ‚Programming in C‛);

strcpy(b1.author, ‚John‛);

Method 3: Using scanf function

scanf(‚%s \n‛, b1.title);

scanf(‚%d \n‛, &b1.pages);

Example

#include<stdio.h>

#include<conio.h>

struct book

int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};

struct book b1, b2, b3;


main()
{
struct book b1;
clrscr();
printf("Enter the Book Id: ");
scanf("%d", &b1.bookid);
printf("Enter the Book Name: ");
scanf("%s", b1.bookname);
printf("Enter the Author Name: ");
scanf("%s", b1.author);
printf("Enter the Price: ");
scanf("%f", &b1.price);
printf("Enter the Year: ");
scanf("%d", &b1.year);
printf("Enter the Total No. of Pages: ");
scanf("%d", &b1.pages);
printf("Enter the Publisher Name: ");
scanf("%s", b1.publisher);
printf("%d %s %d %f %d %d %s", b1.bookid, b1.bookname,
b1.author, b1.price, b1.year, b1.pages, b1.publisher);
getch();
}
Output

Enter the Book Id: 786


Enter the Book Name: Programming
Enter the Author Name: John
Enter the Price: 123.50
Enter the Year: 2015
Enter the Total No. of Pages: 649
Enter the Publisher Name: Tata McGraw
786 Programming 2118 123.500000 2015 649 Tata
Structure Initialization

Like variables, structures can also be initialized at the compile time.

Example
main()
{
struct
{
int rollno;
int attendance;
}
s1={786, 98};
}

The above example assigns 786 to the rollno and 98 to the attendance.

Structure variable can be initialized outside the function also.

Example

main()
{
struct student
{
int rollno;
int attendance;
};
struct student s1={786, 98};
struct student s2={123, 97};
}
Note:

Individual structure members cannot be initialized within the template. Initialization is


possible only with the declaration of structure members.

Nested Structures or Structures within Structures

Structures can also be nested. i.e A structure can be defined inside another structure.

Example

struct employee
{
int empid;
char empname[20];
int basicpay;
int da;
int hra;
int cca;
} e1;

In the above structure, salary details can be grouped together and defined as a
separate structure.

Example

struct employee
{
int empid;
char empname[20];
struct
{
int basicpay;
int da;
int hra;
int cca;
} salary;
} e1;
The structure employee contains a member named salary which itself is another
structure that contains four structure members. The members inside salary structure
can be referred as below:

e1.salary.basicpay
e1.salary.da;
e1.salary.hra;
e1.salary.cca;
However, the inner structure member cannot be accessed without the inner structure
variable.

Example

e1.basicpay
e1.da
e1.hra
e1.cca
are invalid statements
Moreover, when the inner structure variable is used, it must refer to its inner structure
member. If it doesn‟t refer to the inner structure member then it will be considered as
an error.

Example

e1.salary (salary is not referring to any inner structure member. Hence it is wrong)

Note: C permits 15 levels of nesting and C99 permits 63 levels of nesting.

Array of Structures

A Structure variable can hold information of one particular record. For example,
single record of student or employee. Suppose, if multiple records are to be
maintained, it is impractical to create multiple structure variables. It is like the
relationship between a variable and an array. Why do we go for an array? Because we
don‟t want to declare multiple variables and it is practically impossible. Assume that you
want to store 1000 values. Do you declare 1000 variables like a1, a2, a3…. Upto
a1000? Is it easy to maintain such code ? Is it a good coding? No. It is not.
Therefore, we go for Arrays. With a single name, with a single variable, we can store
1000 values. Similarly, to store 1000 records, we cannot declare 1000 structure
variables. But we need “Array of Structures”.

An array of structure is a group of structure elements under the same structure


variables.

struct student s1[1000];

The above code creates 1000 elements of structure type student. Each element
will be structure data type called student. The values can be stored into the array of
structures as follows:

s1[0].student_age = 19;

Example

#include<stdio.h>
#include<conio.h>
struct book
{
int bookid;
char bookname[20];
char author[20];
};

Struct b1[5];

main()
{
int i;
clrscr();
for (i=0;i<5;i++)
{
printf("Enter the Book Id: ");
scanf("%d", &b1[i].bookid);
printf("Enter the Book Name: ");
scanf("%s", b1[i].bookname);
printf("Enter the Author Name: ");
scanf("%s", b1[i].author);
}
for (i=0;i<5;i++)
{
printf("%d \t %s \t %s \n", b1[i].bookid, b1[i].bookname,
b1[i].author);
}
getch();
}

Output:

Enter the Book Id: 786


Enter the Book Name: Programming
Enter the Author Name: Dennis Ritchie
Enter the Book Id: 101
Enter the Book Name: Java Complete Reference
Enter the Author Name: Herbert Schildt
Enter the Book Id: 008
Enter the Book Name: Computer Graphics
Enter the Author Name: Hearn and Baker

786 Programming Dennis Ritchie


101 Java Complete Reference Herbert Schildt

008 Computer Graphics Hearn and Baker

Structure as Function Argument

Example
struct sample
{
int no;
float avg;
} a;
void main( )
{
a.no=75;
a.avg=90.25;
fun(a);
}

void fun(struct sample p)


{
printf(‚The no is=%d Average is %f‛,p.no , p.avg);
}

Output

The no is 75 Average is 90.25

Function that returns Structure

The members of a structure can be passed to a function. If a structure is to be passed to a


called function , we can use any one of the following method.

Method 1 :- Individual member of the structure is passed as an actual argument of the function
call. The actual arguments are treated independently. This method is not suitable if a structure
is very large structure.

Method 2:- Entire structure is passed to the called function. Since the structure declared as
the argument of the function, it is local to the function only. The members are valid for the
function only. Hence if any modification done on any member of the structure , it is not reflected
in the original structure.

Method 3 :- Pointers can be used for passing the structure to a user defined function. When
the pointers are used , the address of the structure is copied to the function. Hence if any
modification done on any member of the structure , it is reflected in the original structure.

Return data type function name ( structured variable )

Structured Data type for the structured variable;

{
Local Variable declaration;
Statement 1;
Statement 2;
--------------
-------------
Statement n;
}
Example :
#include <stdio.h>
struct st
{
char name[20];
int no;
int marks;
};
int main( )
{
struct st x ,y;
int res;
printf(‚\n Enter the First Record‛);
scanf(‚%s%d%d‛,x.name,&x.no,&x.marks);
printf(‚\n Enter the Second Record‛);
scanf(‚%s%d%d‛,y.name,&y.no,&y.marks);
res = compare ( x , y );
if (res == 1)
printf(‚\n First student has got the Highest Marks‛);
else
printf(‚\n Second student has got the Highest Marks‛);
}
compare ( struct st st1 , struct st st2)
{
if (st1.marks > st2. marks )
return ( 1 );
else
return ( 0 );
}

In the above example , x and y are the structures sent from the main ( ) function as the
actual parameter to the formal parameters st1 and st2 of the function compare ( ).

Example program (1) – passing structure to function

#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example *sptr)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr->num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr->num2);
}
//-------------------------------------
void print(struct Example *sptr)
{
printf("\nNum1 : %d",sptr->num1);
printf("\nNum2 : %d",sptr->num2);
}
//-------------------------------------
void main()
{
int i;
clrscr();
for(i=0;i<3;i++)
accept(&s[i]);

for(i=0;i<3;i++)
print(&s[i]);

getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60

Example program (2) – passing structure to function in C by value:


In this program, the whole structure is passed to another function by value. It means the
whole structure is passed to another function with all members and their values. So, this
structure can be accessed from called function. This concept is very useful while writing very big
programs in C.
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

void main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
getch();
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

Example program (3) Passing structure by value

A structure variable can be passed to the function as an argument as normal variable. If


structure is passed by value, change made in structure variable in function definition does not
reflect in original structure variable in calling function.

Write a C program to create a structure student, containing name and roll. Ask user the
name and roll of a student in main function. Pass this structure to a function and display
the information in that function.

#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration
otherwise compiler shows error */
int main()
{
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument
return 0;
}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}

Output
Enter student's name: Kevin Amla
Enter roll number: 149
Output

Example program (4) – Passing structure to function in C by address:


In this program, the whole structure is passed to another function by address. It means
only the address of the structure is passed to another function. The whole structure is not
passed to another function with all members and their values. So, this structure can be
accessed from called function by its address.
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student *record);

void main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(&record);
getch();
}

void func(struct student *record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

Example program (5) Passing structure by reference


The address location of structure variable is passed to function while passing it by
reference. If structure is passed by reference, change made in structure variable in function
definition reflects in original structure variable in the calling function.
Write a C program to add two distances(feet-inch system) entered by user. To solve this
program, make a structure. Pass two structure variable (containing distance in feet and
inch) to add function by reference and display the result in main function without
returning it.
#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3);

/*passing structure variables dist1 and dist2 by value whereas passing


structure variable dist3 by reference */
printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);
return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3)
{
/* Adding distances d1 and d2 and storing it in d3 */
d3->feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) { /* if inch is greater or equal to 12,
converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}
Output
First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5
Sum of distances = 18'-2.3"

Explanation
In this program, structure variables dist1 and dist2 are passed by value (because value of dist1
and dist2 does not need to be displayed in main function) and dist3 is passed by reference ,i.e,
address of dist3 (&dist3) is passed as an argument. Thus, the structure pointer variable d3
points to the address of dist3. If any change is made in d3 variable, effect of it is seed in dist3
variable in main function.

Example program(6) to declare a structure variable as global in C:

Structure variables also can be declared as global variables as we declare other


variables in C. So, When a structure variable is declared as global, then it is visible to all the
functions in a program. In this scenario, we don‟t need to pass the structure to any function
separately.
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

structure_demo();
return 0;
}

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

Example program(7)Passing Array of Structure to Function in C Programming

Array of Structure can be passed to function as a Parameter.function can also return Structure
as return type.Structure can be passed as follow

Example :

#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr[i].num2);
}
}
//-------------------------------------
void print(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
}
}
//-------------------------------------
void main()
{
int i;
clrscr();
accept(s,3);
print(s,3);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60

Explanation :

Inside main structure and size of structure array is passed. When reference (i.e ampersand) is
not specified in main , so this passing is simple pass by value. Elements can be accessed by
using dot [.] operator

Union
The concept of Union is borrowed from structures and the formats are also same. The
distinction between them is in terms of storage. In structures , each member is stored in its own
location but in Union , all the members are sharing the same location. Though Union consists of
more than one members , only one member can be used at a particular time. The size of the
cell allocated for an Union variable depends upon the size of any member within Union
occupying more no:- of bytes. The syntax is the same as structures but we use the keyword
union instead of struct.

Example:- the employee record is declared and processed as follows


union emp
{
char name[20];
int eno;
float salary;
} employee;

where employee is the union variable which consists of the member name,no
and salary. The compiler allocates only one cell for the union variable as
20 Bytes Length

Employee (only one location)

Location / Cell for name,no and salary

20 bytes cell can be shared by all the members because the member name is occupying the
highest no:- of bytes. At a particular time we can handle only one member.To access the
members of an union , we have to use the same format of structures.

Example program for C union:


#include <stdio.h>
#include <string.h>

union student
{
char name[20];
char subject[20];
float percentage;
};

int main()
{
union student record1;
union student record2;

// assigning values to record1 union variable


strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;

printf("Union record1 values example\n");


printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);

strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
Output:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
Explanation for above C union program:
There are 2 union variables declared in this program to understand the difference in
accessing values of union members.
Record1 union variable:

“Raju” is assigned to union member “record1.name” . The memory location name is


“record1.name” and the value stored in this location is “Raju”.
Then, “Maths” is assigned to union member “record1.subject”. Now, memory location
name is changed to “record1.subject” with the value “Maths” (Union can hold only one
member at a time).
Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location
name is changed to “record1.percentage” with value “86.50”.
Like this, name and value of union member is replaced every time on the common
storage space.
So, we can always access only one union member for which value is assigned at last.
We can‟t access other member values.
So, only “record1.percentage” value is displayed in output. “record1.name” and
“record1.percentage” are empty.

Record2 union variable:

If we want to access all member values using union, we have to access the member
before assigning values to other members as shown in record2 union variable in this
program.
Each union members are accessed in record2 example immediately after assigning
values to them.
If we don‟t access them before assigning values to other member, member name and
value will be over written by other member as all members are using same memory.
We can‟t access all members in union at same time but structure can do that.

Example program – Another way of declaring C union:


In this program, union variable “record” is declared while declaring union itself as shown in
the below program.
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
}record;

int main()
{

strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;

printf(" Name : %s \n", record.name);


printf(" Subject : %s \n", record.subject);
printf(" Percentage : %f \n", record.percentage);
return 0;
}
Output:
Name :
Subject :
Percentage : 86.500000
Note:
We can access only one member of union at a time. We can‟t access all member values at
the same time in union. But, structure can access all member values at the same time. This is
because, Union allocates one common storage space for all its members. Where as Structure
allocates storage space for all its members separately.
Difference between structure and union in C:
S.no C Structure C Union

Union allocates one common storage space for all its


Structure allocates storage members.
1 space for all its members Union finds that which of its member needs high storage
separately. space over other members and allocates that much space

Structure occupies higher


2 Union occupies lower memory space over structure.
memory space.

We can access all members


3 We can access only one member of union at a time.
of structure at a time.

4 Structure example: Union example:


struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

For above structure, memory


allocation will be like below.
For above union, only 8 bytes of memory will be allocated
int mark – 2B
since double data type will occupy maximum space of
5 char name[6] – 6B
memory over other data types.
double average – 8B
Total memory allocation = 8 Bytes
Total memory allocation =
2+6+8 = 16 Bytes

Assignment Question

1. Create a structure to store the employee number, name, department and basic salary.
Create a array of structure to accept and display the values of 10 employees.

PRACTICE QUESTIONS

Programs for Practice:

1) Write a C program to initialize an array using functions.


2) Write a C program to interchange array elements of two arrays using functions.
3) Write a C program to pass an array containing age of person to a function. This
function should find average age and display the average age in main function.
4) Write a c program to check whether a given string is a palindrome or not
5) What would be the output of the following programs:

main( )
{
char c[2] = "A" ;
printf ( "\n%c", c[0] ) ;
printf ( "\n%s", c ) ;
}
main( )
{
char str1[ ] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ } ;
char str2[ ] = "Hello" ;
printf ( "\n%s", str1 ) ;
printf ( "\n%s", str2 ) ;
}
a) main( )

printf ( 5 + "Good Morning " ) ;

6) Point out the errors,if any,in the following programs

(a) main( )
{
char *str1 = "United" ;
char *str2 = "Front" ;
char *str3 ;
str3 = strcat ( str1, str2 ) ;
printf ( "\n%s", str3 ) ;
}
7) Which is more appropriate for reading in a multi-word string?

` gets( ) printf( ) scanf( ) puts( )

8) If the string "Alice in wonder land" is feed to the following

scanf( ) statement, what will be the contents of the arrays

str1, str2, str3 and str4 ?

scanf ( "%s%s%s%s%s", str1, str2, str3, str4 ) ;


9) Fill in the blanks:
a. "A" is a ___________ while ‟A‟ is a ____________.
b. A string is terminated by a ______ character, which is written

as ______.

c. The array char name [10] can consist of a maximum of ______ characters.

1. Write a C program to initialize an array using functions.


#include<stdio.h>
int main()
int k, c(), d[ ]={c(),c(),c(),c(),c()};
printf(‚\nArray d[] elements are:‛);
for(k=0;k<5;k++)
printf(‚%2d‛,d[k]);
return(0);
}
c()
{
int m,n;
m++;
printf(‚\nEnter number d[%d] : ‛,m);
scanf(‚%d‛,&n);
return(n);
}
Output:
Enter Number d[1] : 20
Enter Number d[2] : 30
Enter Number d[3] : 40
Enter Number d[4] : 50
Enter Number d[5] : 60
Array d[] elements are: 20 30 40 50 60
2. Write a C program to interchange array elements of two arrays using
functions.
#include<stdio.h>
#include<conio.h>
void main()
{
int read();
void change(int*,int*);
int x,a[5],b[5];
clrscr();
printf(‚Enter 10 Numbers :‛);
for(x=0;x<10;x++)
{
if(x<5)
a[x]=read();
else
b[x-5]=read();
}
printf(‚\nArray A & B‛);
for(x=0;x<5;x++)
{
printf(‚\n%7d%8d‛,a[x],b[x]);
change(&a[x],&b[x]);
}
printf(‚\nNow A & B‛);
for(x=0;x<5;x++)
{
printf(‚\n%7d%8d‛,a[x],b[x]);
}
}
int read()
{
int x;
scanf(‚%d‛,&x);
return(x);
}
void change(int *a,int *b)
{
int *k;
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
Output:
Enter 10 Numbers:
0 1 2 3 4 5 6 7 8 9
Array A & B
0 5
1 6
2 7
3 8
4 9
Now A & B
5 0
6 1
7 2
8 3
9 4
3. Write a C program to pass an array containing age of person to a
function. This function should find average age and display the
average age in main function.
#include <stdio.h>
float average(float a[]);
int main(){
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[])
{
int i;
float avg, sum=0.0;
for(i=0;i<6;++i){
sum+=a[i];
}
avg =(sum/6);
return avg;
}
Output:
Average age=27.08
UNIT IV FUNCTIONS AND POINTERS

Function – definition of function – Declaration of function – Pass by value – Pass by


reference –Recursion – Pointers - Definition – Initialization – Pointers arithmetic – Pointers and
arrays- Example Problems

NOTES :
 Functions are created when the same process or an algorithm to be repeated several times
in various places in the program.
 Function has a self-contained block of code, that executes certain task. A function has a
name, a list of arguments which it takes when called, and the block of code it executes when
called.
 Functions are two types:
1. Built-in / Library function.
Example: printf(), scanf(), getch(), exit(), etc.
2. User defined function.
3.
User-Defined Functions
Functions defined by the users according to their requirements are called user-defined functions.
These functions are used to break down a large program into a small functions.

Advantage of User defined function:


1. Reduce the source code
2. Easy to maintain and modify
3. It can be called any where in the program.

Body of user defined function:


return_type f_name (argument1,argument 2)
{
local variables;
statements;
return_type;
}

GE6151-COMPUTER PROGRAMMING Page 1


The body of user-defined shows that an user-defined functions has following characteristics:
1. Return type
2. Function name
3. Parameter list of arguments
4. Local variables
5. Statements
6. Return value

S.No C function aspects Syntax


1 function definition return_type function_name ( arguments list )
{ Body of function; }
2 function call function_name ( arguments list );
3 unction declaration return_type function_name ( argument list );

Note: The function with return value must be the data type, that is return type and return value
must be of same data type.

User defined function has three parts:


1. Declaration part
ret_type f_name (arguments)
2. Calling part
f_name(arguments);
4. Definition part
5.
Function Parameters:
Parameters provide the data communication between calling function and called function.

Two types:

GE6151-COMPUTER PROGRAMMING Page 2


Actual parameters:
These are the parameters transferred from the calling function[main function] to the called
function[user defined function].
Formal parameters:
Passing the parameters from the called functions[user defined function] to the calling
functions[main function].

Note:
 Actual parameter– This is the argument which is used in function call.
 Formal parameter– This is the argument which is used in function definition.

4.1 Categories of User defined function/Function Prototypes:


 A function prototype declaration consists of the function‟s return type, name and
arguments list.
 Always terminated with semicolon.
The following are the function prototypes:
1. Function without return value and without argument.
2. Function without return value and with argument.
3. Function with return value and with argument.
4. Function with return value and without argument.

Note: Function with more than one return value will not have return type and return statement in
the function definition.

Consider the following example to multiply two numbers:


void main( )
{
int x,y,z;
scanf(“%d%d”, &x,&y);
z=x* y;
printf(“The result is %d”, z); }

1. Function without return value and without argument


In this prototype, no data transfers takes place between the calling function and the called
function. They read data values and print result in the same block.

Syntax:
void f_name(); //function declaration
void f_name (void) //function definition
{
local variables;
statements;
}
void main()
{
f_name(); //function call

GE6151-COMPUTER PROGRAMMING Page 3


}
The above example can be rewritten by creating function:
void f_mult(); //function definition
void f_mult(void )
{
int x,y,z;
scanf(“%d%d”, &x,&y);
z=x* y;
printf(“The result is %d”, z);
}
void main()
{
f_mult();
}

2. Function without return value and with argument


In this prototype, data is transferred from the calling function to called function. The called
function receives some data from the calling function and does not send back any values to the
calling functions.

Syntax:
void f_name(int x, int y ); //Function declaration
void f_name (int x, int y) //Function Definition //Formal Parameters
{
local variables;
statements;
}
void main()
{
//variable declaration
//input statement
f_name(c, d); //Function call //Actual Parameters
}

The above example can be rewritten by creating function


void f_mult(int x, int y);
void f_mult(int x, int y )
{
int z;
z=x* y;
printf(“The result is %d”, z);
}
void main()
{ int c, d;
printf(“Enter any two number”);
scanf(“%d%d”, &c, &d);

GE6151-COMPUTER PROGRAMMING Page 4


f_mult(c, d); //Function call
}

3. Function with return value and without argument


The calling function cannot pass any arguments to the called function but the called function
may send some return value to the calling function.
Syntax:
int f_name(); //Function declaration
int f_name (void) //Function Definition
{
local variables;
statements;
return int;
}
void main()
{
//variable declaration
ret_var=f_name(); //Function call
}

The above example can be rewritten by creating function


int f_mult();
int f_mult(void )
{
int x,y,z;
scanf(“%d%d”, &x,&y);
z=x* y;
printf(“The result is %d”, z);
return(z); }
void main()
{
int c;
c=f_mult();
getch();
}

4. Function with return value and with argument


In this prototype, the data is transferred between the calling function and called function. The
called function receives some data from the calling function and send back a value return to the
calling function.

Syntax:
int f_name (int x, int y); //Function declaration
int f_name (int x, int y) //Function definition //Formal Parameters
{
local variables;

GE6151-COMPUTER PROGRAMMING Page 5


statements;
return int;
}
void main()
{
//variable declaration
//Input Statement
ret_value=f_mult(a, b); //Function Call //Actual Parameters
}

The above example can be rewritten by creating function:


int f_mult(int x, int y);
int f_mult(int x, int y)
{
int z;
z=x* y;
printf(“The result is %d”, z);
return(z);
}
void main()
{
int a,b,c;
printf(“Enter any two value:”);
scanf(“%d%d”, &a, &b);
c=f_mult(a, b);
}

Note:
 If the return data type of a function is “void”, then, it can‟t return any values to the
calling function.
 If the return data type of the function is other than void such as “int, float, double etc”,
then, it can return values to the calling function.

return statement:
It is used to return the information from the function to the calling portion of the program.

Syntax:
return;
return();
return(constant);
return(variable);
return(exp);
return(condn_exp);
By default, all the functions return int data type.

GE6151-COMPUTER PROGRAMMING Page 6


Do you know how many values can be return from C functions?
 Always, only one value can be returned from a function.
 If you try to return more than one values from a function, only one value will be returned
that appears at the right most place of the return statement.
 For example, if you use “return a,b,c” in your function, value for c only will be returned
and values a, b won‟t be returned to the program.
 In case, if you want to return more than one values, pointers can be used to directly
change the values in address instead of returning those values to the function.

Function Call:
A function can be called by specifying the function_name in the source program with
parameters, if presence within the paranthesis.

Syntax:
Fn_name();
Fn_name(parameters);
Ret_value=Fn_name(parameters);

Example:
#include<stdio.h>
#include<conio.h>
int add(int a, int b); //function declaration
void main()
{
int x,y,z;
printf(“\n Enter the two values:”);
scanf(“%d%d”,&x,&y);
z=add(x,y); //Function call(Actual parameters)
printf(“The sum is .%d”, z);
}
int add(int a, int b) //Function definition(Formal parameters)
{
int c;
c=a+b;
return(c); //return statement
}

4.2 Parameter Passing Methods/Argument Passing Methods

Call by Value/Pass by Value:


When the value is passed directly to the function it is called call by value. In call by value only a
copy of the variable is only passed so any changes made to the variable does not reflects in the
calling function.

GE6151-COMPUTER PROGRAMMING Page 7


Example:
#include<stdio.h>
#include<conio.h>
swap(int,int);
void main()
{
int x,y;
printf("Enter two nos");
scanf("%d %d",&x,&y);
printf("\nBefore swapping : x=%d y=%d",x,y);
swap(x,y);
getch();
}
swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
printf("\nAfter swapping :x=%d y=%d",a,b);
}

System Output:
Enter two nos 12 34
Before swapping :12 34
After swapping : 34 12

Call by Reference/Pass by Reference:


When the address of the value is passed to the function it is called call by reference. In call by
reference since the address of the value is passed any changes made to the value reflects in the
calling function.
Example:
#include<stdio.h>
#include<conio.h>
swap(int *, int *);
void main()
{
int x,y;
printf("Enter two nos");
scanf("%d %d",&x,&y);
printf("\nBefore swapping:x=%d y=%d",x,y);
swap(&x,&y);
printf("\nAfter swapping :x=%d y=%d",x,y);
getch();
}
swap(int *a,int *b)

GE6151-COMPUTER PROGRAMMING Page 8


{
int t;
t=*a;
*a=*b;
*b=t;
}
System Output:
Enter two nos 12 34
Before swapping :12 34
After swapping : 34 12

Library Functions:
C language provides built-in-functions called library function compiler itself evaluates these
functions.
List of Functions
 Sqrt(x) (x)0.5
 Log(x)
 Exp(x)
 Pow(x,y)
 Sin(x)
 Cos(x)
 Rand(x)-> generating a positive random integer.

4.3 Recursion in C:
Recursion is calling function by itself again and again until some specified condition has been
satisfied.

GE6151-COMPUTER PROGRAMMING Page 9


Syntax:
int f_name (int x)
{
local variables;
f_name(y); // this is recursion
statements;
}

Example_1: Factorial using Recursion


#include<stdio.h>
#include<conio.h>
int factorial(int n);
void main()
{
int res,x;
printf(“\n Enter the value:”);
scanf(“%d”, &x);
res=factorial(x);
printf(“The factorial of %d is ..%d”, res);
}
int factorial(int n)
{
int fact;
if (n==1)
return(1);
else
fact = n*factorial(n-1);
return(fact);
}

Example_2: Fibonacci using Recursion


#include<stdio.h>
#include<conio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
return 0;

GE6151-COMPUTER PROGRAMMING Page 10


}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

Example_3: Sum of n Natural Numbers


#include<stdio.h>
#include<conio.h>
int add(int n);
void main()
{
int m, x;
printf("Enter an positive integer: ");
scanf("%d",&m);
x=add(m);
printf("Sum = %d", x);
getch();
}
int add(int n)
{
if(n!=0)
return n+add(n-1); /* recursive call */
}

4.4 POINTERS
Definition:
 C Pointer is a variable that stores/points the address of the another variable.
 C Pointer is used to allocate memory dynamically i.e. at run time.
 The variable might be any of the data type such as int, float, char, double, short etc.
 Syntax : data_type *var_name;
Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.

Key points to remember about pointers in C:


 Normal variable stores the value whereas pointer variable stores the address of the
variable.
 The content of the C pointer always be a whole number i.e. address.
 Always C pointer is initialized to null, i.e. int *p = null.
 The value of null pointer is 0.
 & symbol is used to get the address of the variable.

GE6151-COMPUTER PROGRAMMING Page 11


 * symbol is used to get the value of the variable that the pointer is pointing to.
 If pointer is assigned to NULL, it means it is pointing to nothing.
 The size of any pointer is 2 byte (for 16 bit compiler).
 No two pointer variables should have the same name.
 But a pointer variable and a non-pointer variable can have the same name.

4.4.1 Pointer –Initialization:


Assigning value to pointer:
It is not necessary to assign value to pointer. Only zero (0) and NULL can be assigned to a
ointer no other number can be assigned to a pointer. Consider the following examples;
int *p=0;
int *p=NULL; The above two assignments are valid.
int *p=1000; This statement is invalid.

Assigning variable to a pointer:


int x; *p;
p = &x;
This is nothing but a pointer variable p is assigned the address of the variable x. The address of
the variables will be different every time the program is executed.

Reading value through pointer:


int x=123; *p;
p = &x;
Here the pointer variable p is assigned the address of variable x.
printf(“%d”, *p); will display value of x 123. This is reading value through pointer
printf(“%d”, p); will display the address of the variable x.
printf(“%d”, &p); will display the address of the pointer variable p.
printf(“%d”,x); will display the value of x 123.
printf(“%d”, &x); will display the address of the variable x.

Note: It is always a good practice to assign pointer to a variable rather than 0 or NULL.
Pointer Assignments:

We can use a pointer on the right-hand side of an assignment to assign its value to another
variable.

Example:
int main()
{
int var=50;
int *p1, *p2;
p1=&var;
p2=p1;
}

GE6151-COMPUTER PROGRAMMING Page 12


Chain of pointers/Pointer to Pointer:
A pointer can point to the address of another pointer. Consider the following example.
int x=456, *p1, **p2; //[pointer-to-pointer];
p1 = &x;
p2 = &p1;
printf(“%d”, *p1); will display value of x 456.
printf(“%d”, *p2); will also display value of x 456.
This is because p2 point p1, and p1 points x.
Therefore p2 reads the value of x through pointer p1. Since one pointer is points towards another
pointer it is called chain pointer. Chain pointer must be declared with ** as in **p2.

Manipulation of Pointers
We can manipulate a pointer with the indirection operator „*‟, which is known as dereference
operator. With this operator, we can indirectly access the data variable content.

Syntax:
*ptr_var;

Example:
#include<stdio.h>
void main()
{
int a=10, *ptr;
ptr=&a;
printf(”\n The value of a is ”,a);
*ptr=(*ptr)/2;
printf(”The value of a is.”,(*ptr));
}

Output:
The value of a is: 10
The value of a is: 5

4.4.2 Pointer Expression & Pointer Arithmetic


 C allows pointer to perform the following arithmetic operations:
 A pointer can be incremented / decremented.
 Any integer can be added to or subtracted from the pointer.

A pointer can be incremented / decremented.


In 16 bit machine, size of all types[data type] of pointer always 2 bytes.
Eg:
int a;
int *p;
p++;

GE6151-COMPUTER PROGRAMMING Page 13


Each time that a pointer p is incremented, the pointer p will points to the memory location of the
next element of its base type. Each time that a pointer p is decremented, the pointer p will points
to the memory location of the previous element of its base type.
int a,*p1, *p2, *p3;
p1=&a;
p2=p1++;
p3=++p1;
printf(“Address of p where it points to %u”, p1); 1000
printf(“After incrementing Address of p where it points to %u”, p1); 1002
printf(“After assigning and incrementing p %u”, p2); 1000
printf(“After incrementing and assigning p %u”, p3); 1002
In 32 bit machine, size of all types of pointer is always 4 bytes.
The pointer variable p refers to the base address of the variable a. We can increment the pointer
variable,
p++ or ++p
This statement moves the pointer to the next memory address. let p be an integer pointer with a
current value of 2,000 (that is, it contains the address 2,000). Assuming 32-bit integers, after the
expression
p++
the contents of p will be 2,004, not 2,001! Each time p is incremented, it will point to the next
integer. The same is true of decrements. For example,
p–
will cause p to have the value 1,996, assuming that it previously was 2,000. Here is why: Each
time that a pointer is incremented, it will point to the memory location of the next element of its
base type. Each time it is decremented, it will point to the location of the previous element of its
base type.

Any integer can be added to or subtracted from the pointer.


Like other variables pointer variables can be used in expressions. For example if p1 and p2 are
properly declared and initialized pointers, then the following statements are valid.
y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;
C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer
from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc., we
can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2
and p1!=p2 are allowed.

/*Program to illustrate the pointer expression and pointer arithmetic*/


#include< stdio.h >
#include<conio.h>
void main()
{
int ptr1,ptr2;
int a,b,x,y,z;

GE6151-COMPUTER PROGRAMMING Page 14


a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a + %u”,ptr1);
printf(“\nAddress of b %u”, ptr2);
printf(“\na=%d, b=%d”, a, b);
printf(“\nx=%d,y=%d”, x, y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“\na=%d, b=%d”, a, b);
}

/* Sum of two integers using pointers*/


#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
return 0;
}

4.4.3 Pointers and Arrays


Array name is a constant pointer that points to the base address of the array[i.e the first element
of the array]. Elements of the array are stored in contiguous memory locations. They can be
efficiently accessed by using pointers.
Pointer variable can be assigned to an array. The address of each element is increased by one
factor depending upon the type of data type. The factor depends on the type of pointer variable
defined. If it is integer the factor is increased by 2. Consider the following example:
int x[5]={11,22,33,44,55}, *p;
p = x; //p=&x; // p = &x[0];
Remember, earlier the pointer variable is assigned with address (&) operator. When working
with array the pointer variable can be assigned as above or as shown below:
Therefore the address operator is required only when assigning the array with element. Assume
the address on x[0] is 1000 then the address of other elements will be as follows
x[1] = 1002
x[2] = 1004
x[3] = 1006
x[4] = 1008

GE6151-COMPUTER PROGRAMMING Page 15


The address of each element increase by factor of 2. Since the size of the integer is 2 bytes the
memory address is increased by 2 bytes, therefore if it is float it will be increase 4 bytes, and for
double by 8 bytes. This uniform increase is called scale factor.
p = &x[0];
Now the value of pointer variable p is 1000 which is the address of array element x[0].
To find the address of the array element x[1] just write the following statement.
p = p + 1;
Now the value of the pointer variable p is 1002 not 1001 because since p is pointer variable the
increment of will increase to the scale factor of the variable, since it is integer it increases by 2.
The p = p + 1; can be written using increment or decrement operator ++p; The values in the array
element can be read using increment or decrement operator in the pointer variable using scale
factor.
Consider the above example.
printf(“%d”, *(p+0)); will display value of array element x[0] which is 11.
printf(“%d”, *(p+1)); will display value of array element x[1] which is 22.
printf(“%d”, *(p+2)); will display value of array element x[2] which is 33.
printf(“%d”, *(p+3)); will display value of array element x[3] which is 44.
printf(“%d”, *(p+4)); will display value of array element x[4] which is 55.

/*Displaying the values and address of the elements in the array*/


#include<stdio.h>
void main()
{
int a[6]={10, 20, 30, 40, 50, 60};
int *p;
int i;
p=a;
for(i=0;i<6;i++)
{
printf(“%d”, *p); //value of elements of array
printf(“%u”,p); //Address of array
}
getch();
}

/* Sum of elements in the Array*/


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10];
int i,sum=0;
int *ptr;
printf("Enter 10 elements:n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);

GE6151-COMPUTER PROGRAMMING Page 16


ptr = a; /* a=&a[0] */
for(i=0;i<10;i++)
{
sum = sum + *ptr; //*p=content pointed by 'ptr'
ptr++;
}
printf("The sum of array elements is %d",sum);
}

/*Sort the elements of array using pointers*/


#include<stdio.h>
int main(){
int i,j, temp1,temp2;
int arr[8]={5,3,0,2,12,1,33,2};
int *ptr;
for(i=0;i<7;i++){
for(j=0;j<7-i;j++){
if(*(arr+j)>*(arr+j+1)){
ptr=arr+j;
temp1=*ptr++;
temp2=*ptr;
*ptr--=temp1;
*ptr=temp2;
}}}
for(i=0;i<8;i++){
printf(" %d",arr[i]); } }

4.4.4 Pointers and Multi-dimensional Arrays


The array name itself points to the base address of the array.
Example:
int a[2][3];
int *p[2];
p=a; //p points to a[0][0]

/*Displaying the values in the 2-d array*/


#include<stdio.h>
void main()
{
int a[2][2]={{10, 20},{30, 40}};
int *p[2];
int i,j;
p=a;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{

GE6151-COMPUTER PROGRAMMING Page 17


printf(“%d”, *(*(p+i)+j)); //value of elements of array
}
}
getch();
}

4.5 Dynamic Memory Allocation


The process of allocating memory during program execution is called dynamic memory
allocation.

Dynamic memory allocation functions

Sl.No Function Syntax Use


1 malloc() ptr=(cast-type*)malloc(byte-size) Allocates requested size of bytes
and returns a pointer first byte of
allocated space.
2 calloc() ptr=(cast-type*)calloc(n,element- Allocates space for an array
size) elements, initializes to zero and
then returns a pointer to memory.
3 free() free(ptr); dellocate the previously allocated
space.
4 realloc() ptr=realloc(ptr,newsize); Change the size of previously
allocated space.

GE6151-COMPUTER PROGRAMMING Page 18


UNIT V STRUCTURES AND UNIONS

Introduction – need for structure data type – structure definition – Structure declaration –
Structure within a structure - Union - Programs using structures and Unions – Storage classes, Pre-
processor directives.

NOTES:
Array Structure
 Single name that contains a collection of data items of same data type, Single name that
contains a collection of data items of different data types.
 Individual entries in a array are called elements. Individual entries in a structure are called
members.
 No Keyword Keyword: struct
 Members of an array are stored in sequence of memory locations.
 Members of a structure are not stored in sequence of memory locations.

5.1 STRUCTURES
Structure is a collection of variables under the single name, which can be of different data type. In
simple words, Structure is a convenient way of grouping several pieces of related information
together.
A structure is a derived data type, The scope of the name of a structure member is limited to the
structure itself and also to any variable declared to be of the structure's type.
Variables which are declared inside the structure are called ―members of structure‖.
Syntax: In general terms, the composition of a structure may be defined as:
struct <tag>
{
member 1;
member 2;

….

GE6151-COMPUTER PROGRAMMING Page 1


member m;

where, struct is a keyword, <tag> is a structure name.

For example:
struct student
{
char name [80];
int roll_no;
float marks;
};
Now we need an interface to access the members declared inside the structure, it is called structure
variable. we can declare the structure variable in two ways:
i) within the structure definition itself.
ii) within the main function.
i] within the structure definition itself.
struct tag
{
member 1;
member 2;
——

member
m;
} variable 1, variable 2 variable
n; //Structure variables
Eg:
struct student
{

GE6151-COMPUTER PROGRAMMING Page 2


char name [80];
int roll_no;

float marks;
}s1;

ii] within the main function.


struct tag
{
member 1;
member 2;
——

member
m;
};
void main()
{
struct tag var1, var2,...,var_n; //structure variable
}
Eg:
struct student
{
char name [80];
int roll_no;
float marks;
};
void main()
{
struct student s1, s2; //declaration of structure variable.

GE6151-COMPUTER PROGRAMMING Page 3


};

Note: Structure variable can be any of three types:


1. normal variable
2. array_variable
3. pointer_variable

Initialization of Structure members:


A structure variable, like an array can be initialized in two ways:
I. struct student
{
char name [80];
int roll_no;
float marks ;
} s1={―Saravana‖,34,469};
II. struct student
{
char name [80];
int roll_no;
float marks ;
} s1;
struct student s1= {―Saravana‖,34,469};
[OR]
s1.name={―Saravana‖};
s1.roll_no=34;
s1.marks=500;
It is also possible to define an array of structure, that is an array in which each element is a structure.
The procedure is shown in the following example:
struct student

GE6151-COMPUTER PROGRAMMING Page 4


{
char name [80];
int roll_no ;
float marks ;

} st [100];

In this declaration st is a 100element array of structures. It means each element of st represents an


individual student record.

Accessing the Structure Members


The members of a structure are usually processed individually, as separate entities. Therefore, we must
be able to access the individual structure members. A structure member can be accessed by writing:
structure_variable.member_name //[normal variable]
Eg:
struct student
{
char name [80];
int roll_no ;
float marks ;
}st;
e.g. if we want to get the detail of a member of a structure then we can write as
scanf(―%s‖,st.name); or scanf(―%d‖, &st.roll_no) and so on.
if we want to print the detail of a member of a structure then we can write as
printf(―%s‖,st.name); or printf(―%d‖, st.roll_no) and so on.
The use of the period operator can be extended to arrays of structure by writing:
array [expression].member_name //[array variable]
Eg:
struct student
{

GE6151-COMPUTER PROGRAMMING Page 5


char name [80];
int roll_no ;

float marks ;
}st[10];
e.g. if we want to get the detail of a member of a structure then we can write as
scanf(―%s‖,st[i].name); or scanf(―%d‖, &st[i].roll_no) and so on.
if we want to print the detail of a member of a structure then we can write as
printf(―%s‖,st[i].name); or printf(―%d‖, st[i].roll_no) and so on.
The use of the period operator can be extended to pointer of structure by writing:
array [expression]>
member_name //[array variable]
Eg:
struct student
{
char name [80];
int roll_no ;
float marks ;
}*st;
void main()
{
Struct student s;
st=&s;
e.g. if we want to get the detail of a member of a structure then we can write as
scanf(―%s‖,st>
name); or scanf(―%d‖, &st>
roll_no) and so on.
if we want to print the detail of a member of a structure then we can write as
printf(―%s‖,st>
name); or printf(―%d‖, st>
roll_no) and so on.

GE6151-COMPUTER PROGRAMMING Page 6


It is also possible to pass entire structure to and from functions though the way this is done varies from
one version of 'C' to another.

PROGRAM’S USING STRUCTURE


Example 1://To print the student details// normal structure variable
#include<stdio.h>
struct student
{
char name[30];
int reg_no[15];
char branch[30];
};
void main()
{
struct student s1;
printf(―\n Enter the student name::‖);
scanf(―%s‖,s1.name);
printf(―\n Enter the student register number::‖);
scanf(―%s‖,&s1.reg_no);
printf(―\n Enter the student branch::‖);
scanf(―%s‖,s1.branch);
printf(―\n Student Name::‖,s1.name);
printf(―\n Student Branch::‖,s1.branch);
printf(―\n Student reg_no::‖,s1.reg_no);
getch();
}

Example 2://To print the student details// pointer structure variable


#include <stdio.h>
struct name{
int a;

GE6151-COMPUTER PROGRAMMING Page 7


float b;
};
int main()
{
struct name *ptr,p;
ptr=&p; /* Referencing pointer to memory address of p */
printf("Enter integer: ");
scanf("%d",&(*ptr).a);
printf("Enter number: ");
scanf("%f",&(*ptr).b);
printf("Displaying: ");
printf("%d%f",(*ptr).a,(*ptr).b);
return 0;
}
Example 3://To print the Mark sheet for a student//
#include<stdio.h>
struct student
{
char name[30];
int reg_no[15];
char branch[30];
int m1,m2,m3,total;
float avg;
};

void main()
{
int total;
float avg;
struct student s1;
printf(―\n Enter the student name::‖);

GE6151-COMPUTER PROGRAMMING Page 8


scanf(―%s‖,s1.name);
printf(―\n Enter the student register number::‖);
scanf(―%s‖,&s1.reg_no);
printf(―\n Enter the student branch::‖);
scanf(―%s‖,s1.branch);
printf(―\n Enter the 3 subjects Marks:‖);
scanf(―%d%d%d‖, &s1.m1,&s1.m2,&s1.m3);
s1.total=s1.m1+s1.m2+s1.m3;
printf(―\n Ur Total mark is.%d‖, s1.total);
s1.avg=a1.total/3;
printf(―\n Ur Average mark is.%f‖, s1.avg);
getch();
}

Example_4: /* To Print Students Mark Sheet's using Structures*/


#include"stdio.h"
#include"conio.h"
struct student
{
char name[25],grade;
int reg_no[15];
int s1,s2,s3,s4,s5,total;
float avg;

}sa[20];

void main()
{
int i,n,total;
float avg;

GE6151-COMPUTER PROGRAMMING Page 9


printf("\n Enter the count of Students need marksheet::");
scanf("%d",&n);
printf("\n Enter the name of students:,reg_no, 5 sub marks::");
for(i=0;i<n;i++)
{
printf("\n Enter the name of students,reg_no, 5 sub marks::%d",i+1);
scanf("%s%d%d%d%d%d%d", &sa[i].name, &sa[i].reg_no, &sa[i].s1, &sa[i].s2, &sa[i].s3,
&sa[i].s4, &sa[i].s5);
sa[i].total=sa[i].s1+sa[i].s2+sa[i].s3+sa[i].s4+sa[i].s5;
sa[i].avg=sa[i].total/5;
if((sa[i].s1<50)||(sa[i].s2<50)||(sa[i].s3<50)||(sa[i].s4<50)||(sa[i].s5<50))
{
sa[i].grade='U';
printf("Ur grade is %c", sa[i].grade);
}

else
{
if(sa[i].avg==100)
{
sa[i].grade='S';
printf("Ur Grade is %c", sa[i].grade);
}
if((sa[i].avg>90)&&(sa[i].avg<=99))
{

sa[i].grade='A';
printf("Ur Grade is %c", sa[i].grade);
}

GE6151-COMPUTER PROGRAMMING Page 10

You might also like