0% found this document useful (0 votes)
39 views164 pages

Ebin - Pub Gtu Study Material

This document provides an introduction to computers and programming. It defines a computer as an electronic device that can perform calculations quickly and accurately. The document discusses the advantages of computers like speed, storage, accuracy, and reliability. It also mentions some disadvantages like lack of intelligence and inability to correct mistakes. The document then explains the basic block diagram of a computer including input, output, central processing unit, primary memory, and secondary memory. It defines hardware and software. The document concludes by discussing different types of computer languages like machine language, assembly language, and higher-level languages.

Uploaded by

noname3630
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)
39 views164 pages

Ebin - Pub Gtu Study Material

This document provides an introduction to computers and programming. It defines a computer as an electronic device that can perform calculations quickly and accurately. The document discusses the advantages of computers like speed, storage, accuracy, and reliability. It also mentions some disadvantages like lack of intelligence and inability to correct mistakes. The document then explains the basic block diagram of a computer including input, output, central processing unit, primary memory, and secondary memory. It defines hardware and software. The document concludes by discussing different types of computer languages like machine language, assembly language, and higher-level languages.

Uploaded by

noname3630
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/ 164

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

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 63


if v/s while

Flowchart of if v/s Flowchart of while

False False
condition condition

True True

… …

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


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 65


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 67


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 68


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 70


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 71


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 73


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 74


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 75


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 76
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 77


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 78


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 79


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 80


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 81


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 83
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 84


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 85


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 86


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 88
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 89


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 90


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 91


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 93


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 94


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 95


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 96


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 98


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 99


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 100


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 101
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 102


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 103

Thank you
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 106


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 107


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 108


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 109


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 111


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 112


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 113


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 114


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 115


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 117


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 118


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 119


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 120


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 121


{ }
 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 122


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 124


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 125


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 126


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 128


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 129
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 130

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 132


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 133


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 134


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 136
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 137


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 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

You might also like