0% found this document useful (0 votes)
5K views425 pages

PPS Notes by IT Department Gtu

This document provides an introduction to computers and programming. It discusses the basic components of a computer including input, output, CPU, primary memory, secondary memory. It describes different types of software including system software and application software. It also covers topics like high level and low level languages, flowcharts, algorithms and the differences between algorithms and flowcharts.

Uploaded by

anjanikumar9023
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)
5K views425 pages

PPS Notes by IT Department Gtu

This document provides an introduction to computers and programming. It discusses the basic components of a computer including input, output, CPU, primary memory, secondary memory. It describes different types of software including system software and application software. It also covers topics like high level and low level languages, flowcharts, algorithms and the differences between algorithms and flowcharts.

Uploaded by

anjanikumar9023
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

CHAPTER-1

INTRODUCTION TO COMPUTER AND PROGRAMMING

SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE
 Introduction
 Basic block diagram

 functions of various components of computer

 Concepts of Hardware and software

 Types of software,

 Compiler and interpreter

 Concepts of Machine level, Assembly level and high


level programming
 Flowcharts

 Algorithms
INTRODUCTION
 Computer is an electronic device used to perform
arithmetic and logical operation at very high speed
and with highest accuracy.
 Computer is an electronic device which takes input
from user, perform operation on it and generate the
output.
BLOCK DIAGRAM OF COMPUTER

 There are five main component of computer.


1) Input Device
2) CPU
3) Primary Memory
4) Secondary Memory
5) Output Device
Block diagram of computer
INPUT DEVICE
 Input device is used to get the data from user.
 All the data from input devices must be entered
into Primary Memory. ∙ When user enters data
through keyboard, which are into user language
must be converted into binary language.
 So, Input device is bridge between user and
computer.
 Example: keyboard, mouse, scanner, joy stick,
light pen etc
CPU
∙ CPU – Central Processing Unit
∙ It is the brain of computer.
∙ CPU is divided into two main parts.
I) ALU
II) CU
CPU = ALU + CU
CPU
I) ALU – Arithmetic & Logical Unit
∙ As the name suggest it is used to perform arithmetic
and logical operation on data which is come from
primary memory (RAM).
∙ Data is processed on ALU and generate the result
which is again transfer from ALU to RAM.
II) CU – Control Unit
∙ This unit does not take part into any calculation or
operation.
∙ As the name, it is used to control the devices like input
device, output device and primary memory.
PRIMARY MEMORY
All the data, whether it will from input device or from
secondary memory must come into primary memory.
There are two types of primary memory:
I) RAM II) ROM
I) RAM:
RAM – Random Access Memory
It is volatile memory.
∙ We can say that RAM is temporary storage unit and
can’t store data permanent.
∙ All the data from input device or from secondary
memory must come into RAM.
∙ When we turn off the system all the data are erased
from RAM.
PRIMARY MEMORY
 ROM:
∙ ROM – Read Only Memory
∙ As name we can’t write any data into ROM, we
can just read the data from ROM.
∙ It is non-volatile memory.
∙ ROM can store data permanently.
∙ It contains the different details of manufactures,
version etc.
SECONDARY MEMORY
∙ It is non volatile memory, so can store data
permanently.
∙ When result is generated by ALU and if want to
store result permanently, then we can store such
data into secondary memory.
∙ Ex. HDD – Hard Disk Drive, Flash Drive, CD,
DVD etc.
∙ Operating System is also store into secondary
memory.
OUTPUT DEVICE
∙ It is used to display the result generated by CPU.
∙ Again result generated by computer is in binary
form, so need to convert this data into user
language.
∙ Ex. Monitor, Printer, Plotter etc.
SOFTWARE AND DIFFERENT TYPES OF SOFTWARE

 Software is collection of programs and


program is collection of instruction. It is
logical component of computer, which
cannot touch.
 It is used to handle the hardware of
computer.
 Mainly two type of software are available.

I) System Software
II) Application Software
SYSTEM SOFTWARE
 System software is designed to operate the
computer hardware.
 It is also provide platform for running application
software.
 Types of system software:

 Operating system

 System support software

 System developmentsoftware
OPERATING SYSTEM
 It is the interaction between hardware and
software.
 Ex: DOS, Windows-XP,10,7, VISTA, LINUX,
UNIX…
 System Support Software:
 ∙ It mange the hardware more efficiently.

 ∙ Ex: Drivers of the I/O devices, Antivirus


software's.
 ∙ Driver is a one type of interfacing program
which can interacts between I/O devices and O.S.
SYSTEM DEVELOPMENT SOFTWARE

 It provides the environment to user to develop


 application software's.
 ∙ Ex: Editor: It is used to create the programs and
 modify the programs.
 ∙ Pre-processor: It is used before translators (compilers,
editors), which is used to replace some segments of the
 code with some another segment.
 ∙ Compilers: It is the software which translates high level
programs into low level programs.
 ∙ Interpreters: It is the software which translates line high
 level programs into low level programs.
 ∙ Loaders: It is the software which can load object codes into
main memory and execute it.
APPLICATION SOFTWARE

 Application software is designed to perform specific


user applications. There are two categories of
application software.
I) General-purpose software
II) Specific-purpose software
 General-purpose software:
 Microsoft office, Oracle
 Specific-purpose software:
 Tax calculation software, Pay-roll system, banking
software’s etc.
HARDWARE
 Hardware is the physical component which can
be seen and touched. Hardware is divided into
three parts:
 ▪ Microprocessor

 ▪ Motherboard

 ▪ Other peripherals

 Example: Monitor Mouse, CPU, and Printer.


TYPES OF LANGUAGE
 There are two types of language.
1. Low level language
2. High level language
1. Low level language:
Low level language is divided into two types:
∙ Machine level language
∙ Assembly level language
 Machine level language:
 o The Machine language is written using binary language
(0’s and 1’s). o Computer can understand only low level
language. So there is no need to convert this language.
 o Low level languages are faster.
 o Machine Level language is also known as Binary
Language and Low Level language.
MACHINE LEVEL LANGUAGE
 Advantages:
 Binary language is faster as compared to any
other language.
 There is no need of translator.

 Disadvantages:

 As all the instruction and data are in 0’s and 1’s


form, so it is very difficult to remember as
compared to all other language.
ASSEMBLY LEVEL LANGUAGE
 As binary language is difficult to remember,
assembly language is introduced. In this language
all the instruction of 1’s and 0’s form are converted
into symbols, this symbols are known as
mnemonics.
 But computer cannot understand assembly
language, so we need to convert this language into
binary language.
 The translator which is used to convert assembly
language into binary language is
ASSEMBLY LEVEL LANGUAGE
 Advantages:
It is easy to remember as compared to binary
language.
 Disadvantages:
We need to convert this language into binary, so
speed is slow as compared to binary language
HIGH LEVEL LANGUAGE
As assembly language is platform independent, to overcome
this problem high level language is introduce.
 High level language is made up with A-Z, a-z, 0-9 and
mathematical symbols. But computer can’t understand
high level language; need to convert this language into
binary language.
 To convert high level language into binary language two
types of translator are used.
a. Compiler b. Interpreter
 Compiler:
∙ It is used to convert high level language into binary
language.
∙ It converts whole source code into binary language at a
time.
HIGH LEVEL LANGUAGE
∙ It is faster than interpreter.
∙ Error detection is difficult to identify as compared to interpreter.
interpreter.
 It is also used to convert high level language into binary
language.
 ∙ It converts source code into object code (binary language) as
line by line. ∙
 It is slower as compared to compiler.
 ∙ Error detection is easy as compared to compiler.
FLOW CHART

 A flowchart is a graphical representation of


sequence of operations to be performed to get the
solution of the problem.
 Once the flowchart is drawn, it becomes easy to
write the computer program using any high level
language like C.
FLOW CHART
FLOW CHART TO FIND MULTIPLICATION OF THREE
NUMBERS
FLOWCHART FIND THE LARGEST AMONG
TWO NUMBERS.
FLOWCHART FOR WHETHER GIVEN NO IS
ODD OR EVEN
FLOWCHART FOR FINDOUT AREA OF
CIRCLE
ALGORITHM

 An algorithm is just a detailed sequence of


simple steps that are needed to solve a problem.
An algorithm consists of a set of explicit and
finite steps which when carried out for a given
set of initial conditions, produced the
corresponding output and terminate in a fixed
amount of time.
ALGORITHM

 Features of Algorithm:
 Finiteness: Algorithm must have finite steps.

 Definiteness: Each step must be clear.

 Effectiveness: Each step must be effective.

 Input: Algorithm can have multiple inputs.

 Output: Output of algorithm must be one.


WRITE AN ALGORITHM TO FIND
MULTIPLICATION OF THREE NUMBERS.

Step 1: Read the value of no1


Step 2: Read the value of no2
Step 3: Read the value of no3
Step 4: Calculate multiplication of three numbers
by answer = no1 * no2 * no3
Step 5: Print the answer
Step 6: Stop
ALGORITHM FOR WHETHER GIVEN NO IS
ODD OR EVEN
FIND MAXIMUM NUMBER FROM GIVEN TWO
NUMBER
DIFFERENCE BETWEEN ALGORITHM AND
FLOWCHART
CHAPTER-2
FUNDAMENTALS OF C
SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE
 Features of C language,
 structure of C Program,

 comments, header files,

 data types, constants and variables

 operators

 evaluation of expressions

 type conversion

 I/O functions
FEATURES OF C
Easy to learn
Structured programming language
Efficient programs can be developed
It can handle low level activities like assembly
language program.
It is portable. It can be compiled on a variety of
computer platforms
Programs are developed quickly by using built-in
functions
HISTORY
 C is a general-purpose programming language initially
developed by Dennis Ritchie between 1969 and 1973 at
Bell Labs. C is a robust language whose rich set of
built-in functions and operators can be used to write
any complex program. C is one of the most widely used
programming languages of all time.
STRUCTURE OF C PROGRAM
Documentation section
 This section consists of a set of comment lines giving
the name of the program, and other details.
 In which the programmer would like to user later.

 Ex:- /*………………………*/ or //

Link Section
 Link section provides instructions to the compiler to
link functions from the system library.
 Header files that are required to execute a C
program are included in this section
COMPILATION AND EXECUTION OF C
PROGRAM

 Compilation and Execution of C program

1. Creating the program


2. Compiling the Program
3. Linking the Program with system library
4. Executing the program
DATA TYPES IN C

 Data types specify how we enter data into our


programs and what type of data we enter. C
language has some predefined set of data types to
handle various kinds of data that we can use in
our program. These data types have different
storage capacities.
int

char

float
 Primary data types:
These are fundamental data types in C namely
integer(int), floating point(float), character(char)
and void.
 Derived data types:

Derived data types are nothing but primary datatypes


but a little twisted or grouped together
like array, stucture, union and pointer.

Data type determines the type of data a variable will


hold. If a variable x is declared as int. it means x can hold
only integer values. Every variable which is used in the
program must be declared as what data-type it is.
INTEGER TYPE
 Integers are used to store whole numbers.
 Size and range of Integer type on 16-bit machine:
 int id, age;
FLOATING POINT TYPE

 Floating types are used to store real numbers.


 Size and range of Integer type on 16-bit
machine
CHARACTER TYPE

 Character types are used to store characters


value.
 Size and range of Integer type on 16-bit
machine
VOID TYPE

 void type means no value. This is usually used to


specify the type of functions which returns
nothing. We will get acquainted to this datatype
as we start learning more advanced topics in C
language, like functions, pointers etc.
C TOKENS
KEYWORDS
 Keywords are predefined, reserved words in C and
each of which is associated with specific features.
These words help us to use the functionality of C
language. They have special meaning to the compilers.
 There are total 32 keywords in C
IDENTIFIERS

 Each program element in C programming is known as


an identifier. They are used for naming of
variables, functions, array etc. These are user-
defined names which consist of alphabets, number,
underscore „_‟. Identifier‟s name should not be same
or same as keywords. Keywords are not used as
identifiers.
 Rules for naming C identifiers −
 It must begin with alphabets or underscore.
 Only alphabets, numbers, underscore can be used, no
other special characters, punctuations are allowed.
 It must not contain white-space.
 It should not be a keyword.
 It should be up to 31 characters long.
VARIABLES:
 An entity that may vary during program execution is
called a variable. Variable names are names given to
locations in memory. These locations can integer, real
or character constants.
 All the variables that are used in the program should
be declared i.e. typed at the top with their respective
data types.
 The variable declaration tells two things:
a) It tells the compiler the name of the variable.
b) It also tells the type of value the variable will hold.
 Eg: int a;
float b;
char c;
Here a is an integer variable, b is a float variable and
c is a character variable. is called as termination
symbol or end of statement.
STRINGS

 A string is an array of characters ended with a


null character(\0). This null character indicates
that string has ended. Strings are always
enclosed with double quotes(“ “).
 Let us see how to declare String in C language −

 char string[20] = {„s‟,‟t‟,‟u‟,‟d‟,‟y‟, „\0‟};

 char string[20] = “demo”;

 char string [] = “demo”;


CONSTANTS:-
 In C there are 4 types of constants:
 a) Integer constants: – They are a sequence of digits.
 There are three types of integers:
decimal ,octal, hexadecimal.
i)Decimal numbers contain set of digits 0 to 9 which can be
positive (+) or negative (-).
E.g.: 6, 46, 398, 658736, -89, +598 are all integers

ii)Spaces, comma or special symbols are not allowed.


E.g.: 12 897, 364, 897, $56, 78@56 are all invalid or wrong
numbers.
iii)Octal numbers consist of any combination of digits from 0 to
7, with a leading 0.
E.g.: 037, 0435, 0551.

iv)Hexadecimal numbers has 16 digits 0 to 9 and alphabets A


to F (10-15), the sequence of digits is preceded by 0x or 0X.
E.g.: 0X2, 0x9f, 0xbcd.
 b) Floating or Real constants: – Integer
constants are not sufficient to represent all the
Integer constants are not sufficient to represent
all the quantities such as price, distance,
temperature, etc. These numbers have decimal
point (.)
[Link] parts like 65.987, 0.000569, 89.36.
 A floating number can also be represented as
exponential or scientific notation for e.g.
0.0000123 can be written as 1.23*10 -5 or 1.23e-
05.
 c) Character constants: – A single character alphabets in
uppercase („A‟ to „Z‟ ) or lowercase („a‟ to „z‟) or digits (0 to 9) or a
special symbol@,#,$,%,*,&, +, -, ., :, / etc.) which are enclosed in
single quotes („ ‟).
 E.g.: „a‟ or „A‟ or „7‟ or „+‟ are all character constants.
Note: all escape sequences are also considered characters.
 d) String constants: – A string constant is a single character
or a group of characters enclosed in double quotes (“ “).
 Like “hello”, “4598”, “hello235”, “5+3”.
 Note: The character constant „7‟ is not the same as digit 7.
Every character constants has an equivalent integer number.
„A‟ to „Z‟ has ASCII 65 to 90. i.e. „A‟ has ASCII 65 „B‟ has ASCII
66 and so on.
„a‟ to „z‟ has ASCII 97 to 122
„0‟ to „9‟ has ASCII 48 to 57
„ „ (space) has ASCII 32.
( smiling space) has ASCII 1.
Enter has ASCII 13
Esc has ASCII 27
C – OPERATORS AND EXPRESSIONS

 The symbols which are used to perform logical


and mathematical operations in a C program are
called C operators.
 These C operators join individual constants and
variables to form expressions.
 Operators, functions, constants and variables are
combined together to form expressions.
 Consider the expression A + B * 5. where, +, * are
operators, A, B are variables, 5 is constant and A
+ B * 5 is an expression.
TYPES OF C OPERATORS:

 C language offers many types of operators.


They are,
 Arithmetic operators

 Assignment operators

 Relational operators

 Logical operators

 Bit wise operators

 Conditional operators (ternary operators)

 Increment/decrement operators

 Special operators
ARITHMETIC OPERATORS IN C:

 C Arithmetic operators are used to perform


mathematical calculations like addition,
subtraction, multiplication, division and modulus
in C programs.
ASSIGNMENT OPERATORS IN C:

 In C programs, values for the variables are


assigned using assignment operators.
 For example, if the value “10” is to be assigned
for the variable “sum”, it can be assigned as “sum
= 10;”
 There are 2 categories of assignment operators in
C language. They are,
1. Simple assignment operator ( Example: = )
2. Compound assignment operators (
Example: +=, -=, *=, /=, %=, &=, ^= )
RELATIONAL OPERATORS IN C:
 Relational operators are used to find the relation
between two variables. i.e. to compare the values
of two variables in a C program.
LOGICAL OPERATORS IN C:

 These operators are used to perform logical


operations on the given expressions.
 There are 3 logical operators in C language. They
are,
 logical AND (&&),

 logical OR (||)

 logical NOT (!).


BIT WISE OPERATORS IN C:

 These operators are used to perform bit


operations. Decimal values are converted into
binary values which are the sequence of bits and
bit wise operators work on these bits.

 Bit wise operators in C language are


 & (bitwise AND),
 | (bitwise OR),
 ~ (bitwise NOT),
 ^ (XOR),
 << (left shift) and
 >> (right shift).
SHIFT OPERATORS IN C PROGRAMMING
 There are two shift operators in C programming:
1)Right shift operator 2)Left shift operator.
 Right Shift Operator
 Right shift operator shifts all bits towards right by
certain number of specified bits. It is denoted by >>.
LEFT SHIFT OPERATOR
 Left shift operator shifts all bits towards left by a
certain number of specified bits. The bit positions that
have been vacated by the left shift operator are filled
with 0. The symbol of the left shift operator is <<.
CONDITIONAL OPERATOR

 (condition) ? expression1 : expression2


If the condition is true then expression1 is executed
else expression2 is executed.

 x > y ? puts("x is greater") : puts("y is greater");


 Else puts( x > y ? "x is greater" : "y is greater");
INCREMENT / DECREMENT OPERATOR

 C provides an increment operator ++ and decrement


operator --.
 The functionality of ++ is to add 1 unit to the operand and --
is to subtract 1 from the operand.
 ++ a;---is equivalent to a = a + 1
 -- b;--- is equivalent to b = b - 1.
 There are two kinds of increment and decrement operator
i.e prefix and postfix.
 If the operator is used before the variable
i.e ++a then it is called prefix increment operator.
In the prefix operator, first 1 is added and then the value is
assigned to the variable.
 If the operator is used after variable
i.e a++ then it is called postfix increment operator.
In postfix operator, first the value is assigned then only 1 is
added and the added value is assigned
#include <stdio.h>
int main()
{
int i;
i = 4;
printf( "%d\n", i );
printf( "%d\n", i++ ); //post increment
printf( "%d\n\n", i );
i = 4;
printf( "%d\n", i );
printf( "%d\n", ++i ); //preincrement
printf( "%d\n", i ); return 0;
}
 Output
445
455
SPECIAL OPERATORS

 The Comma Operator


 Type cast Operator

 Reference operator or Address Operater ("&")

 Dereference operator ("*") or Pointer Operater

 Double Pointer operator ("**")

 sizeof operator
THE COMMA OPERATOR

 The Comma operator can be used to link the


related expressions together.
 Example For Comma Operator

 Comma Operator In for Loops


for(i=0,j=1;i>10:i++,j++)
 Comma Operator In while Loops

While(c<10,c--)
TYPE CAST OPERATOR
 Syntax:
( type )Explanation
 converts a to the specified type.

 Note that the use of a parenthesized type in a method


declaration or definition is not an example of the use
of the type cast operator.
 Example For Type Cast Operator

float s= 12.5; int a;


a = (int) s;
now a value is 12.
REFERENCE OPERATOR OR ADDRESS OPERATER
("&")

 The reference operator noted by ampersand ("&"), is


also a unary operator in c languages that uses for
assign address of the variables. It returns the pointer
address of the variable. This is called "referencing"
operater.
 Syntax

data_type x;
data_type *pt;
pt = &x
DEREFERENCE OPERATOR ("*") OR POINTER
OPERATER

 The dereference operator or indirection operator,


noted by asterisk ("*"), is also a unary operator in c
languages that uses for pointer variables.
 It operates on a pointer variable, and returns l-value
equivalent to the value at the pointer address. This is
called "dereferencing" the pointer.
 data_type *pt;

Double Pointer operator ("**")


 Double Pointer is, that double pointer points
to another pointer variable address.
 data_type **pt;
SIZEOF OPERATOR

 sizeof returns the size of a variable or datatype


 sizeof (data_type)

#include <stdio.h>
int main()
{
int a,float b, double c, char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}
Output:
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
EXPRESSION EVALUATION
 In c language expression evaluation is mainly depends on
priority and associatively.
 An expression is a sequence of operands and operators
that reduces to a single value. For example, the
expression, 10+15 reduces to the value of 25.
An expression is a combination of variables constants and
operators written according to the syntax of C language.
every expression results in some value of a certain type
that can be assigned to a variable.
 Priority
 This represents the evaluation of expression starts from
"what" operator.
 Associativity
 It represents which operator should be evaluated first if
an expression is containing more than one operator with
same priority.
TYPES OF EXPRESSION EVALUATION IN C
 Based on the operators and operators used in the expression,
they are divided into several types. Types of Expression
Evaluation in C are:
 Integer expressions – expressions which contains integers
and operators
 Real expressions – expressions which contains floating
point values and operators
 Arithmetic expressions – expressions which contain
operands and arithmetic operators
 Mixed mode arithmetic expressions – expressions which
contain both integer and real operands
 Relational expressions – expressions which contain
relational operators and operands
 Logical expressions – expressions which contain logical
operators and operands
 Assignment expressions and so on… – expressions
which contain assignment operators and operands
TYPE CONVERSIONS

 Converting one data type into another data type is


called type casting. Whenever we assign a value to a
variable using assignment operator, the compiler
checks for uniformity and hence the data types at both
sides should be same, if the data types are not same
then we should convert the types to become same at
the both sides.
 To convert the data type we use “cast operator” cast
operator means writing the data types between the
simple braces before a variable whose value is to be
converted. This can be done in 2 ways,
 1. Implicit type conversion
 2. Explicit type conversion
IMPLICIT TYPE CONVERSION
 In this the data type /Variable of lower type (which
holds lower range of values or has lower precision) is
converted to a higher type (which holds higher range
of values or has high precision). This type of
conversion is also called “promotion”.
 If a “char” is converted into “int” it is called as
internal promotion.
 Example :
int i;
char c;
c=‟A‟;
i=c;
EXPLICIT TYPE CONVERSIONS
 This means converting a higher data type to lower data
type, When we want to convert a type forcibly in a way
that is different from automatic type conversion, we need
to go for explicit type conversion.
 Syntax :
 (type name) expression;
 Type name is one of the standard data type. Expression
may be a constant variable or an expression this process of
conversion is called as casting a value.
 Example :
float f=12.50;
int i;
i= (int) f;
INPUT AND OUTPUT FUNCTIONS
 C provides a collection of library functions such
as getchar, putchar, scanf, printf, gets and puts.
 These functions enable the transfer of data between the C
program and standard input/output devices
 The standard input-output devices or the associated files or text
streams, are referred as -
stdin - standard input file, normally connected to the keyboard
stdout - standard output file, normally connected to the
screen/console
stderr - standard error display device file, normally connected to
the screen/console
 In order to be able to use the above mentioned input-output
functions in your C program, you must begin each C program with
a pre-processor directive to include these standard library
functions.
 This can be done with a line entry - #include <stdio.h>.
PRINTF() FUNCTION :

 The printf() function is used for output. It prints the


given statement to the console.
 The general form of printf() function is given below :

 Syntax :

 printf("format string", list of variables);

 Example :

 printf(“%d %d”,a,b);
SCANF() FUNCTION :

 This function is used to read values using keyboard. It is


used for runtime assignment of variables.
 Syntax :
scanf("format string", list_of_addresses_of_Variables );
The format string contains - Conversion specifications
that begin with % sign
 Example :
scanf(“%d %f %c”, &a, &b, &c);

 “ & ” is called the address operator, in scanf( ) the “ & ”


operator indicates the memory location of the variable. So
that the value read would be placed at that location.
GETCHAR() & PUTCHAR() FUNCTIONS

 The getchar() function reads a character from the


terminal and returns it as an integer.
 This function reads only single character at a
time. You can use this method in a loop in case
you want to read more than one character.
 The putchar() function displays the character
passed to it on the screen and returns the same
character.
 This function too displays only a single character
at a time. In case you want to display more than
one characters, use putchar() method in a loop.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
/* Take a character as input and store it in variable c */
c = getchar();
/* display the character stored in variable c */
putchar(c);
}
GETS() & PUTS() FUNCTIONS
 gets() : Reads characters from the standard input and stores them
as a string.
 puts() : prints characters from the standard [Link] like printf
statement.
 gets(char_array_variable);
 puts(char_array_variable/string);
 to stdout.
#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
CHAPTER-3
CONTROL STRUCTURE IN C
SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE

•Decision making statements


•Looping statements
• Nesting of control structures
•break and continue
•goto statement
1. DECISION MAKING

 Decision making is used


to specify the order in
which statements are
executed.

• Decision making in a C program using:


• if statement
• if…else statement
• if…else if…else statement
• nested if...else statement
• Switch case Statement
1.1 SIMPLE IF STATEMENT

if (testExpression)
{
/ / statements
}
1.2 IF...ELSE STATEMENT
 The if...else statement executes some code if the test
expression is true (nonzero) and some other code if the test
expression is false (0).

Syntax of if...else
if (testExpression) {
// codes inside the body of if
}else {
// codes inside the body of else
}
EXAMPLE: IF...ELSE STATEMENT
// Program to check whether an integer entered by the user is odd or even
#include <stdio.h>
void main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);

// True if remainder is 0

if( number%2 == 0 )

{
printf("%d is an even integer.",number); }
else{
printf("%d is an odd integer.",number);}
}
1.3 IF...ELSE IF....ELSE STATEMENT

 The if...else statement executes two different codes


depending upon whether the test expression is true or false.
Sometimes, a choice has to be made from more than 2
possibilities.

 The if...else if…else statement allows you to check for


multiple test expressions and execute different codes for
more than two conditions.
SYNTAX OF IF...ELSE IF....ELSE STATEMENT.

if (testExpression1) {

// statements to be executed if testExpression1 is true

} else if(testExpression2) {
// statements to be executed if testExpression1 is false and
testExpression2 is true

} else if (testExpression 3) {
// statements to be executed if testExpression1 and
testExpression2 is false and testExpression3 is true

} else {

// statements to be executed if all test expressions are false

}
EXAMPLE: IF...ELSE IF....ELSE STATEMENT

/ / Program to relate two integers //checks if number1 is greater than


using =, > or < #include number2.
<stdio.h> int main(){ else if (number1 > number2) {
int number1, number2; printf("Result: %d > %d",
printf("Enter two integers: "); number1, number2);
}
// if both test expression is
scanf("%d %d", &number1,
&number2); false else {
//checks if two integers are printf("Result: %d < %d",
equal. number1, number2);
if(number1 = = number2){ }
printf("Result: %d = %d“, return 0;
number1,number2); }
}
1.4 NESTED IF ELSE STATEMENT

 Nested if else statement is same like if else


statement, where new block of if else statement is
defined in existing if or else block statement.

 Used when user want to check more than one


conditions at a time.
SYNTAX OF NESTED IF ELSE STATEMENT

if(condition is true){
if(condition is true){
statement;
}else{
statement;
}
}else{
statement;
}
FLOWCHART
EXAMPLE OF NESTED IF ELSE STATEMENT

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


char username;
int password;

printf("Username:");
scanf("%c",&username);
printf("Password:");
scanf("%d",&password);

if(username=='a'){
if(password==12345){

printf("Login successful");
}else{
printf("Password is incorrect, Try again.");
}
}else{
printf("Username is incorrect, Try again.");
}
}
THE “ELSE – IF” LADDER

 This is another way of putting if‘s together when


multiple decisions are involved. A multipath decision
is a chain of if‘s in which the statement associated
with each else is an if. Hence it forms a ladder called
else–if ladder.
 if else-if, statement is used to execute one code from
multiple conditions.
SYNTAX
FLOWCHART
2. LOOPS
•Why use loops in c language :
•Suppose you want to execute some code/s 10 times. You
can perform it by writing that code/s only one time and
repeat the execution 10 times using loop.
For example: Suppose that you have to print table of 2
then you need to write 10 lines of code, by using loop
statements you can do it by 2 or 3 lines of code only.

•Loop :
•A loop is defined as a block of statements which are
repeatedly executed for certain number of times.
•In other words it iterates a code or group of code many
times.

TYPES OF LOOPS
 There are three loops in C programming:

o while loop

o do...while loop

o for loop
 Depending upon the position of a control
statement in a program, looping in C is classified
into two types:
 1. Entry controlled loop

 2. Exit controlled loop

 In an entry controlled loop, a condition is


checked before executing the body of a loop. It is
also called as a pre-checking loop.
 In an exit controlled loop, a condition is
checked after executing the body of a loop. It is
also called as a post-checking loop.

2.2 WHILE LOOP
•The while is an entry-controlled loop statement.
•The test condition is evaluated and if the condition is
true, then the body of the loop is executed.
•The execution process is repeated until the test condition
becomes false and the control is transferred out of the
loop.
•On exit, the program continues with the statement
immediately after the body of the loop.
•The body of the loop may have one or more statements.
•The braces are needed only if the body contains two or
more statements.
•It’s a good practice to use braces even if the body has
only one statement.
2.2 WHILE LOOP

Syntax :
Initialization Expression;
while ( Test Condition)
{
Body of the loop
Updation Expression
}
EXAMPLE: WHILE LOOP
#include <stdio.h>

int main()
{
// initialization expression
int i = 1;

// test expression
while (i < 6) {
printf("Hello World\n");

// update expression
i++;
}

return 0;
}
2.3 DO...WHILE LOOP

•To execute a part of program or code several


times, we can use do-while loop of C language.
The code given between the do and while block
will be executed until condition is true.
•The do-while is an exit-controlled loop
statement. Because, in do-while, the condition
is checked at the end of the loop.
•The do-while loop will execute at least one time
even if the condition is false initially.
•The do-while loop executes until the condition
becomes false.
DO...WHILE LOOP SYNTAX
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1;

do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}
while(num<=10);
return 0;
}
EXAMPLE: DO...WHILE LOOP
// Program to add numbers until user enters zero
#include <stdio.h>
int main()
{
Int number, sum = 0;
// loop body is executed at least once
Do
{
printf("Enter a number: ");
scanf("%d", &number);
sum += number;
}
while(number != 0);
printf("Sum = %.",sum);
return 0;}
2.4 NESTED WHILE LOOPS (CON)

 Syntax while loop

while(condition) {

while(condition) {
statement(s);
}

statement(s);
}
2.4 NESTED DO WHILE LOOPS
Using do-while loop within do-while loops is said to be nested do
while loop.

 Syntax do while loop

do {

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

}while( condition );
2.1 FOR LOOP
the for loop works well where the number of iterations of the loop
is known before the loop is entered. The head of the loop consists
of three parts separated by semicolons.
The first is run before the loop is entered. This is usually the
initialization of the loop variable.
The second is a test, the loop is exits when this returns false.
The third is a statement to be run every time the loop body is
completed. This is usually an increment of the loop counter.
The 3 actions are

Syntax :
for (initialize expression; test condition; updation )
{
Statement-1;
Statement-2;
}
FOR LOOP

(i)The initialization sets a loop to an initial value. This statement


is executed only once.
(ii) The test condition is a relational expression that determines
the number of iterations desired or it determines when to exit
from the loop.
For loop continues to execute as long as conditional test is
satisfied.
When the condition becomes false the control of the program
exits from the body of for loop and executes next statements
after the body of the loop.
(iii) The updation (increment or decrement operations) decides
how to make changes in the loop.
The body of the loop may contain either a single statement or
multiple statements.
FOR LOOP FLOWCHART
EXAMPLE: FOR LOOP

// Program to calculate the sum of / / for loop terminates when n is less


first n natural numbers than count
// Positive integers 1,2,3...n are for(count = 1; count <= n; ++count)
known as natural numbers {
sum += count;
#include <stdio.h> int main(){ }
int n, count, sum = 0; printf("Sum = %d", sum); return 0;
printf("Enter a positive integer: "); }
scanf("%d", &n);
NESTED “FOR” LOOP :
We can also use loop within loops.
i.e. one for statement within another for statement is
allowed in C.
In nested for loops one or more for statements are
included in the body of the loop.
•ANSI C allows up to 15 levels of nesting. Some
compilers permit even more.
Syntax :
for( initialize ; test condition ; updation) /* outer loop */
{
for(initialize ; test condition ; updation) /* inner loop */
{
Body of loop;
}
}
3.1 BREAK STATEMENT
break statement comes under decision-making statement,
its most oftenly using in looping.
One can use the break statement to break out from a loop or switch
statement. When break is executed within a loop, the loop ends
immediately, and execution continues with the first statement
following the loop.

C Break Statement
The word break is a keyword that terminates the execution of the
loop or the control statement and the control is transferred to the
statement immediately following it.
The break statement is mostly used in switch control statement.
Syntax:
break;
FLOWCHART OF BREAK STATEMENT
HOW BREAK STATEMENT WORKS?
CONTINUE STATEMENT
The continue statement enables you to skip to the next iteration
in the loop containing the continue statement. The labeled continue
statement enables you to skip to the next iteration in an outer loop
enclosing the labeled continue that is identified by the label. The
labeled loop need not be the loop immediately enclosing the
labeled continue.

C Continue Statement

•The continue statement is exactly opposite to the break statement.


•The loop does not terminate when a continue statement is
encountered.
•Instead, the continue statement skips that particular iteration.
•The continue statement is also called as bypass statement.
FLOWCHART OF CONTINUE STATEMENT
HOW CONTINUE STATEMENT WORKS?
EXAMPLE: CONTINUE STATEMENT

/ / Program to calculate sumof / / If user enters negative


maximum of 10 numbers number, loop is terminated
/ / Negative numbers areskipped if(number < 0.0) {
from calculation
continue;
# include <stdio.h> int
}
main(){
/ / sum = sum + number;
int i; sum + = number;
double number, sum = 0.0;
}
for(i=1; i <= 10; ++i) { printf("Sum = %.2lf",sum);
printf("Enter a n%d: ",i); return 0;
scanf("%lf",&number);
}
4. SWITCH...CASE STATEMENT
 The if...else if…else statement allows you to execute a block code
among many alternatives. If you are checking on the value of a single
variable in if...else if…else statement, it is better to use switch
statement.

 The switch statement is often faster than nested if...else (not always).
Also, the syntax of switch statement is cleaner and easy to understand.
SYNTAX OF SWITCH...CASE

switch (n){
case constant1:
// code to be executed if n is equal to constant1; break;
case constant2:
// code to be executed if n is equal to constant2; break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
SWITCH STATEMENT FLOWCHART
GOTO STATEMENT

 The goto statement is used to alter the normal sequence of a C


program.
SYNTAX OF GOTO STATEMENT
C programming introduces a goto statement by which
you can jump directly to a line of code within the same
file.
Syntax And Facts
The goto statement does not require any condition.
The goto statement simply passes control anywhere in a
program without testing any condition.

goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
WHAT IS LABEL?

 The label is an identifier. When goto statement is encountered,


control of the program jumps to label: and starts executing the code.
EXAMPLE: GOTO STATEMENT
/ / Program to calculate the sum and average of maximum of 5 numbers

previously entered positive number is displayed

/ / If user enters negative number, the sum and average of


# include <stdio.h>
int main()
{
const int maxInput = 5;
int i;
double number, average, sum=0.0;
for(i=1; i<=maxInput; ++i)
{
printf("%d. Enter a number: ", i);
scanf("%lf",&number);
EXAMPLE: GOTO STATEMENT
// If user enters negative number, flow of program moves to label
ju
mp
if(number < 0.0)
goto jump;

sum += number; // sum = sum+number;


}
jump:

average=sum/(i-1);
printf("Sum = %.2f\n", sum); printf("Average = %.2f", average); return 0;
}
CHAPTER-4
ARRAY & STRING
SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE

• Concepts of array
• one and two dimensional arrays
•declaration and initialization of arrays
• string
• string storage
• Built-in string functions
1. CONCEPTS OF ARRAY
•An array is a fixed-size sequenced collection of elements of the
same data type.
• An array is derived data type.
•The individual element of an array
•Every element is referred by their index or subscript value.
•The subscript for an array always begins with 0.
Syntax
data_type array_name [size];
Example
int marks [5]

•The data_type specifies the type of the elements that can be


stored in an array, like int, float or char.
•The size indicates the maximum number of elements that can
be stored inside the array.
1. CONCEPTS OF ARRAY
Advantages :

• You can use one name to store many values with different
indexes.
•An array is very useful when you are working with sequences of
the same kind of data.
•An array makes program easier to read, write and debug.

Disadvantages:

• Wastage of memory space.


• Array is static structure. It means that array is of fixed size We
cannot change size of array at the run time.
• It can store only similar type of data.
• Sometimes it is not easy to operate with many index arrays.
1. CONCEPTS OF ARRAY
Program to take 5 values from the user and store them in an array // Print the elements stored in the array

#include <stdio.h>
void main()
{
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i)
{
printf("%d\n", values[i]);
} }
1. CONCEPTS OF ARRAY

Types of an array
ONE DIMENSIONAL ARRAY

 A list of items can be given one variable name using


only one subscript and such a variable is called a
single – subscripted variable or a one – dimensional
array.
 Declaration of One-Dimensional Arrays :

 Like any other variables, arrays must be declared


before they are used. The general form of array
declaration is
 Syntax :

 <data type> <array name>[sizeofarray];

 The data type specifies the type of element that will


be contained in the array, such as int, float, or char.
 The size indicates the maximum number of elements
that can be stored inside the array.
ONE DIMENSIONAL ARRAY

 For example :
 int age[5];

 Here, the name of array is age. The size of array


is 5, i.e., there are 5 items (elements) of array
age. All elements in an array are of the same
type (int, in this case).
 Array elements :

 Size of array defines the number of elements in


an array. Each element of array can be accessed
and used by user according to the need of
program.
ONE DIMENSIONAL ARRAY
 For example :
 int age [5];

•Note that, the first element is numbered 0 and so on.


•Here, the size of array age is 5 times the size of int because there
are 5 elements.
•Suppose, the starting address of age [0] is 2120d and the size of
int be 2 bytes. Then, the next address (address of a [1]) will be
2122d, address of a [2] will be 2124d and so on.
INITIALIZATION OF ONE-DIMENSIONAL
ARRAY

 After an array is declared, its elements must be


initialized. Otherwise they will contain “garbage”.
We can initialize the elements of arrays in the same
way as the ordinary variables when they are
declared.
 The general form of initialization of array is .

 Syntax :

 datatype array_name[size] = { list of values };


INITIALIZATION OF ONE-DIMENSIONAL
ARRAY

 The values in the list are separated by commas.


 You can initialize array in C either one by
one or using a single statement as follows :
 int age[5]={2,6,34,5,1};

 It is not necessary to define the size of arrays


during initialization.
 int age[]={2,6,34,5,1};

 In this case, the compiler determines the size of


array by calculating the number of elements of
an array.
INITIALIZATION ARRAY

 The different types of initializing arrays:


1. At Compile time

(i) Initializing all specified memory locations.


(ii) Partial array initialization
(iii) Initialization without size.
(iv) String initialization.

2. At Run Time
 1. Compile Time Initialization
We can initialize the elements of arrays in the same
way as the ordinary variables when they are declared.
The general form of initialization of arrays is
type array-name[size]={ list of values};
(i) Initializing all specified memory locations:- Arrays
can be initialized at the time of declaration when their
initial values are known in advance. Array elements
can be initialized with data items of type int, char etc.
Ex:- int a[5]={10,15,1,3,20};
During compilation, 5 contiguous memory locations
are reserved by the compiler for the variable a and all
these locations are initialized as shown in figure.
 (ii) Partial array initialization:- Partial array
initialization is possible in c language. If the
number of values to be initialized is less than the
size of the array, then the elements will be
initialized to zero automatically.
 Ex:- int a[5]={10,15};

 Eventhough compiler allocates 5 memory


locations, using this declaration statement; the
compiler initializes first two locations with 10
and 15, the next set of memory locations are
automatically initialized to 0's by compiler as
shown in figure
Initialization with all zeros:-
 Ex:- int a[5]={0};

(iii) Initialization without size:- Consider the declaration along with


the initialization. Ex:- char b[]={'C','O','M','P','U','T','E','R'}; In this
declaration, eventhough we have not specified exact number of
elements to be used in array b, the array size will be set of the total
number of initial values specified. So, the array size will be set to 8
automatically. The array b is initialized as shown in figure.
 (iv) Array initialization with a string: -Consider
the declaration with string initialization.
 Ex:- char b[]="COMPUTER";

 The array b is initialized as shown in figure.


 Eventhough the string "COMPUTER" contains 8
characters, because it is a string, it always ends
with null character. So, the array size is 9 bytes
(i.e., string length 1 byte for null character).
 Ex:- char b[9]="COMPUTER"; // correct char
b[8]="COMPUTER"; // wrong
RUN TIME INITIALIZATION

 2. Run Time Initialization


 An array can be explicitly initialized at run time.
This approach is usually applied for initializing
large arrays.
 Ex:- scanf can be used to initialize an array.

 int x[3];

 scanf(“%d%d%d”,&x[0],&x[1],&x[2]);

 The above statements will initialize array


elements with the values entered through the
key board. (Or)
RUN TIME INITIALIZATION
PROGRAM TO FIND THE AVERAGE OF N NUMBERS USING ARRAYS

#include <stdio.h>
void main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum
variable sum += marks[i];
}
PROGRAM TO FIND THE AVERAGE OF N NUMBERS USING ARRAYS

average = sum/n;
printf("Average = %d", average);
}
Output:
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
TWO-DIMENSIONAL ARRAYS
 A variable which represent the list of items using
two index (subscript) is called two-dimensional
array.
 In Two dimensional arrays, the data is stored in
rows and columns format.
 For example: int table[2][3];

 The general form of two dimensional array


declaration is :
data type array-name[row_size][column_size];
TWO-DIMENSIONAL ARRAYS

 float x[3][4];
 Here, x is a two-dimensional (2d) array.

 The array can hold 12 elements.

 the array as a table with 3 rows and each row has


4 columns.
TWO-DIMENSIONAL ARRAYS
 The general form of initializing two-dimensional
array is :
 type array-name[row_size][column_size] = {list of
values};
 Example : int table[2][3] = {0,0,0,1,1,1};

 Here the elements of first row initializes to


zero and the elements of second row initializes to
one.
 This above statement can be written as :

int table[2][3] = {{0,0,0}, {1,1,1}};


 In two-dimensional array the row_size can be
omitted.
TWO-DIMENSIONAL ARRAYS
 Example : int table[ ][3] = {{0,0,0}, {1,1,1}};
 If the values are missing in an initializer, they
are automatically set to zero.
 Example : int table[2][3] = {1,1,2};

 Here first row initialize to 1,1 and 2, and

 second row initialize to 0,0 and 0 automatically.

 In Two dimensional arrays, the data is stored in


rows and columns format.
TWO-DIMENSIONAL ARRAYS
For example: int table[2][3] = {1,2,3,4,5,6};
 The memory layout of above example :

 table[0][0] = 1;

table[0][1] = 2
table[0][2] = 3;
table[1][0] = 4;
table[1][1] = 5;
table[1][2] = 6;
A variable which represent the list of items using more
than two index (subscript) is called multi-
dimensional array.
The general form of multi dimensional array is :
type array-name[s1][s2][s3]…….[sn]
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(“%d”,a[i][j]);
}
}
 Example: int a[3][3] = { {1,1,1}, {1,1,1}, {1,1,1}};

 Total number of elements in two dimensional


array = (row size * column size).
MULTI-DIMENSIONAL ARRAYS
 Where S is the size. Some examples are :
 int survey[3][5][6];

 float table[5][4][5][3];

 Here survey is a three-dimensional array And


table is a four-dimensional array.
#include <stdio.h>
int main(void)
{
int rollno[20],marks[20],i;
for(i=0;i<20;i++)
printf("\n Enter Roll of Student [%d]",i+1);
scanf("%d",&rollno[i]);
printf("\n Enter Mark of Student [%d]",i+1);
scanf("%d",&marks[i]);
}
for(i=0;i<20;i++)
{
printf("\n Roll No : %d Marks : %d",rollno[i],marks[i]);
}
}
APPLICATIONS OF ARRAYS

 Using pointers for accessing arrays.

 Passing arrays as function parameters.

 Arrays as members of structures.

 Using structure type data as array elements.

 Arrays as dynamic data structures.

 Manipulating character arrays and strings


STRING
 String is collection characters. C language does not
have string as a data type so user needs to create array
of characters for storing string value.
 Syntax:

char <string name> [<size>];


char first_name[15]; //declaration of a string variable
 For declaration of string data type must be character.
Here string name represent the name of string that
user want to create. Size define the total number of
characters that user want to store as string. Compiler
automatically supplies a null character („\0‟) at the end
of each string.
READ A STRING

#include <stdio.h>
void main()
{
char name[10];
int age;
printf("Enter your first name and age: \n");
scanf("%s %d", name, &age);
printf("You entered: %s %d",name,age);
}
output:
Enter your first name and age: John_Smith 48
1) COMPILE TIME:

 We can assign or store string at two different levels:


1) Compile Time 2) Run Time

1. Compile time initialization is done during declaration of string.


 Example:

char name[4] = {“abc”};


char name[4] = {„a‟, „b‟, „c‟, „\0‟};
 Compile add null value at the end of string. So size of string is
greater than one to the original size of string value that user
want to store.
char name[] = “VGEC Engineering College”;
char name[3] = “Good” ; //error
char name[5];
name = “Good”; //error
2) RUN TIME:

String can be entered at run time in three different


ways:

1) Using scanf()
2) Using getchar()
3) Using gets()
1) USING SCANF():

 Using %s format specification we can use scanf()


to get string value. But using scanf() we can‟t get
the string with white space character.

 Syntax:
scanf(“%s”, <string name>);

 Note: In case of character array, the ampersand


(&) is not required before variable name.
2) USING GETCHAR():

getchar() is used to get the character value from


user. It reads only one character at a time. So to
read multiple characters or series of characters
need to use loop.

char ch[5];
ch[0] = getchar();
3) USING GETS():

 This function is used to read the entire string


from user.
 Using this function we can enter string with
white space characters.
 It reads the value from user until new line
character is not entered.
 gets() can get only one string at time, scanf() can
get multiple string at time.
EXAMPLE:

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20],ch;
printf("\nenter the value through gets");
gets(str);
printf("\nEntered value through get is %s",str);
printf("\nenter the string through scanf");
scanf("%s",str);
printf("\nEntered value through scanf is :
%s",str);
}
FGETS() AND PUTS()

#include <stdio.h>
int main()
{ char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
DIFFERENT STRING FUNCTION

1) strlen()

2) strcat()

3) strcpy()

4) strcmp()

5) strlwr()

6) strupr()

7) strstr()
1) STRLEN():

This function is used to identify the length of


specified string.
Length means total number of character that a
string contains.
Here n is integer variable, which can store the total
number of
characters.
Argument may be string constant or any string
variable name.
Syntax:
n = strlen(string);
EXAMPLE

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}

Output:
Length of string str1: 13
2) STRCAT():
This function is used to concate or joins the two
strings.
Here string 1 and string 2 both are characters
array.
When this function is executed, string 2 is appended
at the end of string 1.
The null value of string 1 is removed and first
character of string 2 is starts to append from that
position.

Syntax:
strcat(string1, string 2);
EXAMPLE

#include <stdio.h>
#include <string.h>
void main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
}
Output:
string after concatenation: HelloWorld
3)STRCMP():

This function is used to compare two strings.


Syntax:
strcmp(string1, string 2);
It both strings are same then function returns 0, if
string 1 is greater than string 2 then function
returns greater than 0 and if string 1 is smaller
than string 2 then function returns less than 0 value.
Comparison is based on the ASCII value of each
character.
 For example:

strcmp(“their”, “there”);
EXAMPLE
#include <stdio.h>
#include <string.h>
void main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "[Link]";
/* below it is comparing first 8 characters of s1 and s2*/
if (strcmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{ printf("string 1 and 2 are different");
}}

Output:
string1 and string 2 are equal
4) STRCPY():

This function is used to copy one string into another


string.
Syntax:
strcpy(string1, string 2);

It just assigns the value of string 2 to the string 1. If


string 1 contains some value then its value is overwrite
by string 2. It‟s recommended that, size of string 1 is
enough larger to get the value of string 2.
EXAMPLE

#include <stdio.h>
#include <string.h>
void main()
{
char str1[20] = "C programming";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
}
5)STRLWR():

This function is used to convert string into lower


case or small letters.
Syntax:
strlwr(string);

If specified string is in already lower case or small


letters then it remains as it is.
EXAMPLE

#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr(str));
return 0;
}

OUTPUT:
modify this string to lower
6)STRUPR():

This function is used to convert string into small


letter or lower case

Syntax:
strupr(string);
EXAMPLE
#include<stdio.h>
#include<string.h>

void main()
{
char str[ ] = "Modify This String To Upper";
printf("%s\n",strupr(str));

}
 OUTPUT:
 MODIFY THIS STRING TO UPPER
7)STRSTR():

This function is used to find the position of sub


string.
Syntax:
strstr(string1,string2);
This function search string 1 to see whether the
string s2 is contained in string 1.
If string is found then it returns the position of
the first occurrence of the substring. Otherwise it
returns the null.
EXAMPLE
#include <stdio.h>
#include <string.h>
void main()
{
char inputstr[70] = "String Function in C [Link]";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
}
Output string is: [Link]
CHAPTER-5,6
FUNCTION,RECURSION
SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE

Concepts of user defined functions,


prototypes
definition of function
 parameters
parameter passing
calling a function
 recursive function
 Macros
Pre-processing
USER-DEFINED FUNCTIONS
 A function is a block of code that performs a specific task.
 C allows you to define functions according to your need. These
functions are known as user-defined functions. For example:
 Suppose, you need to create a circle and color it depending upon
the radius and color. You can create two functions to solve this
problem:
 createCircle() function
 color() function
 A large C program is divided into basic building blocks called C
function. C function contains set of instructions enclosed by “{ }”
which performs specific operation in a C program. Actually,
Collection of these functions creates a C program.
USES OF C FUNCTIONS:
 C functions are used to avoid rewriting same
logic/code again and again in a program.
 There is no limit in calling C functions to make use of
same functionality wherever required.
 We can call functions any number of times in a
program and from any place in a program.
 A large C program can easily be tracked when it is
divided into functions.
 The core concept of C functions are, re-usability,
dividing a big task into small pieces to achieve the
functionality and to improve understandability of very
large C programs.
 C functions aspects
 syntax

 function definition

Return_type function_name (arguments list)


{ Body of function; }

 function call
function_name (arguments list);

 function declaration
return_type function_name (argument list);
EXAMPLE: USER-DEFINED FUNCTION
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{ int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0; }
int addNumbers(int a, int b) // function definition
{ int result;
result = a+b;
return result; // return statement
}
FUNCTION PROTOTYPE

 A function prototype is simply the declaration of a


function that specifies function's name, parameters
and return type. It doesn't contain function body.
 A function prototype gives information to the
compiler that the function may later be used in the
program
 Syntax of function prototype

 returnType functionName(type1 argument1, type2


argument2, ...);
FUNCTION PROTOTYPE

 In the above example,


 int addNumbers(int a, int b); is the function
prototype which provides the following information
to the compiler:
 name of the function is addNumbers()

 return type of the function is int

 two arguments of type int are passed to the function

 The function prototype is not needed if the user-


defined function is defined before
the main() function.
FUNCTION DEFINITION

 Function definition contains the block of code to


perform a specific task. In our example, adding two
numbers and returning it.
 Syntax of function definition

returnType functionName(type1 argument1, type2


argument2, ...)
{
//body of the function
}
When a function is called, the control of the program is
transferred to the function definition. And, the compiler
starts executing the codes inside the body of a function.
FUNCTION PARAMETER AND CALL

 Pass by Value.
Pass by Value, means that a copy of the data is made
and stored by way of the name of the parameter.
Any changes to the parameter have NO affect on
data in the calling function. Also known as call by
value
 Pass by Reference.

A reference parameter "refers" to the original data


in the calling function. Also known as call by
reference
CALL BY VALUE

 The call by value method of passing arguments


to a function copies the actual value of an
argument into the formal parameter of the
function. In this case, changes made to the
parameter inside the function have no effect on
the argument.
 By default, C programming uses call by value to
pass arguments. In general, it means the code
within a function cannot alter the arguments
used to call the function. Consider the
function swap() definition as follows.
EXAMPLE

/* function definition to swap the values */


void swap(int x, int y)
{
int temp;
temp = x; // save the value of x
x = y; // put y into x
y = temp; // put temp into y
return;
}
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */ swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
CALL BY REFERENCE

 The call by reference method of passing


arguments to a function copies the address of an
argument into the formal parameter. Inside the
function, the address is used to access the actual
argument used in the call. It means the changes
made to the parameter affect the passed argument.
 To pass a value by reference, argument pointers are
passed to the functions just like any other value. So
accordingly you need to declare the function
parameters as pointer types as in the following
function swap(), which exchanges the values of the
two integer variables pointed to, by their
arguments.
EXAMPLE

/* function definition to swap the values */


void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{ /* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b. */
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
RECURSIVE FUNCTION

A function that calls itself is known as a recursive function. And,


this technique is known as recursion.
Recursion is the process of repeating items in a self-similar way. In
programming languages, if a program allows you to call a function
inside the same function, then it is called a recursive call of the
function.
How recursion works?
void recurse()
{ ... .. ...
recurse();
... .. ... }
int main()
{ ... .. ...
recurse();
... .. ... }
How does recursion works?
 The recursion continues until some condition is
met to prevent it.
 To prevent infinite recursion, if...else
statement (or similar approach) can be used
where one branch makes the recursive call, and
other doesn't.
EXAMPLE
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0; }
int sum(int n)
{ if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n; }
MACRO FUNCTIONS
PREPROCESSING
 Fibonacci Series in C
 Fibonacci series is a series of numbers formed by
the addition of the preceding two numbers in the
series. The first two terms are zero and one
respectively. The terms after this are generated
by simply adding the previous two terms.
 There are two ways to write the fibonacci series
program:
 Fibonacci Series without recursion

 Fibonacci Series using recursion


 How do you calculate Fibonacci?
 The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
 The next number is found by adding up the two
numbers before it:
 2 is calculated by adding the two numbers
preceding it (1+1),
 3 is calculated by adding the two numbers
preceding it (1+2),
 5 is (2+3), and so on..

 Here is an example of Fibonacci series:


0,1,1,2,3,5,8,13….etc.
#include<stdio.h>
int main()
{
int first=0, second=1, i, n, sum=0;
printf("Enter the number of terms: ");
scanf("%d",&n);
//accepting the terms
printf("Fibonacci Series:");
for(i=0 ; i<n ; i++)
{
if(i <= 1)
{
sum=i;
}
//to print 0 and 1
else
{
sum=first + second;
first=second;
second=sum;
//to calculate the remaining terms.
//value of first and second changes as new term is
printed.
}
printf(" %d",sum)
}
return 0;
}
 Fibonacci Series Using Recursion
 Another way to program the Fibonacci series
generation is by using recursion. Recursion is the
process of repeating items in a self-similar way.
In programming languages, if a program allows
you to call a function inside the same function,
then it is called a recursive call of the function
#include<stdio.h>
int f(int);
int main()
{
int n, m= 0, i;
printf("Enter Total terms:n");
scanf("%d", &n);
printf("Fibonacci series terms are:n");
for(i = 1; i <= n; i++)
{
printf("%dn", fibonacci(m));
m++;
}
return(fibonacci(n-1) + fibonacci(n-2));
}
return 0;
}
int fibonacci(int n)
{
if(n == 0 || n == 1)
return n;
else
ACKERMANN FUNCTION
 Ackermann function, named after Wilhelm
Ackermann, is one of the simplest and earliest-
discovered examples of a total computable
function that is not primitive recursive. All
primitive recursive functions are total and
computable, but the Ackermann function
illustrates that not all total computable functions
are primitive recursive.
#include<stdio.h>
int A(int m, int n);

main()
{
int m,n;
printf("Enter two numbers :: \n");
scanf("%d%d",&m,&n);
printf("\nOUTPUT :: %d\n",A(m,n));
}
int A(int m, int n)
{
if(m==0)
return n+1;
else if(n==0)
return A(m-1,1);
else
return A(m-1,A(m,n-1));
}
************ FIRST RUN ***********
Enter two numbers ::
1
0
OUTPUT :: 2
************* SECOND RUN ***********
Enter two numbers ::
0
5
OUTPUT :: 6
CHAPTER-7
POINTERS
SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE

 Basics of pointers

 pointer to pointer

pointer and array

 pointer to array

array to pointer

function returning pointer


POINTER

A pointer is a reference to another variable


(memory location) in a program
 Used to change variables inside a function
(reference parameters)
 Used to remember a particular member of a
group (such as an array)
 Used in dynamic (on-the-fly) memory allocation
(especially of arrays)
 Used in building complex data structures
(linked lists, stacks, queues, trees, etc.)
POINTER
44
 int a= 44; a
 As we have already seen, it is like 9562628
 when we declare 'a', it is given a memory location
and the value of 'a' is stored in that memory
location, 'a' will also have an address. So, this
address is the address of that memory location in
which the value of 'a' is stored.
 Address of 'a' is an integer which is something
like 9562628. It will vary for every computer as
per memory given to 'a' at that time.
Address in C is represented as &a, read as address of a.
Remember that all the time when we were taking value of variable
using scanf, we were taking an input from user and storing it at the
address of that variable.
ADDRESS OF OPERATOR
HOW TO USE POINTERS?
 int a = 44;
int *b; /* declaration of pointer b */
b = &a;
 int *b → This statement should mean that '*b' is an integer but then
what is significance of '*' before 'b'? It means that b points to some
integer ('b' is a pointer to some integer).
 Or we can say that 'b' will store the address of some integer.
 b = &a → As said, 'b' will store the address of some integer because it is
a pointer to an integer. In this declaration, it is storing the address of
'a'. Since, 'b' is a pointer and '&a' represents address, so, by the
declaration b = &a means that 'b' will now store the address of 'a'.
 int *b means that *b is an integer and *b is an integer which has the
value of the variable which 'b' is pointing to. Here *b is 44. Here, 'b' is
pointing to 'a', therefore 'b' will store the address of 'a' and '*b' will be
the integer to which 'b' is pointing i.e., 'a'.
 int a → 'a' is an integer.
int *b → 'b' is an pointer to an integer.
b = &a → 'b' is now pointing to 'a'.
'b' has the address of 'a' and '*b' has the value of
'a'.
POINTER BASICS
Variables are allocated at addresses in computer memory
(address depends on computer/operating system)
Name of the variable is a reference to that memory address
A pointer variable contains a representation of an address of
another variable (P is a pointer variable in the following):

Name V P
Address v (some value) p (some value)
int V = 101;
Abstract
101
Representation
int *P = &V;
Concrete 4 bytes for 4 bytes for
Representation int value 101 mem addressv
POINTER VARIABLE DEFINITION
Basic syntax: Type *Name
Examples:
int *P; /* P is var that can point to an int var */
float *Q; /* Q is a float pointer */
char *R; /* R is a char pointer */
Complex example:
int *AP[5]; /* AP is an array of 5 pointers to ints */
 more on how to read complex declarations later
ADDRESS (&) OPERATOR
The address (&) operator can be used in
front of any variable object in C -- the
result of the operation is the location in
memory of the variable
Syntax: &VariableReference
Examples:
int V;
int *P;
int A[5];
&V - memory location of integer variable V
&(A[2]) - memory location of array element 2 in
array A
&P - memory location of pointer variable P
POINTER VARIABLE
INITIALIZATION/ASSIGNMENT
NULL - pointer list constant to non-existent
address
 used to indicate pointer points to nothing
 Int *p=NULL;
Can initialize/assign pointer vars to NULL or
use the address (&) op to get address of a
variable
 variable in the address operator must be of the
right type for the pointer (an integer pointer
points only at integer variables)
Examples:
int V;
int *P = &V;
int A[5];
P = &(A[2]);
POINTER SAMPLE
#include <stdio.h>
void main()
{
int a = 10;
int *p;
p = &a; output
printf("p = %u\n", p); p = 3650188180
printf("*p = %d\n", *p); *p = 10
&p = 3650188184
printf("&p = %u\n", &p); *&p = 3650188180
printf("*&p = %u\n", *&p);
}
EXTENDED CONCEPT OF POINTER
POINTER ARITHMETIC
POINTER TO A POINTER (DOUBLE POINTER)
#include <stdio.h>
int main()
{
int a = 10;
int *p1; //this can store the address of variable a
int **p2;

p1 = &a;
p2 = &p1;
printf("Address of a = %u\n", &a);
printf("Address of p1 = %u\n", &p1);
printf("Address of p2 = %u\n\n", &p2);
printf("Value at the address stored by p2 = %u\n", *p2);
printf("Value at the address stored by p1 = %d\n\n", *p1);
printf("Value of **p2 = %d\n", **p2);
}

OUTPUT
Address of a = 2686724
Address of p1 = 2686728
Address of p2 = 2686732
Value at the address stored by p2 = 2686724
Value at the address stored by p1 = 10
Value of **p2 = 10
STRING CONSTANT
#include <stdio.h>
int main()
{
char str[100];
char *ptr;
printf("Enter any string :: ");
scanf("%s",str);
//assign address of str to ptr
ptr=str;
printf("\nThe entered string is :: ");
while(*ptr!='\0')
printf("%c",*ptr++);
return 0;
}
PRINTING ADDRESS OF EACH CHAR IN THE
STRING

#include<stdio.h>
void main()
{
char str[6] = "Hello";
char *ptr;
int i;
//string name itself a base address of the string
ptr = str; //ptr references str
for(i = 0; ptr[i] != '\0'; i++)
printf("&str[%d] = %p\n",i,ptr+i);
}
PASSING POINTERS TO FUNCTION

 When we pass a pointer as an argument instead


of a variable then the address of the variable is
passed instead of the value. So any change made
by the function using the pointer is permanently
made at the address of passed variable. This
technique is known as call by reference in C.
PASSING POINTERS TO FUNCTION
#include <stdio.h>
void swap( int *a, int *b )
{
int t;
t = *a;
*a = *b;
*b = t;
}
Void main()
{
int num1, num2;
printf("Enter first number\n");
scanf("%d", &num1);
printf("Enter second number\n");
scanf("%d", &num2);
swap( &num1, &num2);
printf("First number : %d\n", num1);
printf("Second number : %d\n", num2);
}
POINTER TYPES

 1. Null Pointer: A null pointer is a type of


pointer which points to nothing. It generally
points to the base address of the segment. In
case of nothing is assigned to the pointer
then it has a null value
 It is generally used in header files like
stdio.h, alloc.h
 2. Dangler Pointer: This type of pointer can
be created by deleting the object without
modifying the pointer value
POINTER TYPES

 3. Generic Pointer: This type of pointer


is declared using a variable of type void.
Since it is of void data type hence it is
referred to as a generic pointer. These
type of pointer does not point to any data
 4. Wild Pointer: A pointer which has not
been initialized is known as a wild
pointer. This type of pointer is initialized
during run time when one needs to use it.
This type of pointer is known as wild
pointer
POINTER TO ARRAY

#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
1D ARRAYS AND POINTERS
int A[5] - A is the address where the array
starts (first element), it is equivalent to
&(A[0])
A is in some sense a pointer to an integer
variable
To determine the address of A[x] use formula:
(address of A + x * bytes to represent int)
(address of array + element num * bytes for
element size)
The + operator when applied to a pointer
value uses the formula above:
A + x is equivalent to &(A[x])
*(A + x) is equivalent to A[x]
POINTER TO ARRAYS

 pointer is a variable whose value is the address of


some other variable i.e., if a variable 'y' points to
another variable 'x', it means that the value of the
variable 'y' is the address of 'x'.
 if we say that a variable 'y' points to an array 'n', it
would mean that the value of 'y' is the address of
the first element of the array i.e. n[0]. It means
that the pointer of an array is the pointer of its first
element.
 int age[50];
int *p;
p = age;
 'p' points to the first element of array 'age', '*p' is
the value of the first element of the array.
 *p is age[0], *(p+1) is age[1], *(p+2) is age[2].

 Similarly, *age is age[0] (value at age), *(age+1)


is age[1] (value at age+1), *(age+2) is age[2]
(value at age+2) and so on.
UNDERSTANDING COMPLEX
DECLARATIONS

int A A is a int
float B [5] B is a 1D array of size 5 of floats
int * C C is a pointer to an int
char D [6][3] D is a 2D array of size 6,3 of chars
int * E [5] E is a 1D array of size 5 of
pointers to ints
int (* F) [5] F is a pointer to a
1D array of size 5 of ints
int G (…) G is a function returning an int
char * H (…) H is a function returning
a pointer to a char
POINTERS AND ARRAYS
#include <stdio.h>
void main()
{
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i)
{ // Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
// Equivalent to sum += x[i] sum += *(x+i);
}
printf("Sum = %d", sum);
}
#include <stdio.h>
void main()
{
int *a,i,j,tmp,n;
printf(" Input the number of elements to store in the array :
");
scanf("%d",&n);
printf(" Input %d number of elements in the array : \n",n);
for(i=0;i<n;i++)
{
printf(" element - %d : ",i+1);
scanf("%d",a+i);

}
for(i=0;i<n;i++)
{
if( *(a+i) > *(a+j))
{
tmp = *(a+i);
*(a+i) = *(a+j);
*(a+j) = tmp;
}}}
printf("\n The elements in the array after sorting : \n");
for(i=0;i<n;i++)
{
printf(" element - %d : %d \n",i+1,*(a+i));
}
printf("\n"); }
CHAPTER-8
STRUCTURE
SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE

 Basics of structure
 structure members
 accessing structure
members, nested structures
array of structures
structure and functions
structures and pointers
STRUCTURE

Structure is a user-defined datatype in C


language which allows us to combine data
of different types together. Structure
helps to construct a complex data type
which is more meaningful. It is somewhat
similar to an Array, but an array holds
data of similar type only. But structure on
the other hand, can store data of any type,
which is practical more useful.
.
STRUCTURE

 For example: If I have to write a


program to store Student information,
which will have Student's name, age,
branch, permanent address, father's name
etc, which included string values, integer
values etc, how can I use arrays for this
problem, I will require something which
can hold data of different types together.
 In structure, data is stored in form
of records.
DEFINING A STRUCTURE

struct keyword is used to define a structure.


struct defines a new data type which is a collection
of primary and derived data types.

struct struct_name
{
DataType member1_name;
DataType member2_name;
DataType member3_name; …
};
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
};
Here struct Student declares a structure to hold
the details of a student which consists of 4 data
fields, namely name, age, branch and gender.
These fields are called structure elements or
members.
DECLARE VARIABLE OF A STRUCTURE?

struct struct_name var_name;


or
struct struct_name
{
DataType member1_name;
DataType member2_name;
DataType member3_name; …
}
var_name;
ACCESS DATA MEMBERS OF A STRUCTURE
USING A STRUCT VARIABLE?

 var_name.member1_name;
var_name.member2_name;
ASSIGN VALUES TO STRUCTURE MEMBERS?

There are three ways to do this.


1) Using Dot(.) operator
var_name.memeber_name = value;
2) All members assigned in one statement
struct struct_name var_name =
{value for memeber1, value for memeber2 …so
on for all the members}
#include <stdio.h>
struct StudentData
{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{ /* student is the variable of structure StudentData*/
Struct StudentData student;
/*Assigning the values of each struct member here*/
student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;
/* Displaying the values of struct members */
printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}
Output:
Student Name is: Steve
Student Id is: 1234
Student Age is: 30
#include<stdio.h>
#include<string.h>
struct Student
{ char name[25];
int age;
char branch[10];
char gender;
};
int main()
{
struct Student s1;
[Link] = 18;
[Link]="Viraaj”;
printf("Name of Student 1: %s\n", [Link]);
printf("Age of Student 1: %d\n", [Link]);
return 0;
}
NESTED STRUCTURE IN C: STRUCT INSIDE
ANOTHER STRUCT

Nested structures means, that one structure has


another stucture as member variable.
 Nested structure in C is nothing but structure
within structure. One structure can be declared
inside other structure as we declare structure
members inside a structure.
 The structure variables can be a normal structure
variable or a pointer variable to access the data.
You can learn below concepts in this section.
 Structure within structure in C using normal
variable
 Structure within structure in C using pointer
variable
#include <stdio.h>
#include <string.h>

struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;

int main()
{
struct student_detail stu_data = {1, "Raju", 90.5,
71145, "Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n",
stu_data.percentage);
printf(" College Id is: %d \n",
stu_data.clg_data.college_id);
printf(" College Name is: %s \n",
stu_data.clg_data.college_name);
return 0;
}
 OUTPUT:

 Id is: 1
Name is: Raju
Percentage is: 90.500000
 College Id is: 71145
College Name is: Anna University
ARRAY OF STRUCTURE

 C Structure is collection of different datatypes (


variables ) which are grouped together. Whereas,
array of structures is nothing but collection of
structures. This is also called as structure array
in C.
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;

// 2nd student's record


record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;

// 3rd student's record


record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage %f\n\n",record[i].percentage);
}
return 0;
}
STRUCTURE AND FUNCTIONS

 A structure can be passed to any function from


main function or from any sub function.
 Structure definition will be available within the
function only.
 It won’t be available to other functions unless it
is passed to those functions by value or by
address(reference).
 Else, we have to declare structure variable as
global variable. That means, structure variable
should be declared outside the main function. So,
this structure will be visible to all the functions
in a C program
 Passing structure to a function by value
 Passing structure to a function by
address(reference)
 No need to pass a structure – Declare structure
variable as global
PASSING STRUCTURE TO FUNCTION
IN C BY VALUE:

 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);
int main()
{
struct student record;
[Link]=1;
strcpy([Link], "Raju");
[Link] = 86.5;
func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", [Link]);
printf(" Name is: %s \n", [Link]);
printf(" Percentage is: %f \n",
[Link]);}
STRUCTURE USING POINTER

C structure can be accessed in 2 ways in a C


program. They are,
 Using normal structure variable

 Using pointer variable

 Dot(.) operator is used to access the data using


normal structure variable and arrow (->) is used
to access the data using pointer variable. You
have learnt how to access structure data using
normal variable in
include <stdio.h>
#include <string.h>

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

int main()
{
 int i;


struct student record1 = {1, "Raju", 90.5};
struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);

return 0;
}
DEFINE A STRUCTURE TYPE STRUCT PERSONAL THAT WOULD CONTAIN PERSON NAME,
DATE OF JOINING AND SALARY USING THIS STRUCTURE TO READ THIS INFORMATION
OF 5 PEOPLE AND PRINT THE SAME ON SCREEN.

 #include <stdio.h>
struct person
{
char name[20];
char doj[10];
float salary;
}p[5];
int main(void)
{
int i=0;

for(i=0;i<5;i++)
{
printf("\n Enter Person Name : ");
scanf("%s",p[i].name);
printf("\n Enter Person Date of Joining (dd-mm-
yyyy) : ");
scanf("%s",p[i].doj);
printf("\n Enter Person Salary : ");
scanf("%f",&p[i].salary);
}
for(i=0;i<5;i++)
{
printf("\n Person %d Detail",i+1);
printf("\n Name = %s",p[i].name);
printf("\n DOJ = %s",p[i].doj);
printf("\n Salary = %.2f",p[i].salary);
}
return 0;
}
DEFINE STRUCTURE DATA TYPE CALLED TIME_STRUCT CONTAINING THREE MEMBER’S
INTEGER HOUR, INTEGER MINUTE AND INTEGER SECOND. DEVELOP A PROGRAM THAT
WOULD ASSIGN VALUES TO THE INDIVIDUAL NUMBER AND DISPLAY THE TIME IN THE
FOLLOWING FORMAT: 16: 40:51

 #include <stdio.h>

struct time_struct
{
int hour;
int minute;
int second;
}t;

int main(void)
{
 printf("\n Enter Hour : ");
scanf("%d",&[Link]);
printf("\n Enter Minute: ");
scanf("%d",&[Link]);
printf("\n Enter Second : ");
scanf("%d",&[Link]);

printf("\n Time
%d:%d:%d",[Link]%24,[Link]%60,[Link]%60)
;

return 0;
}
52. DEFINE A STRUCTURE CALLED CRICKET THAT WILL DESCRIBE THE FOLLOWING INFORMATION:
PLAYER NAME TEAM NAME BATTING AVERAGE
USING CRICKET, DECLARE AN ARRAY PLAYER WITH 50 ELEMENTS AND WRITE A C PROGRAM TO
READ THE INFORMATION ABOUT ALL THE 50 PLAYERS AND PRINT TEAM WISE LIST CONTAINING NAMES
OF PLAYERS WITH THEIR BATTING AVERAGE.
*/

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

struct cricket
{
char player_name[20];
char team_name[20];
float batting_avg;
}p[50],t;
int main(void)
{
int i=0,j=0,n=50;
for(i=0;i<n;i++)
{
 printf("\n Enter Player Name : ");
scanf("%s",p[i].player_name);
printf("\n Enter Team Name : ");
scanf("%s",p[i].team_name);
printf("\n Enter Batting Average : ");
scanf("%f",&p[i].batting_avg);
}
 //Sorting of Data based on Team
for(i=0;i<n-1;i++)
{
for(j=i;j<n;j++)
{
if(strcmp(p[i].team_name,p[j].team_name)>0)
{
t=p[i];
p[i]=p[j];
p[j]=t;
j=0;
for(i=0;i<n;i++)
{
if(strcmp(p[i].team_name,p[j].team_name)!=0 ||
i==0)
{
printf("\n Team Name: %s",p[i].team_name);
j=i;
}
printf("\n Player Name =
%s",p[i].player_name);
printf("\n Batting Average =
%f",p[i].batting_avg);
}
return 0;
}
DESIGN A STRUCTURE STUDENT_RECORD TO CONTAIN NAME,
BRANCH AND TOTAL MARKS OBTAINED. DEVELOP A PROGRAM TO
READ DATA FOR 10 STUDENTS IN A CLASS AND PRINT THEM.

 #include <stdio.h>

struct student_record
{
char name[20];
char branch[20];
int total_marks;
}p[10];

int main(void)
{
int i=0,n=10;
for(i=0;i<n;i++)
{
 printf("\n Enter Student Name : ");
scanf("%s",p[i].name);
printf("\n Enter Students Branch : ");
scanf("%s",p[i].branch);
printf("\n Enter Students Marks : ");
scanf("%d",&p[i].total_marks);
}
for(i=0;i<n;i++)
{
printf("\n Student %d Detail",i+1);
printf("\n Name = %s",p[i].name);
printf("\n Branch = %s",p[i].branch);
printf("\n Total marks = %d",p[i].total_marks);
}
return 0;
}
CHAPTER-9
DYNAMIC MEMORY ALLOCATION
SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE

• Memory allocation
• Static Memory Allocation
• Memory Allocation Process
• Memory Allocation Functions
• Allocation A Block Of Memory : Malloc
• Allocation A Block Of Memory : Calloc
• Altering The Size Of A Block :Realloc
• Releasing The Used Space: Free
MEMORY ALLOCATION

• The blocks of information in a memory system is called memory


allocation.

• To allocate memory it is necessary to keep in information of


available memory in the system. If memory management system
finds sufficient free memory, it allocates only as much memory as
needed, keeping the rest available to satisfy future request.

• In memory allocation has two types. They are static and dynamic
memory allocation.
STATIC MEMORY ALLOCATION

• In static memory allocation, size of the memory may be required for


the that must be define before loading and executing the program.

DYNAMIC MEMORY ALLOCATION


• In the dynamic memory allocation, the memory is allocated to a
variable or program at the run time.
• The only way to access this dynamically allocated memory is
through pointer.

• Include #include<stdlib.h> header file


MEMORY ALLOCATION PROCESS
STDLIB FUNCTION
MEMORY ALLOCATION FUNCTIONS

• Include #include<stdlib.h> header file


ALLOCATION A BLOCK OF MEMORY :
MALLOC
malloc() function is used for allocating block of memory at
runtime. This function reserves a block of memory of given
size and returns a pointer of type void.

Ptr=(cast-type*) malloc (byte-size);


EXAMPLE PROGRAM
#include <stdio.h> #include <stdlib.h> struct emp
{
int eno; char name; float esal; void main()
{
struct emp *ptr; Output:
ptr = (struct emp *) malloc(size of(struct emp)); Enter the emp details
if(ptr == null) eno 1
{ ename priya esal
pintf(“out of memory”); 10,000
}
else
{
printf(“Enter the emp deitals”);
scanf(“%d%s%f,&ptr-> eno,ptr-> name,&ptr-> esal”);
return 0;
}
ALLOCATION A BLOCK OF MEMORY :
CALLOC
calloc() is another memory allocation function that is used for
allocating memory at runtime. calloc function is normally used for
allocating memory to derived data types such as arrays and
structures.

Ptr=(cast-type*)calloc(n,elem-size);
EXAMPLEPROGRAM
#include <stdio.h> #include <stdlib.h> int
main()
{
int i, n; output:
int *a;
printf("Number of elements to be entered:"); Number of elements to be entered :3 Enter
scanf("%d",&n); 3 numbers:
a = (int*)calloc(n, sizeof(int)); 22
printf("Enter %d numbers:\n",n); for( i=0 ; i 55
< n ; i++ ) 14
{ The numbers entered are :22 55 14
scanf("%d",&a[i]);
}
printf("The numbers entered are: "); for( i=0
; i < n ; i++ )
{
printf("%d ",a[i]);
}
free( a ); return(0);
}
ALTERING THE SIZE OF A BLOCK :
REALLOC

realloc() changes memory size that is already allocated


dynamically to a variable.

ptr=REALLOC(ptr,new size);
EXAMPLE PROGRAM
#include <stdio.h> #include <stdlib.h> int
main()
{
int *ptr = (int *)malloc(sizeof(int)*2); Output:
int i;
int *ptr_new; 10 20 30
*ptr = 10;
*(ptr + 1) = 20;
ptr_new = (int *)realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30; for(i = 0; i < 3; i++)
printf("%d ", *(ptr_new + i));
return 0;
}
RELEASING THE USED SPACE:
FREE

Free() function should be called on a pointer that was used either with
”calloc()” or “malloc()”,otherwise the function will destroy the memory
management making a system to crash.

free (ptr)
EXAMPLE:
func()
{
int *ptr, *p;
ptr = new int[100];
p = new int;
delete[] ptr; delete p;
}
CHAPTER-10
FILE MANAGEMENT

SUBJECT :PPS

Prepared by
Usha Yogi
IT Dept.
CHAPTER OUTLINE

 Introduction to file management


 and its functions
WHAT IS FILE?
File is a collection of bytes that is stored on secondary
storage devices like disk. There are two kinds of files in a
system. They are,

1. Text files (ASCII)


2. Binary files

Text files contain ASCII codes of digits, alphabetic and


symbols.
Binary file contains collection of bytes (0‟s and 1‟s).
Binary files are compiled version of text files.
BASIC FILE OPERATIONS

 There are 4 basic operations that can be


performed on any files in C programming
language. They are,

[Link]/Creating a file
[Link] a file
[Link] a file

[Link] in a file
FOPEN() – TO OPEN A FILE
 Declaration: FILE *fopen (const char *filename,
const char *mode)

 fopen() function is used to open a file to perform


operations such as reading, writing etc. In a C
program, we declare a file pointer and use fopen()
as below. fopen() function creates a new file if the
mentioned file name does not exist.
 FILE *fp;
fp=fopen (“filename”, ”„mode”);
 On success return address of file

 In failure return NULL pointer


 Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of
the file.
mode – refers to the operation that will be
performed on the file. Example: r, w, a, r+, w+
and a+. Please refer below the description for
these mode of operations.
FCLOSE() – TO CLOSE A FILE
 Declaration: int fclose(FILE *fp);
 fclose() function closes the file that is being
pointed by file pointer fp. In a C program, we
close a file as below.
fclose (fp);
FGETS() – TO READ A FILE
 Declaration:
char *fgets(char *string, int n, FILE *fp)
 fgets function is used to read a file line by line. In
a C program, we use fgets function as below.
fgets (buffer, size, fp);
 where,
buffer – buffer to put the data in.
size – size of the buffer
fp – file pointer
FPRINTF() – TO WRITE INTO A FILE
 Declaration:
int fprintf(FILE *fp, const char *format, …);
 fprintf()

 function writes string into a file pointed by fp. In a C


program, we write string into a file as below.
fprintf (fp, “some data”);
 or
fprintf (fp, “text %d”, variable_name);
MODE OF OPERATIONS PERFORMED ON A
FILE IN C LANGUAGE:
 r – Opens a file in read mode and sets pointer to the first
character in the file. It returns null if file does not exist.
 w – Opens a file in write mode. It returns null if file could
not be opened. If file exists, data are overwritten.
 a – Opens a file in append mode. If a file is in append
mode, then the file is opened. The content within the file
doesn't change It returns null if file couldn‟t be opened.
 r+ – Opens a file for read and write mode and sets pointer
to the first character in the file.
 w+ – opens a file for read and write mode and sets pointer
to the first character in the file.
 a+ – Opens a file for read and write mode and sets pointer
to the first character in the file. But, it can‟t modify
existing contents.
EXAMPLE PROGRAM FOR FILE OPEN, FILE WRITE AND FILE
CLOSE IN C LANGUAGE:

* Open, write and close a file : */


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

int main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf( "Opening the file test.c in write mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard” \
“ to write in the file test.c" ) ;
// getting input from user
while ( strlen ( gets( data ) ) > 0 )
{
// writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
// closing the file
printf("Closing the file test.c") ;
fclose(fp) ;
return 0; }
OUTPUT:
Opening the file test.c in write mode
Enter some text from keyboard to write in the file
test.c
Hi, How are you?
Closing the file test.c
EXAMPLE PROGRAM FOR FILE OPEN, FILE READ AND
FILE CLOSE IN C LANGUAGE:

# include <stdio.h>
int main( )
{
FILE *fp ;
char data[50] ;
printf( "Opening the file test.c in read mode"
);
fp = fopen( "test.c", "r" ) ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
printf( "Reading the file test.c" ) ;
while( fgets ( data, 50, fp ) != NULL )
printf( "%s" , data ) ;
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}

OUTPUT:
Opening the file test.c in read mode
Reading the file test.c
Hai, How are you?
Closing the file test.c

You might also like