0% found this document useful (0 votes)
50 views271 pages

PPS Material

The document provides an introduction to computers and programming, highlighting the definition, advantages, and disadvantages of computers. It includes a detailed explanation of computer components, hardware and software types, and programming concepts such as algorithms and flowcharts. Additionally, it covers the structure of C programming, comments, header files, and data types.

Uploaded by

yash444ytle
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)
50 views271 pages

PPS Material

The document provides an introduction to computers and programming, highlighting the definition, advantages, and disadvantages of computers. It includes a detailed explanation of computer components, hardware and software types, and programming concepts such as algorithms and flowcharts. Additionally, it covers the structure of C programming, comments, header files, and data types.

Uploaded by

yash444ytle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 271

Programming for Problem Solving (PPS)

GTU # 3110003
USING

Introduction to {C}
Programming

computer and
programming

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
What is Computer?
 The word computer comes from the word “compute”, which means, “to calculate”.
 A computer is an electronic device that can perform arithmetic operations at high
speed and it can process data, pictures, sound and graphics.
 It can solve highly complicated problems quickly and accurately.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 2


Advantages of Computer
 Speed
 It can calculate millions of expression within a fraction of second.
 Storage
 It can store large amount of data using various storage devices.
 Accuracy
 It can perform the computations at very high speed without any mistake.
 Reliability
 The information stored in computer is available after years in same form. It works 24 hours
without any problem as it does not feel tiredness.
 Automation
 Once the task is created in computer, it can be repeatedly performed again by a single click
whenever we want.
 Multitasking
 It can perform more than one tasks/operations simultaneously.
Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 3
Disadvantages of Computer
 Lake of intelligence
 It can not think while doing work.
 It does not have natural intelligence.
 It can not think about properness, correctness or effect of work it is doing.
 Unable to correct mistake
 It can not correct mistake by itself.
 So if we provide wrong or incorrect data then it produces wrong result or perform wrong
calculations.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 4


Block Diagram of Computer
 It is a pictorial representation of a computer which shows how it works inside.
 It shows how computer works from feeding/inputting the data to getting the result.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 5


Block Diagram of Computer
CENTRAL PROCESSING UNIT

CONTROL UNIT

INPUT SECTION ARITHMATIC AND OUTPUT SECTION


(Mouse, Keyboard etc…) LOGICAL UNIT (Monitor, Printer etc…)

PRIMARY MEMORY
(RAM, ROM etc…)

SECONDARY MEMORY
(Hard disk, Pen drive etc…)

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 6


Block diagram of computer (Input Section)
 The devices used to enter data in to computer system are called input devices.
 It converts human understandable input to computer controllable data.
 CPU accepts information from user through input devices.
 Examples: Mouse, Keyboard, Touch screen, Joystick etc…

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 7


Block diagram of computer (Output Section)
 The devices used to send the information to the outside world from the computer
is called output devices.
 It converts data stored in 1s and 0s in computer to human understandable
information.
 Examples: Monitor, Printer, Plotter, Speakers etc…

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 8


Block diagram of computer (Central Processing Unit (CPU))

 It contains electronics circuit that processes the data based on instructions.


 It also controls the flow of data in the system.
 It is also known as brain of the computer.
 CPU consists of,
 Arithmetic Logic Unit (ALU)
 It performs all arithmetic calculations such as add, subtract, multiply, compare, etc. and takes logical
decision.
 It takes data from memory unit and returns data to memory unit, generally primary memory (RAM).
 Control Unit (CU)
 It controls all other units in the computer system. It manages all operations such as reads instruction
and data from memory.
 Primary Memory
 It is also known as main memory.
 The processor or the CPU directly stores and retrieves information from it.
 Generally currently executing programs and data are stored in primary memory.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 9


Block diagram of computer (Secondary Memory)
 Secondary memory is also called Auxiliary memory or External memory.
 It is Used to store data permanently.
 It can be modified easily.
 It can store large data compared to primary memory. Now days, it is available in
Terabytes.
 Examples: Hard disk, Floppy disk, CD, DVD, Pen drive, etc…

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 10


What is Hardware?
 Hardware refers to the physical parts of a computer.
 The term hardware also refers to mechanical device that makes up computer.
 User can see and touch the hardware components.
 Examples of hardware are CPU, keyboard, mouse, hard disk, etc…

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 11


What is Software?
 A set of instruction in a logical order to perform a meaningful task is
called program and a set of program is called software.
 It tell the hardware how to perform a task.
 Types of software
 System software
 It is designed to operate the computer hardware efficiently.
 Provides and maintains a platform for running application software.
 Examples: Windows, Linux, Unix etc.
 Application software
 It is designed to help the user to perform general task such as word processing, web browser etc.
 Examples: Microsoft Word, Excel, PowerPoint etc.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 12


Categories of System Software
 Operating system
 It controls hardware as well as interacts with users, and provides different services to user.
 It is a bridge between computer hardware and user.
 Examples: Windows XP, Linux, UNIX, etc…
 System support software
 It makes working of hardware more efficiently.
 For example drivers of the I/O devices or routine for socket programming, etc…
 System development software
 It provides programming development environment to programmers.
 Example: Editor, pre-processor, compiler, interpreter, loader, etc…

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 13


Categories of Application Software
 General purpose software
 It is used widely by many people for some common task, like word processing, web browser,
excel, etc…
 It is designed on vast concept so many people can use it.
 Special purpose software
 It is used by limited people for some specific task like accounting software, tax calculation
software, ticket booking software, banking software etc…
 It is designed as per user’s special requirement.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 14


Compiler, Interpreter and Assembler
 Compiler translates program of higher level language to machine language. It
converts whole program at a time.
 Interpreter translates program of higher level language to machine language. It
converts program line by line.
 Assembler translates program of assembly language to machine language.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 15


Types of Computer Languages
 Machine level language OR Low level language
 It is language of 0’s and 1’s.
 Computer directly understand this language.
 Assembly language
 It uses short descriptive words (MNEMONIC) to represent each of the machine language
instructions.
 It requires a translator knows as assembler to convert assembly language into machine
language so that it can be understood by the computer.
 Examples: 8085 Instruction set
 Higher level language
 It is a machine independent language.
 We can write programs in English like manner and therefore easier to learn and use.
 Examples: C, C++, JAVA etc…

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 16


Types of Computer Languages
Flowchart Algorithm
Flowchart is a pictorial or graphical representation Algorithm is a finite sequence of well defined
of a program. steps for solving a problem.
It is drawn using various symbols. It is written in the natural language like English.
Easy to understand. Difficult to understand.
Easy to show branching and looping. Difficult to show branching and looping.
Flowchart for big problem is impractical. Algorithm can be written for any problem.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 17


Symbols used in Flowchart

Start / Stop Input / Output

Process Decision Making

Subroutine Arrows

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 18


Number is positive or negative
Step 1: Read no.
Start
Step 2: If no is greater than equal zero,
go to step 4.
Read no Step 3: Print no is a negative number,
go to step 5.
True False Step 4: Print no is a positive number.
Is no >= 0
Step 5: Stop.

Print no is Print no is
Positive Negative

Stop

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 19


Number is odd or even
Step 1: Read no.
Start
Step 2: If no mod 2 = 0, go to step 4.
Step 3: Print no is a odd, go to step 5.
Read no
Step 4: Print no is a even.
Step 5: Stop.
True False
Is no % 2 = 0

Print no is Print no is
Even Odd

Stop

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 20


Largest number from 2 numbers
Step 1: Read a, b.
Start
Step 2: If a>b, go to step 4.
Step 3: Print b is largest number, go to
Read a, b step 5.
Step 4: Print a is largest number.
True
Is a>b
False Step 5: Stop.

Print a is Print b is
largest largest

Stop

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 21


Largest number from 3 numbers (Flowchart)
Start

Read a, b, c

True False
Is a>b

True False True False


Is a>c Is b>c

Print a is Print c is Print b is Print c is


largest largest largest largest

Stop

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 22


Largest number from 3 numbers (Algorithm)
Step 1: Read a, b, c.
Step 2: If a>b, go to step 5.
Step 3: If b>c, go to step 8.
Step 4: Print c is largest number, go to step 9.
Step 5: If a>c, go to step 7.
Step 6: Print c is largest number, go to step 9.
Step 7: Print a is largest number, go to step 9.
Step 8: Print b is largest number.
Step 9: Stop.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 23


Print 1 to 10
Step 1: Initialize a to 1.
Start
Step 2: Print a.
Step 3: Repeat step 2 until a<=10.
a=1
Step 3.1: a=a+1.
Step 4: Stop.
a=a+1 Print a

True False
Is a<=10

Stop

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to computer and programming 24


Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Fundamentals {C}
Programming

of C

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
Features of C Language
 Modularity
 Extensibility
 Elegant syntax
 Case sensitive
 Less memory required
 The standard library concept
 The portability of the compiler
 A powerful and varied range of operators
 Ready access to the hardware when needed

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 27


Structure of C Program
Program
Documentation section
1 // Program for addition of 2 nos
(Used for comments)
2
Link section 3
4
Definition section 5
6 void fun();
7
Global declaration section 8 int a=10;
(Variables used in more than 9
one functions) 10
void main () 11 void main( )
{ 12 {
Declaration part 13 printf("Value of a inside main function: %d", a);
Executable part 14 fun();
} 15 }
16
Subprogram section 14 void fun()
(User defined functions) 18 {printf("Value of a inside fun function: %d", a);}

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 28


Comments
 A comment is an explanation or description of the source code of the program
 It helps a programmer to explain logic of the code and improves program
readability.
 At run-time, a comment is ignored by the compiler.
 There are two types of comments in C:
 Single line comment
 Represented as // double forward slash
 It is used to denote a single line comment only.
 Example: // Single line comment
 Multi-line comment
 Represented as /* any_text */ start with forward slash and asterisk (/*) and end with asterisk and
forward slash (*/).
 It is used to denote single as well as multi-line comment.
 Example: /* multi line comment line -1
 multi line comment line -2 */
Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 29
Header files
 A header file is a file with extension .h which contains the set of predefined
standard library functions.
 The “#include” preprocessing directive is used to include the header files with
extension in the program.
Header file Description
stdio.h Input/Output functions (printf and scanf)
conio.h Console Input/Output functions (getch and clrscr)
math.h Mathematics functions (pow, exp, sqrt etc…)
string.h String functions (strlen, strcmp, strcat etc…)

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 30


Data Types
 Data types are defined as the data storage format that a variable can store a data.
 It determines the type and size of data associated with variables.

Data types in C

Primary Data type


Secondary Data type
(int, float, char)

Derived Data type User definer Data type


(array, pointer) (structure, union, enum)

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 31


Primary Data Type
 Primary data types are built in data types which are directly supported by machine.
 They are also known as fundamental data types.
 int:
 int datatype can store integer number which is whole number without fraction part such as 10, 105
etc.
 C language has 3 classes of integer storage namely short int, int and long int. All of these data
types have signed and unsigned forms.
 Example: int a=10;
 float:
 float data type can store floating point number which represents a real number with decimal point
and fractional part such as 10.50, 155.25 etc.
 When the accuracy of the floating point number is insufficient, we can use the double to define the
number. The double is same as float but with longer precision.
 To extend the precision further we can use long double which consumes 80 bits of memory space.
 Example: float a=10.50;

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 32


Primary Data Type (cont…)
 char:
 Char data type can store single character of alphabet or digit or special symbol such as ‘a’, ‘5’ etc.
 Each character is assigned some integer value which is known as ASCII values.
 Example: char a=‘a’;
 void:
 The void type has no value therefore we cannot declare it as variable as we did in case of int or
float or char.
 The void data type is used to indicate that function is not returning anything.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 33


Secondary Data Type
 Secondary data types are not directly supported by the machine.
 It is combination of primary data types to handle real life data in more convenient
way.
 It can be further divided in two categories,
 Derived data types: Derived data type is extension of primary data type. It is built-in system
and its structure cannot be changed. Examples: Array and Pointer.
 Array: An array is a fixed-size sequenced collection of elements of the same data type.
 Pointer: Pointer is a special variable which contains memory address of another variable.
 User defined data types: User defined data type can be created by programmer using
combination of primary data type and/or derived data type. Examples: Structure, Union, Enum.
 Structure: Structure is a collection of logically related data items of different data types grouped
together under a single name.
 Union: Union is like a structure, except that each element shares the common memory.
 Enum: Enum is used to assign names to integral constants, the names make a program easy to read
and maintain.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 34


Variables and Constants
 Variable is a symbolic name given to some value which can be changed.
 𝑥, 𝑦, 𝑎, 𝑐𝑜𝑢𝑛𝑡, 𝑒𝑡𝑐. can be variable names.
 𝑥=5 𝑎=𝑏+𝑐
 Constant is a fixed value which cannot be changed.
 5, −7.5, 1452, 0, 3.14, 𝑒𝑡𝑐.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 35


Tokens
 The smallest individual unit of a program is known as token.
 C has the following tokens:
 Keywords
 C reserves a set of 32 words for its own use. These words are called keywords (or reserved words), and
each of these keywords has a special meaning within the C language.
 Identifiers
 Identifiers are names that are given to various user defined program elements, such as variable,
function and arrays.
 Constants
 Constants refer to fixed values that do not change during execution of program.
 Strings
 A string is a sequence of characters terminated with a null character \0.
 Special Symbols
 Symbols such as #, &, =, * are used in C for some specific function are called as special symbols.
 Operators
 An operator is a symbol that tells the compiler to perform certain mathematical or logical operation.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 36


Operators
 Arithmetic operators (+, - , *, /, %)
 Relational operators (<, <=, >, >=, ==, !=)
 Logical operators (&&, ||, !)
 Assignment operators (+=, -=, *=, /=)
 Increment and decrement operators (++, --)
 Conditional operators (?:)
 Bitwise operators (&, |, ^, <<, >>)
 Special operators ()

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 37


Arithmetic Operators
 Arithmetic operators are used for mathematical calculation.
Operator Meaning Example Description
+ Addition a+b Addition of a and b
- Subtraction a–b Subtraction of b from a
* Multiplication a*b Multiplication of a and b
/ Division a/b Division of a by b
% Modulo division- remainder a%b Modulo of a by b

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 38


Relational Operators
 Relational operators are used to compare two numbers and taking decisions based
on their relation.
 Relational expressions are used in decision statements such as if, for, while, etc…
Operator Meaning Example Description
< Is less than a<b a is less than b
<= Is less than or equal to a <= b a is less than or equal to b
> Is greater than a>b a is greater than b
>= Is greater than or equal to a >= b a is greater than or equal to b
== Is equal to a=b a is equal to b
!= Is not equal to a != b a is not equal to b

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 39


Logical Operators
 Logical operators are used to test more than one condition and make decisions.
Operator Meaning
&& logical AND (Both non zero then true, either is zero then false)
|| logical OR (Both zero then false, either is non zero then true)
! Is greater than

a b a&&b a||b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 40


Assignment Operators
 Assignment operators (=) is used to assign the result of an expression to a variable.
 Assignment operator stores a value in memory.
 C also supports shorthand assignment operators which simplify operation with
assignment.
Operator Meaning
= Assigns value of right side to left side
+= a += 1 is same as a = a + 1
-= a -= 1 is same as a = a - 1
*= a *= 1 is same as a = a * 1
/= a /= 1 is same as a = a / 1
%= a %= 1 is same as a = a % 1

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 41


Increment and Decrement Operators
 Increment (++) operator used to increase the value of the variable by one.
 Decrement (--) operator used to decrease the value of the variable by one.

Example Explanation
x=100; After the execution the
x++; value of x will be 101.

Example Explanation
x=100; After the execution the
x--; value of x will be 99.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 42


Increment and Decrement Operators (cont…)
Operator Description
Pre increment operator (++x) value of x is incremented before assigning it to the variable
on the left

Example Explanation Output


x=10; First increment value of x will be 11
p=++x; x by one then assign. p will be 11

Operator Description
Post increment operator (x++) value of x is incremented after assigning it to the variable on
the left

Example Explanation Output


x=10; First assign value of x x will be 11
p=x++; then increment value. p will be 10

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 43


Conditional Operators
 A ternary operator is known as conditional operator.
 Syntax: exp1 ? exp2 : exp3
Working of the ? : Operator
exp1 is evaluated first
if exp1 is true(nonzero) then
- exp2 is evaluated and its value becomes the value of the expression
If exp1 is false(zero) then
- exp3 is evaluated and its value becomes the value of the expression

Example Example
m=2, n=3; m=2, n=3;
r=(m>n) ? m : n; r=(m<n) ? m : n;
Explanation Explanation
Value of r will be 3 Value of r will be 2

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 44


Bitwise Operators
 Bitwise operators are used to perform operation bit by bit.
 Bitwise operators may not be applied to float or double.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left (shift left means multiply by 2)
>> shift right (shift right means divide by 2)

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 45


Bitwise Operators
8 = 1000 (In Binary) and 6 = 0110 (In Binary)

Example: Bitwise & (AND) Example: Bitwise | (OR)


int a=8, b=6, c; int a=8, b=6, c;
c = a & b; c = a | b;
printf("Output = %d", c); printf("Output = %d", c);
Output Output
0 14

Example: Bitwise << (Shift Left) Example: Bitwise >> (Shift Right)
int a=8, b; int a=8, b;
b = a << 1; b = a >> 1;
printf("Output = %d", b); printf("Output = %d", b);
Output Output
16 (multiplying a by a power of two) 4 (dividing a by a power of two)

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 46


Special Operators

Operator Meaning
& Address operator, it is used to determine address of the variable.
* Pointer operator, it is used to declare pointer variable and to get value from it.
, Comma operator. It is used to link the related expressions together.
sizeof It returns the number of bytes the operand occupies.
. member selection operator, used in structure.
-> member selection operator, used in pointer to structure.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 47


Expressions
 An expression is a combination of operators, constants and variables.
 An expression may consist of one or more operands, and zero or more operators to
produce a value.

Operand 1 Operand 2 Operand 3

answer = a + b * c;

Variable to store Operator 1 Operand 2


the expression value

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 48


Evaluation of Expressions
 An expression is evaluated based on the operator precedence and associativity.
 When there are multiple operators in an expression, they are evaluated according
to their precedence and associativity.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 49


Operator precedence
 Precedence of an operator is its priority in an expression for evaluation.
 The operator with higher precedence is evaluated first and the operator with the
least precedence is evaluated last.
 Operator precedence is why the expression 5 + 3 * 2 is calculated as 5 + (3 * 2),
giving 11, and not as (5 + 3) * 2, giving 16.
 We say that the multiplication operator (*) has higher "precedence" or "priority"
than the addition operator (+), so the multiplication must be performed first.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 50


Operator associativity
 Associativity is the left-to-right or right-to-left order for grouping operands to
operators that have the same precedence.
 Operator associativity is why the expression 8 - 3 - 2 is calculated as (8 - 3) - 2,
giving 3, and not as 8 - (3 - 2), giving 7.
 We say that the subtraction operator (-) is "left associative", so the left subtraction
must be performed first.
 When we can't decide by operator precedence alone in which order to calculate an
expression, we must use associativity.

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 51


Type conversion
 Type conversion is converting one type of data to another type.
 It is also known as Type Casting.
 There are two types of type conversion:
 Implicit Type Conversion
 This type of conversion is usually performed by the compiler when necessary without any commands
by the user.
 It is also called Automatic Type Conversion.
 Explicit Type Conversion
 These conversions are done explicitly by users using the pre-defined functions.
Example: Implicit Type Conversion Example: Explicit Type Conversion
int a = 20; double a = 4.5, b = 4.6, c = 4.9;
double b = 20.5; int result = (int)da + (int)db + (int)dc;
printf("%lf", a + b); printf("result = %d", result);
Output Output
40.500000 12

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 52


printf()
 printf() is a function defined in stdio.h file
 It displays output on standard output, mostly monitor
 Message and value of variable can be printed
 Let’s see few examples of printf
 printf(“ ”);
 printf(“Hello World”); // Hello World
 printf(“%d”, c); // 15
 printf(“Sum = %d”, c); // Sum = 15
 printf(“%d+%d=%d”, a, b, c); // 10+5=15

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 53


scanf()
 scanf() is a function defined in stdio.h file
 scanf() function is used to read character, string, numeric data from keyboard
 Syntax of scanf
 scanf("%X", &variable);
 where %X is the format specifier which tells the compiler what type of data is in a variable.
 & refers to address of “variable” which is directing the input value to a address returned by &variable.

Format Supported Example Description


specifier data types
%d Integer scanf(“%d”, &a) Accept integer value such as 1, 5, 25, 105 etc
%f Float scanf(“%f”, &b) Accept floating value such as 1.5, 15.20 etc
%c Character scanf(“%c”, &c) Accept character value such as a, f, j, W, Z etc
%s String scanf(“%s”, &d) Accept string value such as diet, india etc

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 54


getchar and putchar
Program
 getchar function reads a single
character from terminal. 1
2
#include <stdio.h>
void main( )
 putchar function displays the 3 {
character passed to it on the screen. 4 int c;
5 printf("Enter a character: ");
6 /* Take a character as input */
7 c = getchar();
8 /* Display the character */
9 printf("Entered character is: ");
10 putchar(c);
11 }

Output
Enter a character: a
Entered character is: a

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 55


gets and puts
Program
 gets function reads a line from stdin
into the buffer pointed to by s until 1
2
#include <stdio.h>
void main( )
either a terminating newline or EOF 3 {
(End of File) occurs. 4 /*Character array of length 100*/
 puts function writes the string 's'
5 char str[100];
6 printf("Enter a string: ");
and 'a' trailing newline to stdout. 7 /* Take a string as input */
8 gets( str );
9 /* Display the string */
10 printf("Entered string is: ");
11 puts( str );
12 }

Output
Enter a string: india
Entered string is: india

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 56


Preprocessor
 Preprocessors are programs that process our source code before compilation.
 There are a number of steps involved between writing a program and executing a
program in C.
 Let us have a look at these steps before we actually start learning about
Preprocessors.
C Program

Object Executable
Are there No Code Code
preprocessor Compiler Linker
directive

Yes

Preprocessor perform action


Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 57
Types of Preprocessor
 There are 4 main types of preprocessor directives:
 Macros
 File inclusion
 Conditional compilation
 Other directives

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 58


Macro
 A macro is a fragment of code which has been given a name. Whenever the name
is used in program, it is replaced by the contents of the macro.
 Macro definitions are not variables and cannot be changed by your program code
like variables.
 The ‘#define’ directive is used to define a macro.
 Do not put a semicolon ( ; ) at the end of #define statements.
 There are two types of macros:
 Object-like Macros
 Function-like Macros

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 59


Macro
Description Object-like Macros Function-like Macros
Definition The object-like macro is an identifier that The function-like macro looks like
is replaced by value. function call.
Use It is used to represent numeric constants. It is used to represent function.
Syntax #define CNAME value #define CNAME (expression)
Example #define PI 3.14 #define MIN(a,b) ((a)<(b)?(a):(b))
Program 1 #include <stdio.h> 1 #include <stdio.h>
2 #define PI 3.14 2 #define MIN(a,b) ((a)<(b)?(a):(b))
3 void main() 3 void main()
4 { int r=2; 4 {
5 float a; 5 printf("%d", MIN(2, 5));
6 a=PI*r*r; 6 }
7 printf("%f", a);
8 }

Prof. Nilesh Gambhava #3110003 (PPS) – Fundamentals of C 60


Programming for Problem Solving (PPS)
GTU # 3110003
USING

Decision {C}
Programming

making in
C

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
Need of decision making

if number is odd
{
/* code */
}

else number is even


{
/* code */
}

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 62


Decision Making or Conditional Statement
 C program statements are executed sequentially.
 Decision Making statements are used to control the flow of program.
 It allows us to control whether a program segment is executed or not.
 It evaluates condition or logical expression first and based on its result (either true
or false), the control is transferred to particular statement.
 If result is true then it takes one path else it takes another path.

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 63


Decision Making Statements in C

Decision Making Statements are


One way Decision: if (Also known as simple if)
Two way Decision: if…else
Multi way Decision: if…else if…else if…else
Two way Decision: ?: (Conditional Operator)
n-way Decision: switch…case

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 64


Relational Operators
 Relational Operator is used to compare two expressions.
 It gives result either true or false based on relationship of two expressions.

Math C Meaning Example Result


> > is greater than 5 > 4 true
≥ >= is greater than or equal to 5 >= 4 true
< < is less than 5 < 4 false
≤ <= is less than or equal to 5 <= 4 false
≠ != is not equal to 5 != 4 true
= == is equal to 5 == 4 false

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 65


If statement
if
 if is single branch decision making statement.
 If condition is true then only body will be executed.
 if is a keyword. Flowchart of if
Syntax
if(condition)
{ False
// Body of the if condition
// true part
}
True

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 67


WAP to print Zero if given number is 0

Program Output
1 #include<stdio.h> Enter Number:0
2 void main() Zero
3 {
4 int a;
5 printf("Enter Number:");
6 scanf("%d",&a);
7 if(a == 0)
8 {
9 printf("Zero");
10 }
11 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 68


WAP to print Positive or Negative Number

Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a >= 0)
8 {
9 printf("Positive Number");
10 }
11 if(a < 0)
12 {
13 printf("Negative Number");
14 }
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 69


Modulus Operator
 % is modulus operator in C
 It divides the value of one expression (number) by the value of another expression (number), and
returns the remainder.
 Syntax: express1 % express2
 E.g.
 7%2 Answer: 1
 6%2 Answer: 0
 25%10 Answer: 5
 37%28 Answer: 9

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 70


WAP to print Odd or Even Number

Program Output
1 #include<stdio.h> Enter Number:12
2 void main() Even Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:11
6 scanf("%d",&a); Odd Number
7 if(a%2 == 0)
8 {
9 printf("Even Number");
10 }
11 if(a%2 != 0)
12 {
13 printf("Odd Number");
14 }
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 71


If..else statement
if...else
 if…else is two branch decision making statement
 If condition is true then true part will be executed else false part will be executed
 else is keyword
Flowchart of if…else
Syntax
if(condition)
{ True False
// true part condition
}
else
{
// false part … …
}

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 73


WAP to print Positive or Negative Number using if…else

Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a >= 0)
8 {
9 printf("Positive Number");
10 }
11 else
12 {
13 printf("Negative Number");
14 }
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 74


WAP to print Odd or Even Number using if…else

Program Output
1 #include<stdio.h> Enter Number:12
2 void main() Even Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:11
6 scanf("%d",&a); Odd Number
7 if(a%2 == 0)
8 {
9 printf("Even Number");
10 }
11 else
12 {
13 printf("Odd Number");
14 }
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 75


WAP to find largest number from given 2 numbers using if

Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 if(a > b)
8 {
9 printf("%d is largest", a);
10 }
11 if(a < b)
12 {
13 printf("%d is largest", b);
14 }
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 76


WAP to find largest number from given 2 numbers using if…else

Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 if(a > b)
8 {
9 printf("%d is largest", a);
10 }
11 else
12 {
13 printf("%d is largest", b);
14 }
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 77


{ }
 If body of if contains only one statement then { } are not compulsory
 But if body of if contains more than one statements then { } are compulsory

if(a >= b) Both if(a >= b)


{
are printf("%d is largest", a);
printf("%d is largest", a);
} same

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 78


If…else if…else if…else


Ladder if
If…else if…else if…else
 if…else if…else if…else is multi branch decision making statement.
 If first if condition is true then remaining if conditions will not be evaluated.
 If first if condition is false then second if condition will be evaluated and if it is
true then remaining if conditions will not be evaluated.
 if…else if…else if…else is also known as if…else if ladder
Syntax
if(condition-1)
statement-1;
else if(condition-2)
statement-2;
else
statement-3;

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 80


if…else if…else ladder flowchart

condition False
1

True condition False


2
… True Condition
False
3
… True

… …

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 81


WAP to print Zero, Positive or Negative Number

Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a > 0)
8 printf("Positive Number");
9 else if(a==0)
10 printf("Zero");
11 else
12 printf("Negative Number");
13 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 82


Nested if
Nested if
 If condition-1 is true then condition-2 is evaluated. If it is true then statement-1 will
be executed.
 If condition-1 is false then statement-3 will be executed.
Syntax
if(condition-1)
{
if(condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 84


Nested if flowchart

False condition True


1

Statement condition False


3 2

True
Statement Statement
1 2

Next
Statement
Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 85
WAP to print maximum from given three numbers
Program
1 void main(){
2 int a, b, c; Output
3 printf("Enter Three Numbers:"); Enter Three Numbers:7
4 scanf("%d%d%d",&a,&b,&c); 5
5 if(a>b) 9
6 { 9 is max
7 if(a>c)
8 printf("%d is max",a);
9 else
10 printf("%d is max",c);
11 }
12 else
13 {
14 if(b>c)
15 printf("%d is max",b);
16 else
17 printf("%d is max",c);
18 }
19 }
Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 86

Conditional Operator
? : (Conditional Operator)
 The conditional works operator is similar to the if-else.
 It is also known as a ternary operator.
 It returns first value of expression (before colon(:)) if expression is true and second
value of expression if expression is false.

False
True

variable = Expression1 ? Expression2 : Expression3


Result value
Result value

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 88


Conditional operator flowchart
 Here, Expression1 is the condition to be
evaluated.
True Expression False
1  If the condition(Expression1) is True then
Expression2 will be executed and the result
will be returned.
Expression Expression
2 3
 Otherwise, if condition(Expression1) is
false then Expression3 will be executed
Variable
and the result will be returned.

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 89


WAP to find largest number from given 2 numbers using ? :

Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b, max;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 max = a>b?a:b;
8 printf("%d is largest",max);
9 }

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 90


switch…case
switch...case
 The switch statement allows to execute one code block among many alternatives.
 It works similar to if...else..if ladder.
Syntax  The expression is evaluated once and
switch (expression) compared with the values of each case.
{

case constant1:  If there is a match, the corresponding
// statements statements after the matching case are
break; executed.
case constant2:
// statements  If there is no match, the default
break; statements are executed.
.
.  If we do not use break, all statements
. after the matching label are executed.
default:
// default statements  The default clause inside the switch
} statement is optional.
Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 92
WAP that asks day number and prints day name using switch…case
void main(){ case 7:
int day; printf("Saturday");
printf("Enter day number(1-7):"); break;
scanf("%d",&day); default:
switch(day) printf("Wrong input");
{ break;
case 1: }
printf("Sunday"); }
break;
case 2:
printf("Monday");
break;
case 3:
Output
printf("Tuesday");
break; Enter day number(1-7):5
case 4: Thursday
printf("Wednesday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 93


Practice programs
1) Write a program to check whether entered character is vowel or not?
2) Write a program to perform Addition, Subtraction, Multiplication and Division of
2 numbers as per user’s choice (using if…else/Nested if/Ladder if).
3) Write a program to read marks of five subjects. Calculate percentage and print
class accordingly. Fail below 35, Pass Class between 35 to 45, Second Class
between 45 to 60, First Class between 60 to 70, Distinction if more than 70.
4) Write a program to find out largest number from given 3 numbers (Conditional
operator).
5) Write a program to print number of days in the given month.

Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 94


Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Looping {C}
Programming

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
Life is all about Repetition.
We do same thing everyday
What is loop?
 Loop is used to execute the block of code several times according to the condition
given in the loop. It means it executes the same code multiple times.

“Hello” 5

Output

printf("Hello\n"); Hello
printf("Hello\n"); Hello loop(condition)
{
printf("Hello\n"); Hello //statements
printf("Hello\n"); Hello }

printf("Hello\n"); Hello

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 98


if v/s while

Flowchart of if v/s Flowchart of while

False False
condition condition

True True

… …

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 99


Looping or Iterative Statements in C
Looping Statements are
Entry Controlled Loop: while, for
Exit Controlled Loop: do…while
Virtual Loop: goto

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 100


While loop
While Loop
 while is an entry controlled loop
 Statements inside the body of while are repeatedly executed till the condition is
true
 while is keyword
Syntax
while(condition)
{
// Body of the while
// true part
}

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 102


WAP to print 1 to n(while loop)

Program Output
1 #include <stdio.h> Enter n:10
2 void main() 1
3 { 2
4 int i,n; 3
5 i=1; 4
6 printf("Enter n:"); 5
7 scanf("%d",&n); 6
8 while(i<=n) 7
9 { 8
10 printf("%d\n",i); 9
11 i=i+1; 10
12 }
13 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 103


WAP to print multiplication table(while loop)

Program Output
1 #include<stdio.h> Enter n for multiplication table:5
2 void main() 5 * 1 = 5
3 { 5 * 2 = 10
5 * 3 = 15
4 int i=1,n;
5 * 4 = 20
5 printf("Enter n for multiplication table:"); 5 * 5 = 25
6 scanf("%d",&n); 5 * 6 = 30
7 while(i<=10) 5 * 7 = 35
8 { 5 * 8 = 40
9 printf("%d * %d = %d\n",n,i,n*i); 5 * 9 = 45
10 i=i+1; 5 * 10 = 50
11 }
12 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 105


WAP to Sum of 5 numbers entered by user(while loop)

Program Output
1 #include<stdio.h> Enter a number=10
2 void main() Enter a number=20
3 { Enter a number=30
Enter a number=40
4 int sum=0, i=1,n;
Enter a number=50
5 while(i<=5) Sum is=150
6 {
7 printf("Enter a number=");
8 scanf("%d",&n);
9 sum=sum+n;
10 i=i+1;
11 }
12 printf("Sum is=%d",sum);
13 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 106


Syntax and Logic
Swimming Rules To Swim
1. Breath control
2. Kicking legs
3. Back stroke with arms
4. Front stroke with arms
5. Crawling in water

Syntax Logic
while(condition) int i = 1;
{ while (i <= 5)
// Body of the while {
// true part printf("%d\n", i);
} i=i+1;
}

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 108


How to build logic? Step-1
Step 1: Understand the problem statement
 e.g. Write a program to find factors of a number.
 Run following questions through mind
 What is the factor of a number?
 Factor is a number that divides another number evenly with no remainder.
 For example, 1,2,3,4,6,12 are factors of 12.
 How many variables needed? What should be their data types?(Inputs/Outputs)
 To get number from user we need variable n.
 Now we need to divide n with 1,2,3,...,n. For this we will declare a loop variable i initialized as 1.
 Both variables should be of integer data type.
 What control structure you require?
 First we need a loop to divide n by 1,2,3,…,n, loop will start from 1 and ends at n.
 Inside loop we need if structure to check n%i==0 (Number n is evenly divisible by i or not).

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 109


How to build logic? Step-2
Step 2: Think for 1 or 2 examples
 Consider n=6, now take i=1
 6%1==0, TRUE; So, 1 is factor of 6
 6%2==0, TRUE; So, 2 is factor of 6
 6%3==0, TRUE; So, 3 is factor of 6
 6%4==2, FALSE; S0, 4 is not factor of 6
 6%5==1, FALSE; S0, 5 is not factor of 6
 6%6==0, TRUE; S0, 6 is factor of 6

 From this we can infer that loop variable i starts with 1 and incremented by one
for next iteration then ends at value n.
 Consider n=10, factors are 1,2,5,10
 Consider n=11, factor is 1,11
 From this we can infer that 1 and number itself are always factors of any number n.

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 110


How to build logic? Step-3
Step 3: Draw flowchart/steps on paper or in mind
Start
Steps
i=1 Step 1: Start
Step 2: Declare variables n,i
read n Step 3: Initialize variable
i ← 1
Step 4: Read value of n
i<=n? Step 5: Repeat the steps until i = n
True False 5.1: if n%i == 0
Display i
n%i==0? 5.2: i=i+1
True False Step 7: Stop
print i

i=i+1
Stop
Prof. Nilesh Gambhava #3110003 (PPS) – Looping 111
How to build logic? Step-4
Step 4: Writing Pseudo-code
 Pseudo-code is an informal way to express the design of a computer program or
an algorithm.
 It does not require any strict programming language syntax.

Pseudo-code
Initialize i=1 integer
Declare n as integer
Input n
while i<n
if n%i
print i
end if
increment i=i+1
end while

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 112


WAP to find factors of a number(while loop)

Program Output
1 #include <stdio.h> Enter n to find factors=12
2 void main() 1,2,3,4,6,12,
3 {
4 int i=1,n;
5 printf("Enter n to find factors=");
6 scanf("%d",&n);
7 while(i<=n)
8 {
9 if(n%i==0)
10 printf("%d,",i);
11 i=i+1;
12 }
13 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 113


WAP to print reverse a number(while loop)

Program Output
1 #include <stdio.h> Enter a number=1234
2 void main() 4321
3 {
4 int n;
5 printf("Enter a number=");
6 scanf("%d",&n);
7 while(n!=0)
8 {
9 printf("%d",n%10);
10 n=n/10;
11 }
12 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 114


WAP to check given number is perfect or not(while loop)
1 void main(){
2 int i=1,n,sum=0;
3 printf("Enter a number:"); Output
4 scanf("%d",&n); Enter a number:6
5 while(i<n) 1+2+3=6
6 is a perfect number
6 {
7 if(n%i==0)
Output
8 {
9 printf("%d+",i); Enter a number:8
1+2+4+=7
10 sum=sum+i;
8 is not a perfect number
11 }
12 i=i+1;
Output
13 }
14 printf("=%d",sum); Enter a number:496
1+2+4+8+16+31+62+124+248+=496
15 if(sum==n) 496 is a perfect number
16 printf("\n%d is a perfect number",n);
17 else
18 printf("\n%d is not a perfect number",n);
19 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 115


WAP to check given number is prime or not(while loop)
1 void main()
2 {
3 int n, i=2,flag=0; Output
4 printf("Enter a number:"); Enter a number:7
5 scanf("%d",&n); 7 is a prime number
6 while(i<=n/2)
7 {
Output
8 if(n%i==0)
9 { Enter a number:9
9 is not a prime number
10 flag=1;
11 break;
12 }
13 i++;
14 }
15 if (flag==0)
16 printf("%d is a prime number",n);
17 else
18 printf("%d is not a prime number",n);
19 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 116


for loop
for Loop
 for is an entry controlled loop
 Statements inside the body of for are repeatedly executed till the condition is true
 for is keyword
Syntax
for (initialization; condition; updateStatement)
{
// statements
}

 The initialization statement is executed only once.


 Then, the condition is evaluated. If the condition is false, the for loop is
terminated.
 If the condition is true, statements inside the body of for loop are executed, and
the update statement is updated.
 Again the condition is evaluated.
Prof. Nilesh Gambhava #3110003 (PPS) – Looping 118
WAP to print numbers 1 to n (for loop)

Program Output
1 #include<stdio.h> Enter a number:5
2 void main() 1
3 { 2
4 int i,n; 3
5 printf("Enter a number:"); 4
6 scanf("%d",&n); 5
7 for(i=1;i<=n;i++)
8 {
9 printf("%d\n",i);
10 }
11 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 119


WAP to find factors of a number (for loop)

Program Output
1 #include <stdio.h> Enter n to find factors=12
2 void main() 1,2,3,4,6,12,
3 {
4 int i,n;
5 printf("Enter n to find factors=");
6 scanf("%d",&n);
7 for(i=1;i<=n;i++)
8 {
9 if(n%i==0)
10 printf("%d,",i);
11 }
12 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 120


WAP to check given number is perfect or not(for loop)
1 void main(){
2 int i,n,sum=0;
3 printf("Enter a number:"); Output
4 scanf("%d",&n); Enter a number:6
5 for(i=1;i<n;i++) 1+2+3=6
6 is a perfect number
6 {
7 if(n%i==0)
Output
8 {
9 printf("%d+",i); Enter a number:8
1+2+4+=7
10 sum=sum+i;
8 is not a perfect number
11 }
12 }
Output
13 printf("=%d",sum);
14 if(sum==n) Enter a number:496
1+2+4+8+16+31+62+124+248+=496
15 printf("\n%d is a perfect number",n); 496 is a perfect number
16 else
17 printf("\n%d is not a perfect number",n);
18 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 121


do while loop
do while Loop
 do while is an exit controlled loop.
 Statements inside the body of do while are repeatedly executed till the condition
is true.
 Do and while are keywords. Syntax
do
{
// statement
}
while (condition);

 Loop body will be executed first, and then condition is checked.


 If the condition is true, the body of the loop is executed again and the condition is
evaluated.
 This process goes on until the condition becomes false.
 If the condition is false, the loop ends.
Prof. Nilesh Gambhava #3110003 (PPS) – Looping 123
WAP to print Odd numbers between 1 to n(do while loop)

Program Output
1 void main() Enter a number:5
2 { 1,3,5
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 if(i%2!=0)
9 {
10 printf("%d,",i);
11 }
12 i=i+1;
13 }
14 while(i<=n);
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 124


WAP to find factors of a number(do while loop)

Program Output
1 void main() Enter a number:6
2 { 1,2,3,6,
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 if(n%i==0)
9 {
10 printf("%d,",i);
11 }
12 i=i+1;
13 }
14 while(i<=n);
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 125


WAP to print reverse a number(do while loop)

Program Output
1 void main() Enter a number=1234
2 { 4321
3 int n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 printf("%d",n%10);
9 n=n/10;
10 }
11 while(n!=0);
12 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 126


goto statement
goto Statement
 goto is an virtual loop
 The goto statement allows us to transfer control of the program to the specified
label.
 goto is keyword
Syntax Syntax
goto label; label:
. .
. .
. .
label: goto label;

 The label is an identifier. When the goto statement is encountered, the control of
the program jumps to label: and starts executing the code.

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 128


WAP to print Odd numbers between 1 to n(goto)

Program Output
1 void main() Enter a number:5
2 { 1,3,5
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 odd:
7 if(i%2!=0)
8 {
9 printf("%d,",i);
10 }
11 i=i+1;
12 if(i<=n)
13 {
14 goto odd;
15 }
16 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 129


WAP to find factors of a number(goto)

Program Output
1 void main() Enter a number:6
2 { 1,2,3,6,
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 odd:
7 if(n%i==0)
8 {
9 printf("%d,",i);
10 }
11 i=i+1;
12 if(i<=n)
13 {
14 goto odd;
15 }
16 }

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 130


Types of loops
Entry Control Loop Entry Control Loop Exit Control Loop Virtual Loop
int i=1; int i; int i=1; int i=1;
while(i<=10) for(i=1;i<=10;i++) do labelprint:
{ { { printf("%d",i++);
printf("%d",i++); printf("%d",i); printf("%d",i++); if(i<=10)
} } } goto labelprint;
while(i<=10);

False
Loop Body Label Statement
condition
True True
condition condition
Loop Body
False True False
goto

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 131


Pattern
Always detect pattern in pattern
Pattern
There are important points to note in pattern
1. Determine, how many rows?
2. Determine, how many numbers/characters/columns in a row?
3. Determine, Increment/Decrement among the number of rows.
4. Determine, starting in each row

1 1 1 *
11 12 23 * *
111 123 456 * * *
1111 1234 78910 * * * *
11111 12345 * * *
* *
*

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 133


WAP to print given pattern (nested loop)
* Program
** 1 void main()
*** 2 {
**** 3 int i,j;
***** 4 for(i=1;i<=5;i++)
5 {
No. of rows: 5 6 for(j=1; j<=i; j++)
No. of characters 7 {
Row-1: * 8 printf("*");
Row-2: ** 9 }
Row-3: *** 10 printf("\n");
Row-4: **** 11 }
Row-5: ***** 12 }

Inner loop: Increment


Outer loop: Increment

Starting: *

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 134


WAP to print given pattern (nested loop)
1 Program
12 1 void main()
123 2 {
1234 3 int i,j;
12345 4 for(i=1;i<=5;i++)
5 {
No. of rows: 5 6 for(j=1; j<=i; j++)
No. of values 7 {
Row-1: 1 8 printf("%d",j);
Row-2: 12 9 }
Row-3: 123 10 printf("\n");
Row-4: 1234 11 }
Row-5: 12345 12 }

Inner loop: Increment


Outer loop: Increment

Starting: 1

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 135


WAP to print given pattern (nested loop)
5 Program
54 1 void main()
543 2 {
5432 3 int i,j;
54321 4 for(i=5;i>0;i--)
5 {
No. of rows: 5
6 for(j=5; j>=i ; j--)
No. of values 7 {
Row-1: 5 8 printf("%d",j);
Row-2: 54 9 }
Row-3: 543 10 printf("\n");
Row-4: 5432 11 }
Row-5: 54321 12 }

Inner loop: Decrement


Outer loop:
Decrement/Increment
Starting: 5
Prof. Nilesh Gambhava #3110003 (PPS) – Looping 136
WAP to print given pattern (nested loop)
* Program
** 1 void main() First we need to print 4
*** 2 { spaces before printing *
**** 3 int i,j,k;
***** 4 for(i=1;i<=5;i++)
*
5 {
No. of rows: 5 6 for(k=5;k>i;k--) **

No. of values 7 { ***


Row-1: ----* 8 printf(" ");
****
Row-2: ---** 9 }
Row-3: --*** 10 for(j=1;j<=i;j++) *****
Row-4: -**** 11 {
Row-5: ***** 12 printf("*"); After printing spaces
13 } this inner loop prints *
Inner loop: Decrement 14 printf("\n");
Outer loop: Decrement/Increment 15 }
16 }
Starting: -(space)
Ending: *

Prof. Nilesh Gambhava #3110003 (PPS) – Looping 137


Practice programs
1) Write a program to find sum of first N odd numbers. Ex. 1+3+5+7+………..+N
2) Write a program to find 1+1/2+1/3+1/4+....+1/n.
3) Write a program to print all Armstrong numbers in a given range. For example 153 = 1^3 + 5^3 +
3^3. So, 153 is Armstrong number.
4) Write a program to print given number in reverse order
5) Write a program to check whether a given string is palindrome or not.
6) Write a program to print Multiplication Table up to n.
1 2 3 4 5 6 7 .
2 4 6 8 10 12 14 .
3 6 9 12 15 18 21 .
4 8 12 16 20 24 28 .
5 10 15 20 25 30 35 .
. . . . . . . .

7) Construct C programs to print the following patterns using loop statement.


1 * 1 1 1 * * * * * * * * * *
22 # # 0 1 2 2 A B * * * * * *
333 * * * 1 0 1 3 3 3 2 3 4 * * * * *
4444 # # # # 0 1 0 1 4 4 4 4 C D E F * * * * * * *
55555 * * * * * *
Prof. Nilesh Gambhava #3110003 (PPS) – Looping 138

Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Array & {C}


Programming

Strings

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
Need of Array Variable
 Suppose we need to store rollno of the student in the integer variable.
Declaration
int rollno;

 Now we need to store rollno of 100 students.


Declaration
int rollno101, rollno102, rollno103, rollno104...;

 This is not appropriate to declare these many integer variables.


e.g. 100 integer variables for rollno.
 Solution to declare and store multiple variables of similar type is an array.
 An array is a variable that can store multiple values.

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 141


Definition: Array
 An array is a fixed size sequential collection of elements of same data type grouped
under single variable name.

[0] [1] [2] … [99]


int rollno[100];

Fixed Size Sequential Same Data type Single Name


Here, the size of an It is indexed to 0 to 99 All the elements (0-99) All the elements (0-99)
array is 100 (fixed) to in sequence will be integer will be referred as a
store rollno variables common name rollno

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 142


Declaring an array
Syntax  By default array index starts
data-type variable-name[size]; with 0.
 If we declare an array of size
5 then its index ranges from
Integer Array [0] [1] [2] [3] [4] 0 to 4.
int mark[5];
 First element will be store at
mark[0] and last element
integer will be stored at mark[4] not
mark[5].
Float Array [0] [1] [2] [3] [4]  Like integer and float array
float avg[5];
we can declare array of type
char.

float

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 143


Initialing and Accessing an Array
Declaring, initializing and accessing single integer variable
int mark=90; //variable mark is initialized with value 90
printf("%d",mark); //mark value printed

Declaring, initializing and accessing integer array variable


int mark[5]={85,75,76,55,45}; //mark is initialized with 5 values
printf("%d",mark[0]); //prints 85
printf("%d",mark[1]); //prints 75
printf("%d",mark[2]); //prints 65
printf("%d",mark[3]); //prints 55
printf("%d",mark[4]); //prints 45

[0] [1] [2] [3] [4]


mark[5] 85 75 65 55 45

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 144


Read(Scan) Array Elements
Reading array without loop Reading array using loop
1 void main() 1 void main()
2 { 2 {
3 int mark[5]; 3 int mark[5],i;
printf("Enter array element="); for(i=0;i<5;i++)
4 4
scanf("%d",&mark[0]); {
5 printf("Enter array element="); 5 printf("Enter array element=");
6 scanf("%d",&mark[1]); 6 scanf("%d",&mark[i]);
7 printf("Enter array element="); 7 }
8 scanf("%d",&mark[2]); 8 for(i=0;i<5;i++)
9 printf("Enter array element="); 9 {
10 scanf("%d",&mark[3]); 10 printf("%d",mark[i]);
11 printf("Enter array element="); 11 }
scanf("%d",&mark[4]); }
12 12
13 printf("%d",mark[0]);
14 printf("%d",mark[1]);
15 printf("%d",mark[2]);
16 printf("%d",mark[3]); [0] [1] [2] [3] [4]
17 printf("%d",mark[4]); mark[5] 85 75 65 55 45
18 }

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 145


Develop a program to count number of positive or negative
number from an array of 10 numbers.
Program
1 void main(){
2 int num[10],i,pos,neg; Output
3 pos = 0; Enter array element=1
4 neg = 0; Enter array element=2
5 for(i=0;i<10;i++) Enter array element=3
6 { Enter array element=4
7 printf("Enter array element="); Enter array element=5
8 scanf("%d",&num[i]); Enter array element=-1
9 } Enter array element=-2
10 for(i=0;i<10;i++) Enter array element=3
11 { Enter array element=4
12 if(num[i]>0) Enter array element=5
13 pos=pos+1; Positive=8,Negative=2
14 else
15 neg=neg+1;
16 }
17 printf("Positive=%d,Negative=%d",pos,neg);
18 }

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 146


Develop a program to read n numbers in an array and print
them in reverse order.
Program
1 void main()
2 { Output
3 int num[100],n,i; Enter number of array
4 printf("Enter number of array elements="); elements=5
5 scanf("%d",&n); Enter array element=1
6 //loop will scan n elements only Enter array element=2
7 for(i=0;i<n;i++) Enter array element=3
8 { Enter array element=4
9 printf("Enter array element="); Enter array element=5
10 scanf("%d",&num[i]); 5
11 } 4
12 //negative loop to print array in reverse order 3
13 for(i=n-1;i>=0;i--) 2
14 { 1
15 printf("%d\n",num[i]);
16 }
17 }

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 147


Practice Programs
1) Develop a program to calculate sum of n array elements in C.
2) Develop a program to calculate average of n array elements in C.
3) Develop a program to find largest array element in C.
4) Develop a program to print sum of second and second last element of an array.
5) Develop a program to copy array elements to another array.
6) Develop a program to count odd and even elements of an array.

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 148


Multi Dimensional Array
Declaring 2 Dimensional Array
Syntax  A two dimensional array can
data-type variable-name[x][y]; be seen as a table with ‘x’
rows and ‘y’ columns.
Declaration  The row number ranges from
int data[3][3]; //This array can hold 9 elements 0 to (x-1) and column
number ranges from 0 to
(y-1).
int data[3][3];
Column-0 Column-1 Column-2

Row-0 data[0][0] data[0][1] data[0][2]

Row-1 data[1][0] data[1][1] data[1][2]

Row-2 data[2][0] data[2][1] data[2][2]

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 150


Initialing and Accessing a 2D Array: Example-1
Program
1 int data[3][3] = {
2 {1,2,3}, //row 0 with 3 elements
3 {4,5,6}, //row 1 with 3 elements
4 {7,8,9} //row 2 with 3 elements
5 }; Column-0 Column-1 Column-2
6 printf("%d",data[0][0]); //1
7 printf("%d",data[0][1]); //2 Row-0 1 2 3
8 printf("%d\n",data[0][2]); //3
9 Row-1 4 5 6
10 printf("%d",data[1][0]); //4
11 printf("%d",data[1][1]); //5 Row-2 7 8 9
12 printf("%d\n",data[1][2]); //6
13
14 printf("%d",data[2][0]);//7
15 printf("%d",data[2][1]); //8
16 printf("%d",data[2][2]); //9
1 // data[3][3] can be initialized like this also
2 int data[3][3]={{1,2,3},{4,5,6},{7,8,9}};
Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 151
Initialing and Accessing a 2D Array: Example-2
Program
1 int data[2][4] = {
2 {1,2,3,4}, //row 0 with 4 elements
3 {5,6,7,8}, //row 1 with 4 elements
4 };
5 printf("%d",data[0][0]); //1
6 printf("%d",data[0][1]); //2 Col-0 Col-1 Col-2 Col-3
7 printf("%d",data[0][2]); //3
8 printf("%d\n",data[0][3]); //4 Row-0 1 2 3 4
9
10 printf("%d",data[1][0]); //5 Row-1 5 6 7 8
11 printf("%d",data[1][1]); //6
12 printf("%d",data[1][2]); //7
13 printf("%d",data[1][3]); //8

1 // data[2][4] can be initialized like this also


2 int data[2][4]={{1,2,3,4},{5,6,7,8}};

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 152


Read(Scan) 2D Array Elements
Program
1 void main(){
2 int data[3][3],i,j;
3 for(i=0;i<3;i++)
4 {
5 for(j=0;j<3;j++)
6 { Output
7 printf("Enter array element="); Enter array element=1
8 scanf("%d",&data[i][j]); Enter array element=2
9 } Enter array element=3
10 } Enter array element=4
11 for(i=0;i<3;i++) Enter array element=5
12 { Enter array element=6
13 for(j=0;j<3;j++) Enter array element=7
14 { Enter array element=8
15 printf("%d",data[i][j]); Enter array element=9
16 } 123
17 printf("\n"); 456
18 } 789
19 }
Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 153
Develop a program to count number of positive, negative and
zero elements from 3 X 3 matrix
Program
1 void main(){
2 int data[3][3],i,j,pos=0,neg=0,zero=0; Output
3 for(i=0;i<3;i++) Enter array element=9
4 { Enter array element=5
5 for(j=0;j<3;j++) Enter array element=6
6 { Enter array element=-3
7 printf("Enter array element="); Enter array element=-7
8 scanf("%d",&data[i][j]); Enter array element=0
9 if(data[i][j]>0) Enter array element=11
10 pos=pos+1; Enter array element=13
11 else if(data[i][j]<0) Enter array element=8
12 neg=neg+1; positive=6,negative=2,zero=1
13 else
14 zero=zero+1;
15 }
16 }
17 printf("positive=%d,negative=%d,zero=%d",pos,neg,zero);
18 }

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 154


Practice Programs
1. Develop a program to perform addition of two matrix.
2. Develop a program to perform multiplication of two matrix.

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 155


String
(Character Array)
Definition: String
 A String is a one-dimensional array of characters terminated by a null('\0').

[0] [1] [2] … [9]


char name[10];

 Each character in the array occupies one byte of memory, and the last character
must always be null('\0').
 The termination character ('\0') is important in a string to identify where the
string ends.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10] D A R S H A N \0

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 157


Declaring & Initializing String
Declaration
char name[10];

Initialization method 1:
char name[10]={'D','A','R','S','H','A','N','\0'};

Initialization method 2:
char name[10]="DARSHAN";
//'\0' will be automatically inserted at the end in this type of declaration.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10] D A R S H A N \0

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 158


Read String: scanf()
Program
Output
1 void main()
2 { Enter name: Darshan
3 char name[10]; Name=Darshan
4 printf("Enter name:"); Output
5 scanf("%s",name);
Enter name: CE Darshan
6 printf("Name=%s",name);
Name=CE
7 }

 There is no need to use address of (&) operator in scanf to store a string.


 As string name is an array of characters and the name of the array, i.e., name
indicates the base address of the string (character array).
 scanf() terminates its input on the first whitespace(space, tab, newline etc.)
encountered.

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 159


Read String: gets()
Program
1 #include<stdio.h> Output
2 void main() Enter name:Darshan Institute
3 { Name=Darshan Institute
4 char name[10];
5 printf("Enter name:");
6 gets(name); //read string including white spaces
7 printf("Name=%s",name);
8 }

 gets(): Reads characters from the standard input and stores them as a string.
 puts(): Prints characters from the standard.
 scanf(): Reads input until it encounters whitespace, newline or End Of File(EOF)
whereas gets() reads input until it encounters newline or End Of File(EOF).
 gets(): Does not stop reading input when it encounters whitespace instead it
takes whitespace as a string.

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 160


String Handling Functions : strlen()
 C has several inbuilt functions to operate on string. These functions are known as
string handling functions.
 strlen(s1): returns length of a string in integer

Program
1 #include <stdio.h> Output
2 #include <string.h> //header file for string functions Enter string: CE Darshan
3 void main() 10
4 {
5 char s1[10];
6 printf("Enter string:");
7 gets(s1);
8 printf("%d",strlen(s1)); // returns length of s1 in integer
9 }

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 161


String Handling Functions: strcmp()
 strcmp(s1,s2): Returns 0 if s1 and s2 are the same.
 Returns less than 0 if s1<s2.
 Returns greater than 0 if s1>s2.
Program
1 void main() Output
2 { Enter string-1:Computer
3 char s1[10],s2[10]; Enter string-2:Computer
4 printf("Enter string-1:"); Strings are same
5 gets(s1);
6 printf("Enter string-2:"); Output
7 gets(s2); Enter string-1:Computer
8 if(strcmp(s1,s2)==0) Enter string-2:Computer
9 printf("Strings are same"); Strings are same
10 else
11 printf("Strings are not same");
12 }

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 162


String Handling Functions
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description
strcpy(s1,s2) Copies 2nd string to 1st string.
strcpy(s1,s2) copies the string s2 in to string s1 so s1 is now “There”. s2
remains unchanged.

strcat(s1,s2) Appends 2nd string at the end of 1st string.


strcat(s1,s2); a copy of string s2 is appended at the end of string s1.
Now s1 becomes “TheirThere”

strchr(s1,c) Returns a pointer to the first occurrence of a given character in the string s1.
printf("%s",strchr(s1,'i'));
Output : ir

strstr(s1,s2) Returns a pointer to the first occurrence of a given string s2 in string s1.
printf("%s",strstr(s1,"he"));
Output : heir

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 163


String Handling Functions (Cont…)
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description
strrev(s1) Reverses given string.
strrev(s1); makes string s1 to “riehT”
strlwr(s1) Converts string s1 to lower case.
printf("%s",strlwr(s1)); Output : their
strupr(s1) Converts string s1 to upper case.
printf("%s",strupr(s1)); Output : THEIR
strncpy(s1,s2,n) Copies first n character of string s2 to string s1
s1=""; s2="There";
strncpy(s1,s2,2);
printf("%s",s1); Output : Th
strncat(s1,s2,n) Appends first n character of string s2 at the end of string s1.
strncat(s1,s2,2);
printf("%s", s1); Output : TheirTh
Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 164
String Handling Functions (Cont…)
For examples consider: char s1[]="Their",s2[]="There";
Syntax Description
strncmp(s1,s2,n) Compares first n character of string s1 and s2 and returns similar result as
strcmp() function.
printf("%d",strcmp(s1,s2,3)); Output : 0
strrchr(s1,c) Returns the last occurrence of a given character in a string s1.
printf("%s",strrchr(s2,'e')); Output : ere

Prof. Nilesh Gambhava #3110003 (PPS) – Array and Strings 165


Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Functions {C}
Programming

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
What is Function?
 A function is a group of statements that perform a specific task.
 It divides a large program into smaller parts.
 A function is something like hiring a person to do a specific job for you.
 Every C program can be thought of as a collection of these functions.
 Program execution in C language starts from the main function.
Syntax
void main()
{
// body part
}

 Why function ?
 Avoids rewriting the same code over and over.
 Using functions it becomes easier to write programs and keep track of what they doing.

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 168


Types of Function
Function

Library Function User Defined Function (UDF)

Predefined or inbuilt Created by User


Declarations inside header files Programmer need to declare it
Eg. printf() – stdio.h Eg. findSimpleInterest()
pow() – math.h areaOfCircle()
strcmp() – string.h

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 169


Program Structure for Function
 When we use a user-defined function program structure is divided into three parts.
Function Structure
void func1(); Function Prototype

void main()
{
....
func1(); Function call
}

void func1()
{
.... Function definition
//function body
....
}

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 170


Function Prototype
 A function Prototype also know as function declaration.
 A function declaration tells the compiler about a function name and how to call the
function.
 It defines the function before it is being used or called.
 A function prototype needs to be written at the beginning of the program.

Syntax Example
return-type function-name (arg-1, arg 2, …); void addition(int, int);

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 172


Function Definition
 A function definition defines the functions header and body.
 A function header part should be identical to the function prototype.
 Function return type
 Function name
 List of parameters
 A function body part defines function logic.
 Function statements

Syntax Example
return-type function-name (arg-1, arg 2, …) void addition(int x, int y)
{ {
//... Function body printf("Addition is=%d“,(x+y));
} }

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 173


WAP to add two number using add(int, int) Function
Program Output
1 #include <stdio.h> Addition is = 11
2 void add(int, int); // function declaration
3
4 void main()
5 {
6 int a = 5, b = 6;
7 add(a, b); // function call
8 }
9
10 void add(int x, int y) // function definition
11 {
12 printf("Addition is = %d", x + y);
13 }

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 174


Actual parameters and Formal parameters
 Values that are passed to the called function from the main function are known
as Actual parameters.
 The variables declared in the function prototype or definition are known as Formal
parameters.
 When a method is called, the formal parameter is temporarily "bound" to the
actual parameter.

Actual parameters Formal parameters


void main() void add(int x, int y) // x and y are
{ formal parameters.
int a = 5, b = 6; {
add(a, b); // a and b are the printf("Addition is = %d", x + y);
actual parameters in this call.
} }

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 175


Return Statement
 If function is returning a value to calling function, it needs to use the keyword
return.
 The called function can only return one value per call.

Syntax
return;
Or

return (expression);

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 176


WAP to find maximum number from two number
Program Output
1 #include <stdio.h> Max value is : 200
2 int max(int a, int b);
3 void main()
4 {
5 int a = 100;
6 int b = 200;
7 int maxvalue;
8 maxvalue = max(a, b);
9 printf("Max value is : %d\n",
10 maxvalue);
11 }
12 int max(int a, int b)
13 {
14 if (a > b)
15 return a; // return a
16 else
17 return b; // return b
18 }

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 177


WAP to calculate the Power of a Number
Program Output
1 #include <stdio.h> Enter any number : 5
2 int power(int, int); Enter power of number : 3
3 void main() 5's power 3 = 125
4 {
5 int num, pow, res;
6 printf("Enter any number : ");
7 scanf("%d", &num);
8 printf("Enter power of number : ");
9 scanf("%d", &pow);
10 res = power(num, pow);
11 printf("%d's power %d = %d", num, pow, res);
12 }
13 int power(int n, int p)
14 { int r = 1;
15 while (p >= 1)
16 {
17 r = r * n;
18 p--;
19 }
20 return r;}

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 178


WAP to find Factorial of a Number
Program Output
1 #include <stdio.h> Enter the number :
2 int fact(int); 5
3 int main() factorial = 120
4 {
5 int n, f;
6 printf("Enter the number :\n");
7 scanf("%d", &n);
8 f = fact(n);
9 printf("factorial = %d", f);
10 }
11 int fact(int n)
12 {
13 int i, fact = 1;
14 for (i = 1; i <= n; i++)
15 fact = fact * i;
16 return fact;
17 }

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 179


WAP to check Number is Prime or not
Program Program contd.
1#include <stdio.h> 14 int checkPrime(int n1)
2int checkPrime(int); 15 {
3void main() 16 int i = 2;
4{ 17 while (i <= n1 / 2)
5 int n1, prime; {
6 printf("Enter the number :");
18 if (n1 % i == 0)
7 scanf("%d", &n1); 19 return 0;
8 prime = checkPrime(n1); 20 else
9 if (prime == 1) 21 i++;
10 printf("The number %d is a prime 22 }
number.\n", n1); 23 return 1;
11 else 24 }
12 printf("The number %d is not a prime
number.\n", n1);
13 }

Output
Enter the number :7
The number 7 is a prime number.

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 180


Category of Function
(1) Function with no argument and but no return value
No
void main() Input void fun1()
{ {
..... .....
No return
fun1(); .....
value
..... .....
} }

(2) Function with no argument and returns value


No
void main() Input int fun1(void)
{ {
..... .....
a = fun1() Function .....
..... result return b;
} }

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 181


Category of Function cont.
(3) Function with argument and but no return value
Value of
void main() Argument void fun1(int f)
{ {
..... .....
fun1(a); No Return .....
..... value .....
} }

(4) Function with argument and returns value


Value of
void main() Argument int fun1(int f)
{ {
..... .....
b = fun1(a); Function .....
..... Result return e;
} }

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 182


Storage Classes
 Storage class decides the scope, lifetime and memory allocation of variable.
 Scope of a variable is the boundary within which a variable can be used.

Storage Initial
Storage Scope Life Example
Specifier Value

Automatic int a;
Stack Garbage Within block End of block
{auto} auto int a;

Register CPU Garbage Within block End of block


register int var;
{register} register

External Data Global Till end of


Zero extern int var;
{extern} segment Multiple file program

Till end of
Static Data Zero Within block static extern int var;
program
{static} segment static int var;

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 183


Static Example
Program Output
1 #include <stdio.h> Counter = 1
2 int incrementCounter(); Counter = 2
3
4 void main()
5 {
6 printf("Counter = %d \n", incrementCounter());
7 printf("Counter = %d \n", incrementCounter());
8 }
9
10 int incrementCounter()
11 {
12 static int count = 0; // static variable
13 count++;
14 return count;
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 184


Advantages of Function
 Using function we can avoid rewriting the same logic or code again and again in a
program.
 We can track or understand large program easily when it is divide into functions.
 It provides reusability.
 It help in testing and debugging because it can be tested for errors individually in
the easiest way.
 Reduction in size of program due to code of a function can be used again and
again, by calling it.

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 185


Practice Programs
1) WAP to count simple interest using function.
2) WAP that defines a function to add first n numbers.
3) WAP using global variable, static variable.
4) WAP that will scan a character string passed as an argument and convert all
lowercase character into their uppercase equivalents.
5) Build a function to check number is prime or not. If number is prime then
function return value 1 otherwise return 0.
6) Write a program to calculate nCr using user defined function. nCr = n! / (r! * (n-
r)!)
7) Create a function to swap the values of two variables.
8) Write a function which takes 2 numbers as parameters and returns the gcd of the
2 numbers. Call the function in main().

Prof. Nilesh Gambhava #3110003 (PPS) – Functions 186


Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Recursion {C}
Programming

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
What is Recursion?
 Any function which calls itself is called recursive function and such function calls
are called recursive calls.
 Recursion cannot be applied to all problems, but it is more useful for the tasks that
can be defined in terms of a similar subtask.
 It is idea of representing problem a with smaller problems.
 Any problem that can be solved recursively can be solved iteratively.
 When recursive function call itself, the memory for called function allocated and
different copy of the local variable is created for each function call.
 Some of the problem best suitable for recursion are
 Factorial
 Fibonacci
 Tower of Hanoi

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 189


Working of Recursive function
Working
void func1();

void main()
{
....
func1();
.... Function
} call

void func1()
{ Recursive
.... function call
func1();
....
}

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 190


Properties of Recursion
 A recursive function can go infinite like a loop. To avoid infinite running of recursive
function, there are two properties that a recursive function must have.
 Base Case or Base criteria
 It allows the recursion algorithm to stop.
 A base case is typically a problem that is small enough to solve directly.
 Progressive approach
 A recursive algorithm must change its state in such a way that it moves forward to the base
case.

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 191


Recursion - factorial example
 The factorial of a integer n, is Recursive trace
product of
 n * (n-1) * (n-2) * …. * 1 Final Ans 5 *24 = 120

 Recursive definition of factorial Fact(5)


 n! = n * (n-1)! call
return 4 * 6 = 24
 Example
 3! = 3 * 2 * 1 Fact(4)
return 3 * 2 = 6
 3! = 3 * (2 * 1) call
 3! = 3 * (2!)
Fact(3)
return 2 * 1 = 2
call
Fact(2)
return 1
call
Fact(1)

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 192


WAP to find factorial of given number using Recursion
Program Output
1 #include <stdio.h> Enter the number? 5
2 int fact(int); factorial = 120
3 void main()
4 {
5 int n, f;
6 printf("Enter the number?\n");
7 scanf("%d", &n);
8 f = fact(n);
9 printf("factorial = %d", f);
10 }
11 int fact(int n)
12 {
13 if (n == 0)
14 return 1;
15 else if (n == 1)
16 return 1;
17 else
18 return n * fact(n - 1);
19 }

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 193


Recursion - Fibonacci example
 A series of numbers , where next Recursive trace
number is found by adding the two
number before it. Fib(4) Final Ans. 3

 Recursive definition of Fibonacci return 2 return 1


 Fib(0) = 0
 Fib(1) = 1 Fib(3) Fib(2)
 Fib(n) = Fib(n-1) + Fib(n-2)
return 1 return 1 return 0
 Example return 1
Fib(2) Fib(1) Fib(1) Fib(0)
 Fib(4) = Fib(3) + Fib(2)
 Fib(4) = 3
return 1 return 0
Fib(1) Fib(0)

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 194


WAP to Display Fibonacci Sequence
Program Program contd.
1 #include <stdio.h> 15 int fibonacci(int n)
2 int fibonacci(int); 16 {
3 void main() 17 if (n == 0 || n == 1)
4 { 18 return n;
5 int n, m = 0, i; 19 else
6 printf("Enter Total terms\n"); 20 return (fibonacci(n - 1) +
7 scanf("%d", &n); fibonacci(n - 2));
8 printf("Fibonacci series\n"); 21 }
9 for (i = 1; i <= n; i++)
10 { Output
11 printf("%d ", fibonacci(m)); Enter Total terms
12 m++; 5
13 } Fibonacci series
14 } 0 1 1 2 3

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 195


Recursion - Decimal to Binary example
 To convert decimal to binary, divide Recursive trace
decimal number by 2 till dividend
will be less then 2 Final Ans 13%2 + 10*110 = 1101
 To convert decimal 13 to binary decToBin(13)
 13/2 = 6 reminder 1 return 6%2 + 10*11 = 110
call
 6/2 = 6 reminder 0
 3/2 = 3 reminder 1 decToBin(6)
 1/2 = 1 reminder 1 call
return 3%2 + 10*1 = 11

 Recursive definition of Decimal to decToBin(3)


Binary return 1%2 + 10*0 = 1
call
 decToBin(0) = 0
 decToBin(n) = n%2 + 10* decToBin(n/2) decToBin(1)

 Example call
return 0

 decToBin(13) = 13%2 + 10 decToBin(6) decToBin(0)


 decToBin(13) = 1101
Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 196
WAP to Convert Decimal to Binary
Program Output
1 #include <stdio.h> Enter a decimal number: 12
2 int convertDecimalToBinary(int); The binary equivalent = 1100
3 void main()
4 {
5 int dec, bin;
6 printf("Enter a decimal number: ");
7 scanf("%d", &dec);
8 bin = convertDecimalToBinary(dec);
9 printf("The binary equivalent = %d \n",bin);
10 }
11 int convertDecimalToBinary(int dec)
12 {
13 if (dec == 0)
14 return 0;
15 else
16 return (dec % 2 + 10 *
convertDecimalToBinary(dec / 2));
17 }

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 197


WAP to Convert Binary to Decimal
Program Output
1 #include <stdio.h> Enter a binary number: 101
2 int convertBinaryToDecimal(int b, int c, int t); Decimal value of 101 is 5
3 void main()
4 {
5 unsigned int binary, decimal;
6 printf("Enter a binary number: ");
7 scanf("%d", &binary);
8 decimal = convertBinaryToDecimal(binary, 1, 0);
9 printf("Decimal value of %d is %d", binary, decimal);
10 }
11 int convertBinaryToDecimal(int b, int c, int t)
12 {
13 if (b > 0)
14 {
15 t += (b % 10) * c;
16 convertBinaryToDecimal(b / 10, c * 2, t);
17 }
18 else
19 return t;
20 }

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 198


Practice Programs
1) Write a program to find factorial of a given number using recursion.
2) WAP to convert decimal number into binary using recursion.
3) WAP to use recursive calls to evaluate F(x) = x – x3/3! + x5/5! – x7/7! + … + xn/n!

Prof. Nilesh Gambhava #3110003 (PPS) – Recursion 199


Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Pointer {C}
Programming

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
What is Pointer?
 A normal variable is used to store value.
 A pointer is a variable that store address / reference of another variable.
 Pointer is derived data type in C language.
 A pointer contains the memory address of that variable as their value. Pointers are
also called address variables because they contain the addresses of other variables.

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 202


Declaration & Initialization of Pointer
Syntax Output
1 datatype *ptr_variablename; 10 10 5000

Example
1 void main()
2 { Variable Value Address
3 int a=10, *p; // assign memory address of a
4 to pointer variable p a 10 5000
5 p = &a;
6 printf("%d %d %d", a, *p, p); p 5048
7 }
5000

 p is integer pointer variable


 & is address of or referencing operator which returns memory address of variable.
 * is indirection or dereferencing operator which returns value stored at that memory
address.
 & operator is the inverse of * operator
 x = a is same as x = *(&a)
Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 203
Why use Pointer?
 C uses pointers to create dynamic data structures, data structures built up from
blocks of memory allocated from the heap at run-time. Example linked list, tree,
etc.
 C uses pointers to handle variable parameters passed to functions.
 Pointers in C provide an alternative way to access information stored in arrays.
 Pointer use in system level programming where memory addresses are useful. For
example shared memory used by multiple threads.
 Pointers are used for file handling.
 This is the reason why C is versatile.

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 204


Pointer to Pointer – Double Pointer
 Pointer holds the address of another variable of same type.
 When a pointer holds the address of another pointer then such type of pointer is
known as pointer-to-pointer or double pointer.
 The first pointer contains the address of the second pointer, which points to the
location that contains the actual value.
Syntax
Pointer Pointer Variable
1 datatype **ptr_variablename;
address address value
Example
1 int **ptr;

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 205


Write a program to print variable, address of pointer variable and pointer to pointer variable.

WAP to print Odd numbers between 1 to n


Program
1 #include <stdio.h>
2 int main () {
3 int var;
4 int *ptr;
5 int **pptr;
6 var = 3000;
7 ptr = &var; // address of var
8 pptr = &ptr; // address of ptr using address of operator &
9 printf("Value of var = %d\n", var );
10 printf("Value available at *ptr = %d\n", *ptr );
11 printf("Value available at **pptr = %d\n", **pptr);
12 return 0;
13 }

Output
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 206


Relation between Array & Pointer
 When we declare an array, compiler allocates continuous blocks of memory so that
all the elements of an array can be stored in that memory.
 The address of first allocated byte or the address of first element is assigned to an
array name.
 Thus array name works as pointer variable.
 The address of first element is also known as base address.

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 207


Relation between Array & Pointer – Cont.
 Example: int a[10], *p;
 a[0] is same as *(a+0), a[2] is same as *(a+2) and a[i] is same as *(a+i)

a: a[0] a: *(a+0) 2000

a[1] a+1: *(a+1) 2002


. .
. .
. .
. .
a[i] a+i: *(a+i) 2000 + i*2
. .
. .
. .
. .
a[9] a+9: *(a+9) 2018

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 208


Array of Pointer
 As we have an array of char, int, float etc, same way we can have an array of pointer.
 Individual elements of an array will store the address values.
 So, an array is a collection of values of similar type. It can also be a collection of
references of similar type known by single name.

Syntax
1 datatype *name[size];

Example
1 int *ptr[5]; //declares an array of integer pointer of size 5

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 209


Array of Pointer – Cont.
 An array of pointers ptr can be used to point to different rows of matrix as follow:
Example
1 for(i=0; i<5; i++)
2 {
3 ptr[i]=&mat[i][0];
4 }

ptr 0 1 2
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]

 By dynamic memory allocation, we do not require to declare two-dimensional


array, it can be created dynamically using array of pointers.
Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 210
Write a program to swap value of two variables using pointer / call by reference.

WAP to print Odd numbers between 1 to n


Program
1 int main()
2 {
3 int num1,num2;
4 printf("Enter value of num1 and num2: ");
5 scanf("%d %d",&num1, &num2);
6
7 //displaying numbers before swapping
8 printf("Before Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
9
10 //calling the user defined function swap()
11 swap(&num1,&num2);
12
13 //displaying numbers after swapping
14 printf("After Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
15 return 0;
16 }

Output
Enter value of num1 and num2: 5
10
Before Swapping: num1 is: 5, num2 is: 10
After Swapping: num1 is: 10, num2 is: 5

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 211


Pointer and Function
 Like normal variable, pointer variable can be passed as function argument and
function can return pointer as well.
 There are two approaches to passing argument to a function:
 Call by value
 Call by reference / address

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 212


Call by Value
 In this approach, the values are passed as function argument to the definition of
function.
Program Output
1 #include<stdio.h> Values before calling 10, 20
2 void fun(int,int); Values after calling 10, 20
3 int main()
4 {
5 int A=10,B=20;
6 printf("\nValues before calling %d, %d",A,B);
7 fun(A,B); Address 48252 24688
8 printf("\nValues after calling %d, %d",A,B);
9 return 0; Value 10 20 10 11 20 22
10 }
11 void fun(int X,int Y) Variable A B X Y
12 {
13 X=11;
14 Y=22;
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 213


Call by Reference / Address
 In this approach, the references / addresses are passed as function argument to the
definition of function.
Program
Output
1 #include<stdio.h>
Values before calling 10, 20
2 void fun(int*,int*); Values after calling 11, 22
3 int main()
4 {
5 int A=10,B=20;
6 printf("\nValues before calling %d, %d",A,B);
7 fun(&A,&B); Address 24688
48252
8 printf("\nValues after calling %d, %d",A,B);
9 return 0; Value 10 11 20 22 48252 24688
10 }
11 void fun(int *X,int *Y) Variable A B *X *Y
12 {
13 *X=11;
14 *Y=22;
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 214


Pointer to Function
 Every function has reference or address, and if we know the reference or address of
function, we can access the function using its reference or address.
 This is the way of accessing function using pointer.
Syntax
1 return-type (*ptr-function)(argument list);

 return-type: Type of value function will return.


 argument list: Represents the type and number of value function will take, values
are sent by the calling statement.
 (*ptr-function): The parentheses around *ptr-function tells the compiler that it is
pointer to function.
 If we write *ptr-function without parentheses then it tells the compiler that ptr-
function is a function that will return a pointer.

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 215


Write a program to sum of two numbers using pointer to function.

WAP to print Odd numbers between 1 to n


Program
1 #include<stdio.h> Output
2 int Sum(int,int); Enter 1st number : 5
3 int (*ptr)(int,int);
4 int main() Enter 2nd number : 10
5 {
6 int a,b,rt; The sum is : 15
7 printf("\nEnter 1st number : ");
8 scanf("%d",&a);
9 printf("\nEnter 2nd number : ");
10 scanf("%d",&b);
11 ptr = Sum;
12 rt = (*ptr)(a,b);
13 printf("\nThe sum is : %d",rt);
14 return 0;
15 }
16 int Sum(int x,int y)
17 {
18 return x + y;
19 }

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 216


Practice Programs
1. Write a C program to print the address of variable using pointer.
2. Write a C a program to swap two elements using pointer.
3. Write a C a program to print value and address of a variable
4. Write a C a program to calculate sum of two numbers using pointer
5. Write a C a program to swap value of two numbers using pointer
6. Write a C a program to calculate sum of elements of an array using pointer
7. Write a C a program to swap value of two variables using function
8. Write a C a program to print the address of character and the character of string using pointer
9. Write a C a program for sorting using pointer

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 217


Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Structure {C}
Programming

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
Data Types
 Data types are defined as the data storage format that a variable can store a data.

Data types in C

Primary Data type


Secondary Data type
(int, float, char)

Derived Data type User defined Data type


(array, pointer) (structure, union, enum)

 C language has built-in datatypes like primary and derived data types.
 But, still not all real world problems can be solved using those data types.
 We need custom datatype for different situation.
Prof. Nilesh Gambhava #3110003 (PPS) – Structure 220
User Defined Datatype
 We need combination of various datatypes to understand different entity/object.
 Example-1:
 Book Title: Let Us C Datatype: char / string
Author: Yashavant Kanetkar Datatype: char / string
Page: 320 Datatype: int
Price: 255.00 Datatype: float
 Example-2:
 Student Name: ABC Datatype: char / string
Roll_No: 180540107001 Datatype: int
CPI: 7.46 Datatype: float
Backlog: 01 Datatype: int

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 221


What is Structure?
 Structure is a collection of logically related data items of different datatypes
grouped together under single name.
 Structure is a user defined datatype.
 Structure helps to build a complex datatype which is more meaningful than an
array.
 But, an array holds similar datatype record, when structure holds different
datatypes records.
 Two fundamental aspects of Structure:
 Declaration of Structure Variable
 Accessing of Structure Member

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 222


Syntax to Define Structure
 To define a structure, we need to use struct keyword.
 This keyword is reserved word in C language. We can only use it for structure and
its object declaration.
Syntax
1 struct structure_name structure_name is name of custom type
2 {
3 member1_declaration;
4 member2_declaration;
5 . . . memberN_declaration is individual member
6 memberN_declaration; declaration
7 };

 Members can be normal variables, pointers, arrays or other structures.


 Member names within the particular structure must be distinct from one another.

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 223


Example to Define Structure
Example
1 struct student
2 {
3 char name[30]; // Student Name
4 int roll_no; // Student Roll No
5 float CPI; // Student CPI
6 int backlog; // Student Backlog
7 };

 You must terminate structure definition with semicolon ;.


 You cannot assign value to members inside the structure definition, it will cause
compilation error.
Example
1 struct student
2 {
3 char name[30] = “ABC”; // Student Name
4 . . .
5 };
Prof. Nilesh Gambhava #3110003 (PPS) – Structure 224
Create Structure variable
 A data type defines various properties about data stored in memory.
 To use any type we must declare its variable.
 Hence, let us learn how to create our custom structure type objects also known
as structure variable.
 In C programming, there are two ways to declare a structure variable:
1. Along with structure definition
2. After structure definition

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 225


Create Structure Variable – Cont.
1. Declaration along with the structure definition
Syntax Example
1 struct structure_name 1 struct student
2 { 2 {
3 member1_declaration; 3 char name[30]; // Student Name
4 member2_declaration; 4 int roll_no; // Student Roll No
5 . . . 5 float CPI; // Student CPI
6 memberN_declaration; 6 int backlog; // Student Backlog
7 } structure_variable; 7 } student1;

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 226


Create Structure Variable – Cont.
2. Declaration after Structure definition
Syntax
1 struct structure_name structure_variable;

Example
1 struct student
2 {
3 char name[30]; // Student Name
4 int roll_no; // Student Roll No
5 float CPI; // Student CPI
6 int backlog; // Student Backlog
7 };
8 struct student student1; // Declare structure variable

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 227


Access Structure member (data)
 Structure is a complex data type, we cannot assign any value directly to it
using assignment operator.
 We must assign data to individual structure members separately.
 C supports two operators to access structure members, using a structure variable.
1. Dot/period operator (.)
2. Arrow operator (->)

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 228


Access Structure member (data) – Cont.
1. Dot/period operator (.)
 It is known as member access operator. We use dot operator to access members of simple
structure variable.

Syntax Example
1 structure_variable.member_name; 1 // Assign CPI of student1
2 student1.CPI = 7.46;
2. Arrow operator (->)
 In C language it is illegal to access a structure member from a pointer to structure variable
using dot operator.
 We use arrow operator to access structure member from pointer to structure.

Syntax Example
1 pointer_to_structure->member_name; 1 // Student1 is a pointer to student type
2 student1 -> CPI = 7.46;

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 229


Write a program to read and display student information using structure.

WAP to print Odd numbers between 1 to n


Program Output
1 #include <stdio.h> Enter Student Name:aaa
2 struct student Enter Student Roll Number:111
3 {
4 char name[40]; // Student name Enter Student CPI:7.89
5 int roll; // Student enrollment Enter Student Backlog:0
6 float CPI; // Student mobile number
7 int backlog; Student using simple structure variable.
8 };
9 int main()
Student name: aaa
10 { Student Enrollment: 111
11 struct student student1; // Simple structure variable Student CPI: 7.890000
12 // Input data in structure members using dot operator Student Backlog: 0
13 printf("Enter Student Name:");
14 scanf("%s", student1.name);
15 printf("Enter Student Roll Number:");
16 scanf("%d", &student1.roll);
17 printf("Enter Student CPI:");
18 scanf("%f", &student1.CPI);
19 printf("Enter Student Backlog:");
20 scanf("%d", &student1.backlog);
21 // Display data in structure members using dot operator
22 printf("\nStudent using simple structure variable.\n");
23 printf("Student name: %s\n", student1.name);
24 printf("Student Enrollment: %d\n", student1.roll);
25 printf("Student CPI: %f\n", student1.CPI);
26 printf("Student Backlog: %i\n", student1.backlog);
27 }

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 230


Write a program to declare time structure and read two different time period and display sum of it.

WAP to print Odd numbers between 1 to n


Program
1 #include<stdio.h> 27 scanf ("%d",&t2.seconds);
2 struct time { 28 printf ("The Time is
3 int hours; 29 %d:%d:%d",t2.hours,t2.minutes,t2.seco
4 int minutes; 30 nds);
5 int seconds; 31 h = t1.hours + t2.hours;
6 }; 32 m = t1.minutes + t2.minutes;
7 int main() { 33 s = t1.seconds + t2.seconds;
8 struct time t1,t2; 34 printf ("\nSum of the two time's is
9 int h, m, s; 35 %d:%d:%d",h,m,s);
10 //1st time 36 return 0;
11 printf ("Enter 1st time."); 37 }
12 printf ("\nEnter Hours: ");
13 scanf ("%d",&t1.hours);
14 printf ("Enter Minutes: "); Output
15 scanf ("%d",&t1.minutes); Enter 1st time.
16 printf ("Enter Seconds: "); Enter Hours: 1
17 scanf ("%d",&t1.seconds); Enter Minutes: 20
18 printf ("The Time is Enter Seconds: 20
19 %d:%d:%d",t1.hours,t1.minutes,t1.seconds); The Time is 1:20:20
20 //2nd time
21 printf ("\n\nEnter the 2nd time."); Enter the 2nd time.
22 printf ("\nEnter Hours: "); Enter Hours: 2
23 scanf ("%d",&t2.hours); Enter Minutes: 10
24 printf ("Enter Minutes: "); Enter Seconds: 10
25 scanf ("%d",&t2.minutes); The Time is 2:10:10
26 printf ("Enter Seconds: "); Sum of the two time's is 3:30:30

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 231


Array of Structure
 It can be defined as the collection of multiple structure variables where each
variable contains information about different entities.
 The array of structures in C are used to store information about multiple entities of
different data types.
Syntax
1 struct structure_name
2 {
3 member1_declaration;
4 member2_declaration;
5 ...
6 memberN_declaration;
7 } structure_variable[size];

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 232


Write a program to read and display N student information using array of structure.

WAP to print Odd numbers between 1 to n


Program
1 #include<stdio.h> Output
2 struct student {
3 char name[20]; Enter how many records u want to store : 3
4 int rollno;
5 float cpi; Enter 1 record :
6 }; Enter Name : aaa
7 int main( ) { Enter RollNo. : 111
8 int i,n; Enter CPI : 7.89
9 printf("Enter how many records u want to store : ");
10 scanf("%d",&n); Enter 2 record :
11 struct student sarr[n]; Enter Name : bbb
12 for(i=0; i<n; i++)
Enter RollNo. : 222
13 {
Enter CPI : 7.85
14 printf("\nEnter %d record : \n",i+1);
15 printf("Enter Name : ");
16 scanf("%s",sarr[i].name); Enter 3 record :
17 printf("Enter RollNo. : "); Enter Name : ccc
18 scanf("%d",&sarr[i].rollno); Enter RollNo. : 333
19 printf("Enter CPI : "); Enter CPI : 8.56
20 scanf("%f",&sarr[i].cpi);
21 } Name RollNo Marks
22 printf("\n\tName\tRollNo\tMarks\t\n"); aaa 111 7.89
23 for(i=0; i<n; i++) { bbb 222 7.85
24 printf("\t%s\t\t%d\t\t%.2f\t\n", sarr[i].name, ccc 333 8.56
25 sarr[i].rollno, sarr[i].cpi);
26 }
27 return 0;
28 }

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 233


Write a program to declare time structure and read two different time period and display sum of it using function.

WAP to print Odd numbers between 1 to n


Program
1 #include<stdio.h> Output
2 struct Time {
3 int hours; Enter Hours: 1
4 int minutes; Enter Minutes: 20
5 int seconds; Enter Seconds: 20
6 };
7 struct Time input(); // function declaration Hours : Minutes : Seconds
8 int main() 1 : 20 : 20
9 {
10 struct Time t;
11 t=input();
12 printf("Hours : Minutes : Seconds\n %d : %d :
13 %d",t.hours,t.minutes,t.seconds);
14 return 0;
15 }
16 struct Time input() // function definition
17 {
18 struct Time tt;
19 printf ("Enter Hours: ");
20 scanf ("%d",&tt.hours);
21 printf ("Enter Minutes: ");
22 scanf ("%d",&tt.minutes);
23 printf ("Enter Seconds: ");
24 scanf ("%d",&tt.seconds);
25 return tt; // return structure variable
26 }

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 234


Structure using Pointer
 Reference/address of structure object is passed as function argument to the definition of function.
Program Output
1 #include <stdio.h> Enter Name: ABC
2 struct student {
3 char name[20]; Enter RollNo: 121
4 int rollno; Enter CPI: 7.46
5 float cpi;
6 };
7 int main() Student Details:
8 { Name: ABC
9 struct student *studPtr, stud1;
10 studPtr = &stud1; RollNo: 121
11 printf("Enter Name: "); CPI: 7.460000
12 scanf("%s", studPtr->name);
13 printf("Enter RollNo: ");
14 scanf("%d", &studPtr->rollno);
15 printf("Enter CPI: ");
16 scanf("%f", &studPtr->cpi);
17 printf("\nStudent Details:\n");
18 printf("Name: %s\n", studPtr->name);
19 printf("RollNo: %d", studPtr->rollno);
20 printf(”\nCPI: %f", studPtr->cpi);
21 return 0;
22 }

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 235


Nested Structure
 When a structure contains another structure, it is called nested structure.
 For example, we have two structures named Address and Student. To make Address nested
to Student, we have to define Address structure before and outside Student structure and
create an object of Address structure inside Student structure.
Syntax
1 struct structure_name1
2 {
3 member1_declaration;
4 member2_declaration;
5 ...
6 memberN_declaration;
7 };
8 struct structure_name2
9 {
10 member1_declaration;
11 member2_declaration;
12 ...
13 struct structure1 obj;
14 };

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 236


Write a program to read and display student information using nested of structure.
Program
1 #include<stdio.h> 27 printf("\n\tEnter Student City : ");
2 struct Address 28 scanf("%s",s.Add.City);
3 { 29 printf("\n\tEnter Student Pincode : ");
4 char HouseNo[25]; 30 scanf("%s",s.Add.PinCode);
5 char City[25]; 31 printf("\nDetails of Students");
6 char PinCode[25]; 32 printf("\n\tStudent Name : %s",s.name);
7 }; 33 printf("\n\tStudent Roll Number :
8 struct Student 34 %d",s.roll);
9 { 35 printf("\n\tStudent CPI : %f",s.cpi);
10 char name[25]; 36 printf("\n\tStudent House No :
11 int roll; 37 %s",s.Add.HouseNo);
12 float cpi; 38 printf("\n\tStudent City :
13 struct Address Add; 39 %s",s.Add.City);
14 }; 40 printf("\n\tStudent Pincode :
15 int main() 41 %s",s.Add.PinCode);
16 { 42 return 0;
17 int i; 43 }
18 struct Student s;
19 printf("\n\tEnter Student Name : "); Output
20 scanf("%s",s.name); Details of Students
21 printf("\n\tEnter Student Roll Number : "); Student Name : aaa
22 scanf("%d",&s.roll); Student Roll Number : 111
23 printf("\n\tEnter Student CPI : "); Student CPI : 7.890000
24 scanf("%f",&s.cpi); Student House No : 39
25 printf("\n\tEnter Student House No : "); Student City : rajkot
26 scanf("%s",s.Add.HouseNo); Student Pincode : 360001

Prof. Nilesh Gambhava #3110003 (PPS) – Structure 237


Practice Programs
1. Define a structure data type called time_struct containing three member’s integer hours, minutes, second.
Develop a program that would assign values to individual member and display the time in following format :
HH:MM:SS
2. WAP to create structure of book with book title, author name, publication, and price. Read data of n books
and display them.
3. Define a structure Person 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.
4. Define a structure time_struct containing three member’s integer hour, integer minute and integer second.
WAP that would assign values to the individual number and display the time in the following format: 16: 40:
51.
5. Define a structure cricket that will describe the following information:
Player name
Team name
Batting average
6. Using cricket, declare an array player with 50 elements and WAP to read the information about all the 50
players and print team wise list containing names of players with their batting average.
7. Define a structure student_record to contain name, branch, and total marks obtained. WAP to read data for
10 students in a class and print them.
Prof. Nilesh Gambhava #3110003 (PPS) – Structure 238

Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Union {C}
Programming

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
What is Union?
 Union is a user defined data type similar like Structure.
 It holds different data types in the same memory location.
 You can define a union with various members, but only one member can hold a
value at any given time.
 Union provide an efficient way of using the same memory location for multiple-
purpose.

Prof. Nilesh Gambhava #3110003 (PPS) – Union 241


Syntax to Define and Access Union
 Declaration of union must start with the keyword union followed by the union
name and union’s member variables are declared within braces.
Syntax
1 union union_name union_name is name of custom type.
2 {
3 member1_declaration;
4 member2_declaration;
memberN_declaration is individual member
5 . . .
declaration.
6 memberN_declaration;
7 };
 Accessing the union members:
 You need to create an object of union to access its members.
 Object is a variable of type union. Union members are accessed using the dot operator(.)
between union’s object and union’s member name.
Syntax
1 union union_name union_variable;

Prof. Nilesh Gambhava #3110003 (PPS) – Union 242


Example to Define Union
Example
1 union student
2 {
3 char name[30]; // Student Name
4 int roll_no; // Student Roll No
5 float CPI; // Student CPI
6 int backlog; // Student Backlog
7 } student1;

 You must terminate union definition with semicolon ;.


 You cannot assign value to members inside the union definition, it will cause
compilation error.
Example
1 union student
2 {
3 char name[30] = “ABC”; // Student Name
4 . . .
5 } student1;
Prof. Nilesh Gambhava #3110003 (PPS) – Union 243
Structure Vs. Union
COMPARISON STRUCTURE UNION

Basic The separate memory location is allotted to All members of the 'union' share the same memory location.
each member of the structure.
keyword 'struct' 'union'
Size Size of Structure = sum of size of all the data Size of Union = size of the largest member.
members.
Store Value Stores distinct values for all the members. Stores same value for all the members.
At a Time A structure stores multiple values, of the A union stores a single value at a time for all members.
different members, of the structure.
Declaration struct ss union uu
4 bytes
{ 1 byte for c {
int a; int a; c
float f; 2 bytes for a float f; a
f
char c 4 bytes for f char c
}; };

Prof. Nilesh Gambhava #3110003 (PPS) – Union 244


Where Union should be used?
 Mouse Programming
 Embedded Programming
 Low Level System Programming

Prof. Nilesh Gambhava #3110003 (PPS) – Union 245


Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

Dynamic {C}
Programming

Memory
Allocation
Computer Engineering Department,
Darshan Institute of Engineering & Technology, Rajkot
Dynamic Memory Allocation (DMA)
 If memory is allocated at runtime (during execution of program) then it is called
dynamic memory.
 It allocates memory from heap (heap: it is an empty area in memory)
 Memory can be accessed only through a pointer.

When DMA is needed?


 It is used when number of variables are not known in advance or large in size.
 Memory can be allocated at any time and can be released at any time during
runtime.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 248


malloc() function
 malloc () is used to allocate a fixed amount of memory during the execution of a
program.
 malloc () allocates size_in_bytes of memory from heap, if the allocation
succeeds, a pointer to the block of memory is returned else NULL is returned.
 Allocated memory space may not be contiguous.
 Each block contains a size, a pointer to the next block, and the space itself.
 The blocks are kept in ascending order of storage address, and the last block points
to the first.
 The memory is not initialized.
Syntax Description
ptr_var = (cast_type *) This statement returns a pointer to size_in_bytes of uninitialized
malloc (size_in_bytes); storage, or NULL if the request cannot be satisfied.

Example: fp = (int *)malloc(sizeof(int) *20);


Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 249
Write a C program to allocate memory using malloc.

Program
1 #include <stdio.h>
2 void main()
3 {
4 int *fp; //fp is a pointer variable
5 fp = (int *)malloc(sizeof(int)); //returns a pointer to int size storage
6 *fp = 25; //store 25 in the address pointed by fp
7 printf("%d", *fp); //print the value of fp, i.e. 25
8 free(fp); //free up the space pointed to by fp
9 }

Output
25

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 250


calloc() function
 calloc() is used to allocate a block of memory during the execution of a
program
 calloc() allocates a region of memory to hold no_of_blocks of
size_of_block each, if the allocation succeeds then a pointer to the block of
memory is returned else NULL is returned.
 The memory is initialized to ZERO.
Syntax Description
ptr_var = (cast_type *) This statement returns a pointer to no_of_blocks of size
calloc (no_of_blocks, size_of_blocks, it returns NULL if the request cannot be satisfied.
size_of_block);
Example:
int n = 20;
fp = (int *)calloc(n, sizeof(int));

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 251


Write a C program to allocate memory using calloc.
Program
1 #include <stdio.h>
2 void main()
3 {
4 int i, n; //i, n are integer variables
5 int *fp; //fp is a pointer variable
6 printf("Enter how many numbers: ");
7 scanf("%d", &n);
8 fp = (int *)calloc(n, sizeof(int)); //calloc returns a pointer to n blocks
9 for(i = 0; i < n; i++) //loop through until all the blocks are read
10 {
11 scanf("%d",fp); //read and store into location where fp points
12 fp++; //increment the pointer variable
13 }
14 free(fp); //frees the space pointed to by fp
}

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 252


realloc() function
 realloc() changes the size of the object pointed to by pointer fp to specified
size.
 The contents will be unchanged up to the minimum of the old and new sizes.
 If the new size is larger, the new space will be uninitialized.
 realloc() returns a pointer to the new space, or NULL if the request cannot be
satisfied, in which case *fp is unchanged.

Syntax Description
ptr_var = (cast_type *) This statement returns a pointer to new space, or NULL if the request
realloc (void *fp, cannot be satisfied.
size_t);
Example: fp = (int *)realloc(fp,sizeof(int)*20);

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 253


Write a C program to allocate memory using realloc.
Program
1 #include <stdio.h>
2 void main()
3 {
4 int *fp; //fp is a file pointer
5 fp = (int *)malloc(sizeof(int)); //malloc returns a pointer to int size storage
6 *fp = 25; //store 25 in the address pointed by fp
7 fp =(int *)realloc(fp, 2*sizeof(int)); //returns a pointer to new space
8 printf("%d", *fp); //print the value of fp
9 free(fp); //free up the space pointed to by fp
}

Output
25

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 254


free() function
 free deallocates the space pointed to by fp.
 It does nothing if fp is NULL.
 fp must be a pointer to space previously allocated by calloc, malloc or
realloc.

Syntax Description
void free(void *); This statement free up the memory not needed anymore.

Example: free(fp);

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 255


Write a C program to sort numbers using malloc
Program Program (cont.)
1 #include<stdio.h> 17 if(p[i] > p[j])
2 #include<stdlib.h> 18 {
3 void main() 19 t = p[i];
4 { 20 p[i] = p[j];
5 int i,j,t,n; 21 p[j] = t;
6 int *p; 22 }
7 printf("Enter value of n: "); 23 }
8 scanf("%d", &n); 24 }
9 p=(int *) malloc(n * sizeof(int)); 25 printf("Ascending order\n");
10 printf("Enter values\n"); 26 for(i=0; i<n; i++)
11 for(i=0; i<n; i++) 27 printf("%d\n", p[i]);
12 scanf("%d", &p[i]); 28 free(p);
13 for(i=0; i<n; i++) 29 }
14 {
15 for(j= i+1; j<n; j++)
16 {

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 256


Write a C program to find square of numbers using calloc
Program Output
1 #include<stdio.h> Enter value of n: 3
2 #include<stdlib.h> Enter values
3 void main() 3
4 { 2
5 int i,n; 5
6 int *p; Square of 3 = 9
7 printf("Enter value of n: "); Square of 2 = 4
8 scanf("%d",&n); Square of 5 = 25
9 p=(int*)calloc(n,sizeof(int));
10 printf("Enter values\n");
11 for(i=0;i<n;i++)
12 scanf("%d",&p[i]);
13 for(i=0;i<n;i++)
14 printf("Square of %d = %d\n", p[i],
15 p[i] * p[i]);
16 free(p);
17 }

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 257


Write a C program to add/remove item from a list using realloc
Program Program (cont.)
1 #include<stdio.h> 18
2 #include<stdlib.h> 19 printf("Enter new size of list: ");
3 void main() 20 scanf("%d", &n2);
4 { 21
5 int i, n1, n2; 22 fp = realloc(fp, n2 * sizeof(int));
6 int *fp; 23 if(n2 > n1)
7 printf("Enter size of list: "); 24 {
8 scanf("%d", &n1); 25 printf("Enter %d numbers\n", n2 - n1);
9 fp=(int *) malloc (n1 * sizeof(int)); 26 for(i = n1; i < n2; i++)
10 27 scanf("%d", &fp[i]);
11 printf("Enter %d numbers\n", n1); 28 }
12 for(i = 0; i < n1; i++) 29 printf("The numbers in the list are\n");
13 scanf("%d", &fp[i]); 30 for(i = 0; i < n2; i++)
14 31 printf("%d\n", fp[i]);
15 printf("The numbers in the list are\n"); 32 }
16 for(i = 0; i < n1; i++)
17 printf("%d\n", fp[i]);

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 258


Practice Programs
1) Write a C program to calculate sum of n numbers entered by user.
2) Write a C program to input and print text using DMA
3) Write a C program to read and print student details using structure and DMA

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 259


Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING

File {C}
Programming

Management

Computer Engineering Department,


Darshan Institute of Engineering & Technology, Rajkot
File management is what you
have, and how you want to
manipulate it. - Anonymous
Why File Management?
 In real life, we want to store data permanently so that later we can retrieve it and
reuse it.
 A file is a collection of characters stored on a secondary storage device like hard
disk, or pen drive.
 There are two kinds of files that programmer deals with:
 Text Files are human readable and it is a stream of plain English characters
 Binary Files are computer readable, and it is a stream of processed characters and ASCII
symbols

Text File Binary File

Hello, this is a text file. Whatever 11010011010100010110111010


written here can be read easily 10111010111010011010100010
without the help of a computer. 11011101010111010111010011

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 263


File Opening Modes
 We can perform different operations on a file based on the file opening modes
Mode Description

Open the file for reading only. If it exists, then the file is opened with the current contents;
r
otherwise an error occurs.
Open the file for writing only. A file with specified name is created if the file does not exists.
w
The contents are deleted, if the file already exists.
Open the file for appending (or adding data at the end of file) data to it. The file is opened
a with the current contents safe. A file with the specified name is created if the file does not
exists.
r+ The existing file is opened to the beginning for both reading and writing.

w+ Same as w except both for reading and writing.

a+ Same as a except both for reading and writing.

Note: The main difference is w+ truncate the file to zero length if it exists or create a new file if it doesn't.
While r+ neither deletes the content nor create a new file if it doesn't exist.
Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 264
File Handling Functions
 Basic file operation performed on a file are opening, reading, writing, and closing a
file.

Syntax Description
fp=fopen(file_name, This statement opens the file and assigns an identifier to the FILE type pointer
mode); fp.

Example: fp = fopen("printfile.c","r");
fclose(filepointer); Closes a file and release the pointer.

Example: fclose(fp);
fprintf(fp, Here fp is a file pointer associated with a file. The control string contains items
“control string”, to be printed. The list may includes variables, constants and strings.
list);
Example: fprintf(fp, "%s %d %c", name, age, gender);

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 265


File Handling Functions
Syntax Description
fscanf(fp, Here fp is a file pointer associated with a file. The control string contains items to
“control string”, be printed. The list may includes variables, constants and strings.
list);
Example: fscanf(fp, "%s %d", &item, &qty);
int getc( getc() returns the next character from a file referred by fp; it require the FILE
FILE *fp); pointer to tell from which file. It returns EOF for end of file or error.

Example: c = getc(fp);
int putc(int c, putc() writes or appends the character c to the FILE fp. If a putc function is
FILE *fp); successful, it returns the character written, EOF if an error occurs.

Example: putc(c, fp);

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 266


File Handling Functions
Syntax Description
int getw( getw() reads an integer value from FILE pointer fp and returns an integer.
FILE *pvar);
Example: i = getw(fp);
putw(int, putw writes an integer value read from terminal and are written to the FILE
FILE *fp); using fp.

Example: putw(i, fp);


EOF EOF stands for “End of File”. EOF is an integer defined in <stdio.h>

Example: while(ch != EOF)

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 267


Write a C program to display content of a given file.

Program
1 #include <stdio.h>
2 void main()
3 {
4 FILE *fp; //p is a FILE type pointer
5 char ch; //ch is used to store single character
6 fp = fopen("file1.c","r"); //open file in read mode and store file pointer in p
7 do { //repeat step 9 and 10 until EOF is reached
8 ch = getc(fp); //get character pointed by p into ch
9 putchar(ch); //print ch value on monitor
10 }while(ch != EOF); //condition to check EOF is reached or not
11 fclose(fp); //free up the file pointer pointed by fp
12 }
13

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 268


Write a C program to copy a given file.
Program
1 #include <stdio.h>
2 void main()
3 {
4 FILE *fp1, *fp2; //p and q is a FILE type pointer
5 char ch; //ch is used to store temporary data
6 fp1 = fopen("file1.c","r"); //open file “file1.c” in read mode
7 fp2 = fopen("file2.c","w"); //open file “file2.c” in write mode
8 do { //repeat step 9 and 10 until EOF is reached
9 ch = getc(fp1); //get character pointed by p into ch
10 putc(ch, fp2); //print ch value into file, pointed by pointer q
11 }while(ch != EOF); //condition to check EOF is reached or not
12 fclose(fp1); //free up the file pointer p
13 fclose(fp2); //free up the file pointer q
14 printf("File copied successfully...");
15 }

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 269


File Positioning Functions
 fseek, ftell, and rewind functions will set the file pointer to new location.
 A subsequent read or write will access data from the new position.

Syntax Description
fseek(FILE *fp, fseek() function is used to move the file position to a desired location within
long offset, the file. fp is a FILE pointer, offset is a value of datatype long, and position
int position); is an integer number.

Example: /* Go to the end of the file, past the last character of the file */
fseek(fp, 0L, 2);
long ftell(FILE *fp); ftell takes a file pointer and returns a number of datatype long, that
corresponds to the current position. This function is useful in saving the current
position of a file.

Example: /* n would give the relative offset of the current position. */


n = ftell(fp);

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 270


File Positioning Functions

Syntax Description
rewind(fp); rewind() takes a file pointer and resets the position to the start of the file.

Example: /* The statement would assign 0 to n because the file position has been set
to the start of the file by rewind. */

rewind(fp);

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 271


Write a C program to count lines, words, tabs, and characters

Program Program (contd.)


1 #include <stdio.h> 17 c++;
2 void main() 18
3 { 19 ch = getc(p);
4 FILE *p; 20 }
5 char ch; 21 fclose(p);
6 int ln=0,t=0,w=0,c=0; 22 printf("Lines = %d, tabs = %d, w
7 p = fopen("text1.txt","r"); ords = %d, characters = %d\n",ln, t,
8 ch = getc(p); w, c);
9 while (ch != EOF) { 23 }
10 if (ch == '\n')
11 ln++;
12 else if(ch == '\t') Output
13 t++;
Lines = 22, tabs = 0, words = 152, characters =
14 else if(ch == ' ')
283
15 w++;
16 else

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 272


Practice Programs
1) Write a C program to write a string in file.
2) A file named data contains series of integer numbers. Write a C program to read
all numbers from file and then write all the odd numbers into file named “odd”
and write all even numbers into file named “even”. Display all the contents of
these file on screen.
3) Write a C program to read name and marks of n number of students and store
them in a file.
4) Write a C program to print contents in reverse order of a file.
5) Write a C program to compare contents of two files.
6) Write a C program to copy number of bytes from a specific offset to another file.
7) Write a C program to convert all characters in UPPER CASE of a File.

Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 273


Thank you

You might also like