PPS - 2
PPS - 2
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.
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.
#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.
• 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.
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.
• 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)
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 (.).
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.
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:
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;
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:
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:
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 :
16
Arithmetic Operators:
There are five arithmetic operators in C. They are
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.
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:
• 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.
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:
Ex:
24
Syntax 2:
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:
• 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.
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.
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:
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.
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:
50
Write Algorithm:
• 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
Start/stop
Process
Decision
Input/output
52
Symbol Name Symbol Representation
Stored data
Document
Flow
Predefined process
Connector
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:
• 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:
• 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
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
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];
Types of Array
1. Single Dimensional Array / One Dimensional Array
2. Multi Dimensional Array
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:
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
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
1 integer roll 1 10
Declaration a[3][4]
No of Rows 3
No of Columns 4
No of Cells 12
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
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
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
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.
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);
C library supports a large number of string handling functions. Those functions are stored under
the header file string.h in the program.
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
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.
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.
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.
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.
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.
Syntax
STRUCTURE_Variable.STRUCTURE_Members
The different ways for storing values into structure variable is given below:
b1.pages = 786;
b1.price = 786.50;
strcpy(b1.author, ‚John‛);
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];
};
Example
main()
{
struct
{
int rollno;
int attendance;
}
s1={786, 98};
}
The above example assigns 786 to the rollno and 98 to the attendance.
Example
main()
{
struct student
{
int rollno;
int attendance;
};
struct student s1={786, 98};
struct student s2={123, 97};
}
Note:
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)
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”.
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:
Example
struct sample
{
int no;
float avg;
} a;
void main( )
{
a.no=75;
a.avg=90.25;
fun(a);
}
Output
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.
{
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 ( ).
#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
struct student
{
int id;
char name[20];
float percentage;
};
void main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
getch();
}
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
struct student
{
int id;
char name[20];
float percentage;
};
void main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
getch();
}
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.
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
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.
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
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.
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
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:
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.
int main()
{
strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;
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
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( )
(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?
as ______.
c. The array char name [10] can consist of a maximum of ______ characters.
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.
Note: The function with return value must be the data type, that is return type and return value
must be of same data type.
Two types:
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.
Note: Function with more than one return value will not have return type and return statement in
the function definition.
Syntax:
void f_name(); //function declaration
void f_name (void) //function definition
{
local variables;
statements;
}
void main()
{
f_name(); //function call
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
}
Syntax:
int f_name (int x, int y); //Function declaration
int f_name (int x, int y) //Function definition //Formal Parameters
{
local variables;
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.
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
}
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.
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.
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;
}
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
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;
….
member m;
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
{
float marks;
}s1;
} st [100];
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.
void main()
{
int total;
float avg;
struct student s1;
printf(―\n Enter the student name::‖);
}sa[20];
void main()
{
int i,n,total;
float avg;
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);
}