0% found this document useful (0 votes)
9 views

CPPSFINALISED

Uploaded by

ghost.bhootha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

CPPSFINALISED

Uploaded by

ghost.bhootha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

C Programming for Problem Solving I/II Semester Common to all branches

Unit- I

Computer: A computer is an electronic device, operating under the control of instructions stored
in its own memory that can accept data (input), process the data according to specified rules,
produce information (output), and store the information for future use.
Computer Components: Any kind of computers consists of Hardware & Software
Hardware: Computer hardware is the collection of physical elements that constitutes a computer
system. Computer hardware refers to the physical parts or components of a computer such as the
monitor, mouse, keyboard, computer data storage, hard drive disk (HDD), system unit (graphic
cards, sound cards, memory, motherboard and chips), etc. all of which are physical objects that
can be touched
Input Devices: Input device is any peripheral (piece of computer hardware equipment to provide
data and control signals to an information processing system such as a computer or other
information appliance. Input device Translate data from form that humans understand to one that
the computer can work with. Most common are keyboard and mouse
Central Processing Unit (CPU)
A CPU is brain of a computer. It is responsible for all functions and processes. Regarding
computing power, the CPU is the most important element of a computer system.
The CPU is comprised of two main parts:
1. Arithmetic Logic Unit (ALU): Executes all arithmetic and logical operations. Arithmetic
calculations like as addition, subtraction, multiplication and division. Logical operation
like compare numbers, letters, or special characters
2. Control Unit (CU): controls and co-ordinates computer components.
Primary Memory: -
1. RAM: Random Access Memory (RAM) is a memory scheme within the computer system
responsible for storing data on a temporary basis, so that it can be promptly accessed by the
processor as and when needed. It is volatile in nature, which means that data will be erased once
supply to the storage device is turned off. RAM stores data randomly and the processor accesses
these data randomly from the RAM storage. RAM is considered "random access" because you can
access any memory cell directly if you know the row and column that intersect at that cell.
2. ROM (Read Only Memory): ROM is a permanent form of storage. ROM stays active regardless
of whether power supply to it is turned on or off. ROM devices do not allow data stored on them
to be modified.
Secondary Memory:- Stores data and programs permanently :it retains the contents after the
power is turned off

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page1


C Programming for Problem Solving I/II Semester Common to all branches

Hard drive (HD): A hard disk is part of a unit, often called a "disk drive," "hard drive," or "hard
disk drive," that store and provides relatively quick access to large amounts of data on an
electromagnetically charged surface or set of surfaces.

Differences between RAM & Hard Disk


RAM Hard Disk
Smaller amount of memory limited to Large amount of memory scalable up to
64GB 1TB
Volatile Non-volatile
Consists of Chips Consists of platters
Always holds temporary copy Holds permanent copy
Access time is very high Access time is very slow.
High cost Low cost

Output devices: An output device is any piece of computer hardware equipment used to
communicate the results of data processing carried out by an information processing system (such
as a computer) which converts the electronically generated information into human-readable form.
Examples include Monitor, Speakers, Printer etc.
Software: Software is a generic term for organized collections of computer data and instructions,
often broken into two major categories: system software that provides the basic non-task-specific
functions of the computer, and application software which is used by users to accomplish specific
tasks.
Software Types
A. System software is responsible for controlling, integrating, and managing the individual
hardware components of a computer system so that other software and the users of the system see
it as a functional unit without having to be concerned with the low-level details such as
transferring data from memory to disk, or rendering text onto a display. Generally, system
software consists of an operating system and some fundamental utilities such as disk formatters,
file managers, display managers, text editors.
B. Application software is used to accomplish specific tasks other than just running the computer
system. Application software may consist of a single program, such as an image viewer; a small
collection of programs (often called a software package) that work closely together to accomplish
a task, such as a spreadsheet or text processing system; a larger collection (often called a software
suite) of related but independent programs and packages that have a common user interface or

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page2


C Programming for Problem Solving I/II Semester Common to all branches

shared data format, such as Microsoft Office, which consists of closely integrated word processor,
spreadsheet, database, etc

Computer Languages
How do you think we communicate with a computer? A computer cannot understand any
commands that you may give in English or in any other language. It has its own set of instructions
for communication, or what we call computer languages. The user of a computer must be able to
communicate with it. That means, he must be able to give the computer commands and
understand the output that the computer generates. This is possible due to the invention of
computer languages. Basically, there are two main categories of computer languages, namely Low
Level Language and High Level Language.

Low Level Languages :Low level languages are the basic computer instructions or better known
as machine codes. A computer cannot understand any instruction given to it by the user in English
or any other high level language. These low level languages are very easily understandable by the
machine. The main function of low level languages is to interact with the hardware of the
computer. They help in operating, syncing and managing all the hardware and system components
of the computer. They handle all the instructions which form the architecture of the hardware
systems.

Machine Language :This is one of the most basic low level languages. The language was first
developed to interact with the first generation computers. It is written in binary code or machine
code, which means it basically comprises of only two digits – 1 and 0.

Assembly Language: This is the second generation programming language. It is a development


on the machine language, where instead of using only numbers, we use English words, names, and
symbols. It is the most basic computer language necessary for any processor.

High Level Language: When we talk about high level languages, these are programming
languages. Some prominent examples are PASCAL, FORTRAN, C++ etc. The important
feature about such high-level languages is that they allow the programmer to write programs
for all types of computers and systems. Every instruction in high level language is converted
to machine language for the computer to comprehend.
Language Translators: A translator is a programming language processor that converts
a computer program from one language to another. It takes a program written in source

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page3


C Programming for Problem Solving I/II Semester Common to all branches

code and converts it into machine code. It discovers and identifies the error during
translation.
There are 3 different types of translators as follows:

Compiler

A compiler is a translator used to convert high-level programming language to low-level


programming language. It converts the whole program in one session and reports errors
detected after the conversion. Compiler takes time to do its work as it translates high-level
code to lower-level code all at once and then saves it to memory.
A compiler is processor-dependent and platform-dependent. But it has been addressed by a
special compiler, a cross-compiler and a source-to-source compiler. Before choosing a
compiler, user has to identify first the Instruction Set Architecture (ISA), the operating system
(OS) and the programming language that will be used to ensure that it will be compatible.

Interpreter

Just like a compiler, is a translator used to convert high-level programming language to low-
level programming language. It converts the program one at a time and reports errors
detected at once, while doing the conversion. With this, it is easier to detect errors than in a
compiler. An interpreter is faster than a compiler as it immediately executes the code upon
reading the code. It is often used as a debugging tool for software development as it can
execute a single line of code at a time. An interpreter is also more portable than a compiler
as it is not processor-dependent, you can work between hardware architectures.
Assembler

An assembler is a translator used to translate assembly language to machine language. It is


like a compiler for the assembly language but interactive like an interpreter. Assembly
language is difficult to understand as it is a low-level programming language. An assembler
translates a low-level language, an assembly language to an even lower-level language,
which is the machine code. The machine code can be directly understood by the CPU.
Some of the examples of commonly used translators:
Translator Examples

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page4


C Programming for Problem Solving I/II Semester Common to all branches

Compiler Turbo C, Borland C, COBOL, GCC

Interpreter Python, LISP

Assembler Fortran Assembly program, PDP-11

C programming Concepts
C is a general-purpose high-level language that was originally developed by Dennis Ritchie
for the Unix operating system. It was first implemented on the Digital Equipment
Corporation PDP-11 computer in 1972.
The Unix operating system and virtually all Unix applications are written in the C language.
C has now become a widely used professional language for various reasons.

• Easy to learn
• Structured language
• It produces efficient programs.
• It can be compiled on a variety of computers.
Facts about C
• C was invented to write an operating system called UNIX.
• C is a successor of B language which was introduced around 1970
• The language was formalized in 1988 by the American National Standard Institute
(ANSI).
• By 1973 UNIX OS almost totally written in C.
• Today C is the most widely used System Programming Language.
• Most of the state-of-the-art software have been implemented using C

Basic Structure of C Program

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page5


C Programming for Problem Solving I/II Semester Common to all branches

Documentation Section
The documentation section is the part of the program where the programmer gives the
details associated with the program. He usually gives the name of the program, the details
of the author and other details like the time of coding and description. It gives anyone
reading the code the overview of the code.
Example
/**
* File Name: Helloworld.c
* Author: Prasanna Kumar K R
* date: 22/01/2020 */
Link Section
This part of the code is used to declare all the header files that will be used in the program.
This leads to the compiler being told to link the header files to the system libraries.
Example

# include<stdio.h>
#include<math.h>
Definition Section
In this section, we define different constants. The keyword define is used in this part.

Global Declaration Section

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page6


C Programming for Problem Solving I/II Semester Common to all branches

This part of the code is the part where the global variables are declared. All the global
variable used are declared in this part. The user-defined functions are also declared in this
part of the code.

Main Function Section


Every C-programs needs to have the main function. Each main function contains 2 parts.
A declaration part and an Execution part. The declaration part is the part where all the
variables are declared. The execution part begins with the curly brackets and ends with
the curly close bracket. Both the declaration and execution part are inside the curly braces.

main()
{
printf(“Hello SIT\n”);
return 0;
}

Sub Program Section


All the user-defined functions are defined in this section of the program.

Constants, Variables & Data Types in C language


What is a character set?

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page7


C Programming for Problem Solving I/II Semester Common to all branches

Like every other language 'C' also has its own character set. A program is a set of
instructions that when executed, generate an output. The data that is processed by a
program consists of various characters and symbols. The output generated is also a
combination of characters and symbols.
A character set in 'C' is divided into,

1. Letters : Uppercase characters (A-Z) , Lowercase characters (a-z)


2. Numbers :All digits from 0 to 9
3. Special characters : !, < ,> , ? , ; , << , >>
4. White spaces (blank spaces) : New line , Blank
Token: A token is the smallest unit in a 'C' program. A token is divided into six different
types as follows

Keywords and Identifiers: In 'C' every word can be either a keyword or an identifier.
Keywords have fixed meanings, and the meaning cannot be changed. They act as a
building block of a 'C' program. There are total 32 keywords in 'C'. Keywords are written
in lowercase letters.

Following table represents the keywords in 'C',

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page8


C Programming for Problem Solving I/II Semester Common to all branches

auto double int struct

break else long switch

case enum register typedef

char extern return union

const short float unsigned

continue for signed void

default goto sizeof volatile

do if static while

Identifiers: An identifier is nothing but a name assigned to an element in a program.


Example, name of a variable, function, etc. Identifiers are the user-defined names
consisting of 'C' standard character set. As the name says, identifiers are used to identify a
particular element in a program. Each identifier must have a unique name. Following rules
must be followed for identifiers:
1. The first character must always be an alphabet or an underscore.
2. It should be formed using only letters, numbers, or underscore.
3. A keyword cannot be used as an identifier.
4. It should not contain any whitespace character.
5. The name must be meaningful.
Examples: Name, Age, Address are valid identifiers while 1sem,age limit are invalid
identifiers.

What is a Variable?

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page9


C Programming for Problem Solving I/II Semester Common to all branches

A variable is an identifier which is used to store some value. Constants can never change
at the time of execution. Variables can change during the execution of a program and
update the value stored inside it. A single variable can be used at multiple locations in a
program. A variable name must be meaningful. It should represent the purpose of the
variable.
Example: Height, age, are the meaningful variables that represent the purpose it is being
used for. Height variable can be used to store a height value. Age variable can be used to
store the age of a person
A variable must be declared first before it is used somewhere inside the program. A
variable name is formed using characters, digits and an underscore.
Following are the rules that must be followed while creating a variable:
1. A variable name should consist of only characters, digits and an underscore.
2. A variable name should not begin with a number.
3. A variable name should not consist of whitespace.
4. A variable name should not consist of a keyword.
5. 'C' is a case sensitive language that means a variable named 'age' and 'AGE' are
different.

C Constants: C Constants are also like normal variables. But, only difference is, their
values cannot be modified by the program once they are defined. Constants refer to fixed
values. They are also called as literals.
TYPES OF C CONSTANT:
1. Integer constants
2. Real or Floating-point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants

INTEGER CONSTANTS IN C:
1. An integer constant must have at least one digit.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page10


C Programming for Problem Solving I/II Semester Common to all branches

2. It must not have a decimal point.


3. It can either be positive or negative.
4. No commas or blanks are allowed within an integer constant.
5. If no sign precedes an integer constant, it is assumed to be positive.
An octal integer constant consists of any combination of digits from 0 to 7 with a leading
0. Some examples of octal integer are 037, 0435,0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integers. They
may also include alphabets through A to F or a to f which correspondingly represents the
number 10 through 15 respectively. Examples of valid hexadecimal numbers are 0X9BC ,
0XABCD, 0XF100.

Floating Point Constants: Integer numbers are inadequate to represent quantities that
vary continuously, such as heights, distances, temperatures and so on. These numbers
have integer part and decimal part separated by . . Examples include 97.6,121.3659 so on.A
real number may also be expressed in the exponential notation. For example the value
215.65 may be written as 2.1565e2. e2 means 102.The general format is
Mantissa e Exponent.
The mantissa is either a real number or integer with an optional + or – sign. The letter e
separating the mantissa and exponent can be written either in lower case or upper case.
Examples include 0.654e2, 12e-2, 1.5e+5
CHARACTER AND STRING CONSTANTS IN C:
A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single quotes. The maximum length of a character constant is 1 character. Examples
include ‘A’, ‘b’, ‘C’
String constants are enclosed within double quotes. Examples are “SIT”, “RVCE” etc
BACKSLASH CHARACTER CONSTANTS IN C:
There are some characters which have special meaning in C language.
They should be preceded by backslash symbol to make use of special function of them.

\n New line

\t Horizontal tab

Data types in C Language

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page11


C Programming for Problem Solving I/II Semester Common to all branches

Data types specify how we enter data into our programs and what type of data we enter.
C language has some predefined set of data types to handle various kinds of data that we
can use in our program. These datatypes have different storage capacities.
C language supports 3 different type of data types
1.Primary Data type 2.Derived data type 3.User-defined data type
Primary data types:
These are fundamental data types in C namely
1. integer(int)
2. floating point(float)
3. character(char)
Integer: Integers are used to store whole numbers. It usually occupies 2 bytes of memory,
which means 16 bits. When an integer is declared it gets stored in the form of binary. Now
let us examine how actually data gets stored.
Assume you are declaring int a= 15;
Binary equivalent of 15 is 1111. So 16 bit representation would be 0000000000001111
If we name the bits from b0 to b15 where b15 being the MSB and b0 being the LSB
b15 b0
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1

Bit b15 is used for sign representation. If the bit is 0 then it’s a positive number ,if the bit is
1 then it is a negative number. Similarly if we want to store x=-15 , its representation would
be
b15 b0
1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1

So, even though we have 16 bits for representation we could utilise only 15 bits for
representation. Hence the maximum value where integer can hold is 215 – 1 which is +32767
and minimum value what it can store is -215 which is -32768. Thus integer can hold any
value in the range -32768 to +32767.
Unsigned integers: In programming you come across some situations where in a variable
can never have a negative value throughout its execution. In such situations we could

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page12


C Programming for Problem Solving I/II Semester Common to all branches

declare variable as unsigned int , which means no negative values are allowed. So the
range of such integers would be 0 to 65535.( 32768 +32767 =65535).
Short integer: Short integer occupies 1 byte of memory. Similar to the int bit b7 is used to
represent the sign bit. So range of short int would be -27 to 27-1. i.e. -128 to +127
Similarly unsigned short it has the range of 0 to 255.
Long integers: Long integers occupy 4 bytes of memory or 32 bits. Hence its range would
be -2,147,483,648 to +2,147,483,647. If we have unsigned long int then its range would be 0
to 4,2941967,295.
By this discussion you should be able to decide the type of integer which you would lie to
include in your program.
Floating Point (float):floating point numbers are stored in 32 bits with 6 digits of
precision(decimal data).They are defined in C by the keyword float. When the accuracy
provided by float is not sufficient ,double can be used to define the number. A double data
type number uses 64 bits giving a precision of 14 digits.long double uses 80 bits to
represent the number.In general

Type Size(bytes) Range

Float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

Character data type (char) : Character data type occupies 1 byte of memory. Always the
data is enclosed in single quotes. Examples include ‘A’, ‘J’, ‘1’ So on. The range of char is
-128 to +127. Is its is unsigned char then its range would be 0 to 255.

Derived data type: Derived data types are nothing but primary datatypes but a little
twisted or grouped together like array, stucture, union and pointer. These are discussed
in details later.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page13


C Programming for Problem Solving I/II Semester Common to all branches

User-defined type declaration: Those data types which are defined by the user as per
his/her will are called user-defined data types.It takes the general form
typedef type identifier;
Example typedef int marks;
marks m1,m2,m3; Now m1,m2,m3 are of the type marks which is of type
integer.
Enumerated data type: Enumeration is a user defined datatype in C language. It is used
to assign names to the integral constants which makes a program easy to read and
maintain. The keyword “enum” is used to declare an enumeration.
Here is the syntax of enum in C language,

enum enum_name{const1, const2, ....... };

Example : enum day{Mond, Tues, Wedn, Thurs, Frid, Sat, Sund};

Now when we have such declarations automatically compiler assigns the value 0 to
Mond, 1 to Tues and 6 to Sund.

However the programmer has the liberty to set it for some other values also like

enum day{Mond =10, Tues=20, Wedn=30, Thurs=40, Frid=50, Sat=60, Sund=70};

OPERATORS & EXPRESSIONS

The symbols which are used to perform logical and mathematical operations in a C
program are called C operators. These C operators join individual constants and variables

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page14


C Programming for Problem Solving I/II Semester Common to all branches

to form expressions. Operators, functions, constants and variables are combined together
to form expressions.
Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant
and A + B * 5 is an expression.
TYPES OF C OPERATORS:

C language offers many types of operators. They are,


1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
ARITHMETIC OPERATORS IN C:
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.

Arithmetic
Operators/Operation Example

+ (Addition) A+B

– (Subtraction) A-B

* (multiplication) A*B

/ (Division) A/B

% (Modulus) A%B

ASSIGNMENT OPERATORS IN C:
• In C programs, values for the variables are assigned using assignment operators.
• For example, if the value 10 is to be assigned for the variable sum, it can be assigned
as sum = 10;

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page15


C Programming for Problem Solving I/II Semester Common to all branches

• There are 2 categories of assignment operators in C language. They are,


1. Simple assignment operator ( Example: = )
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=)

Operators Example/Description

sum = 10;
= 10 is assigned to variable sum

sum += 10;
+= This is same as sum = sum + 10

sum -= 10;
-= This is same as sum = sum – 10

sum *= 10;
*= This is same as sum = sum * 10

sum /= 10;
/= This is same as sum = sum / 10

sum %= 10;
%= This is same as sum = sum % 10
RELATIONAL OPERATORS IN C:
Relational operators are used to find the relation between two variables. i.e. to
compare the values of two variables in a C program.

Operators Example/Description

> x > y (x is greater than y)

< x < y (x is less than y)

x >= y (x is greater than or equal to


>= y)

<= x <= y (x is less than or equal to y)

== x == y (x is equal to y)

!= x != y (x is not equal to y)
Note that always whenever relational operator is applied its result is either 0 or 1.

LOGICAL OPERATORS IN C:
• These operators are used to perform logical operations on the given expressions.
• There are 3 logical operators in C language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page16


C Programming for Problem Solving I/II Semester Common to all branches

Operators Example/Description

&& (logical (x>5)&&(y<5)


AND) It returns true when both conditions are true

(x>=10)||(y>=10)
|| (logical
OR) It returns true when at-least one of the condition is true

!((x>5)&&(y<5))

It reverses the state of the operand “((x>5) && (y<5))”

! (logical If “((x>5) && (y<5))” is true, logical NOT operator makes it


NOT) false

BIT WISE OPERATORS IN C:


These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT),
^ (XOR), << (left shift) and >> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:

BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE.

1. & – Bitwise AND


2. | – Bitwise OR
3. ~ – Bitwise NOT

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page17


C Programming for Problem Solving I/II Semester Common to all branches

4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift
Consider x=40 and y=80. Binary form of these values are given below.
x=00101000
y= 01010000
All bit wise operations for x and y are given below.
1. x&y = 00000000 (binary) = 0 (decimal)
2. x|y = 01111000 (binary) = 120 (decimal)
3. ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41
(decimal)
4. x^y = 01111000 (binary) = 120 (decimal)
5. x << 1 = 01010000 (binary) = 80 (decimal)
6. x >> 1 = 00010100 (binary) = 20 (decimal)
When you specify the left shift operator << by 1 bit position the bits get shifted to left by
one bit position.bo is set to 0.Fascinatingly now its decimal equivalent is exactly the
double of the original number. If X= 64 then X<<1 would be 128.
In general note that X << n = X* 2n so assume x =32 and operation is x<<4. So it is 32
*24 =32*16=512.
Similarly the operator >> 1 shifts the data right by one bit position.Fascinatingly now its
decimal equivalent is Half of the original data.If X=64 then X>>1 would be 32.In general
note that X >> n = X/ 2n so assume x =32 and operation is x>>4. So it is 32 /24
=32/16=2.

C – Increment/decrement Operators
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax: Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page18


C Programming for Problem Solving I/II Semester Common to all branches

Example: Increment operator : ++ i ; i ++ ;


Decrement operator : – – i ; i – – ;

DIFFERENCE BETWEEN PRE/POST INCREMENT & DECREMENT OPERATORS IN C:

Below table will explain the difference between pre/post increment and decrement
operators in C programming language.
Operator Operator/Description

value of i is incremented before assigning it to the


Pre increment operator (++i) variable i

Post increment operator


(i++) value of i is incremented after assigning it to the variable i

value of i is decremented before assigning it to the


Pre decrement operator (-–i) variable i

Post decrement operator (i–-) value of i is decremented after assigning it to variable i

CONDITIONAL OR TERNARY OPERATORS IN C:

Conditional operators return one value if condition is true and returns another value is
condition is false.
This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);
To find biggest of 2 numbers :
Max = (x>y) ?x : y ;
This assigns either x or y to the variable Max.

To find biggest of three numbers we could write it as

Max= (x>y && x>z)? x :(y>z)?y:z ;


Precedence of Operators:
If more than one operators are involved in an expression, C language has a predefined rule
of priority for the operators. This rule of priority of operators is called operator precedence.
In C, precedence of arithmetic operators(*, %, /, +, -) is higher than relational operators(==,
!=, >, <, >=, <=) and precedence of relational operator is higher than logical operators(&&,
|| and !).

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page19


C Programming for Problem Solving I/II Semester Common to all branches

Operator Meaning of operator Associativity

() Functional call
[] Array element reference
-> Indirect member selection
. Direct member selection Left to right

! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion) Right to left

* Multiply
/ Divide
% Remainder Left to right

+ Binary plus(Addition)
- Binary minus(subtraction) Left to right

<< Left shift


>> Right shift Left to right

< Less than


<= Less than or equal
> Greater than
>= Greater than or equal Left to right

== Equal to
!= Not equal to Left to right

& Bitwise AND Left to right

^ Bitwise exclusive OR Left to right

| Bitwise OR Left to right

&& Logical AND Left to right

|| Logical OR Left to right

?: Conditional Operator Right to left

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page20


C Programming for Problem Solving I/II Semester Common to all branches

Operator Meaning of operator Associativity

Simple assignment
= Assign product
*= Assign quotient
/= Assign remainder
%= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift Right to left

, Separator of expressions Left to right

UNIT- II
Decision Making & Branching

In C programming it support sequential program statements which execute one statement


immediately after another. Here the flow is sequential it never change the flow of control from the
next line. The compiler executes the program sequentially in the order which they appear. This
happens when there are no options and if the repeated steps are not needed. But there are another

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page21


C Programming for Problem Solving I/II Semester Common to all branches

option when we need the options and when we want to use the selective steps repeatedly. In many
situations we may have to change the order of execution and want to repeat certain steps based on
any condition or until the condition meets, which means decision making. C supports much
decision making or control statements.

The main important decision making statements in c are as follows.


• If statement
• Switch statement

If statement
‘If’ is the most powerful decision making statement in C language. Thus it is used to control the
execution of statements. ‘If’ is used along with an expression. It is a two way branching or
decision making statement.

Syntax :

if(test expression)
{
Body of if;
}

Using an ‘if’ a computer first evaluate the expression and if it is true the body of if is executed
which means the flow of control passes to the if’s body, or if the test condition is false then the
flow of control passes to the immediate step next to if’s body. If there are more than one step in the
body of ‘if’ they are normally written with in brackets ‘{ }’ to denote it is the body of ‘if’.
The test expression will return a Boolean value which is a’0’ or ‘1’. Here 1 is ‘true’ and 0 denotes it
is ‘false’.

Depending upon the complexity and conditions to be tested if can be further subdivided.

• Simple if
• if…..else
• nested if…else
• if…else…if ladder

simple if statement
The general syntax of a simple if statement is

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page22


C Programming for Problem Solving I/II Semester Common to all branches

if(test expression)
{
Body of if;
}

Statement X;
The body of ‘if’ may be a single statement or group of statements. When the test expression returns
a true value these body of if is executed. If the condition is false the flow of control passes to the
statement X. The statement X will be executed in both cases.
If else statement
an extension to simple if is called if.. else statement.
Syntax:

if(test expression)
{
Body of if;
}
else
{
Body of else;
}

Statement x;
As a simple if statement first tests the condition. If it is true then executes the body of if and then
skips the next part and then passes the control in to the statement x. Here we added another
block which is the set of statements to do when the condition is false and it is named as else. The
flow passes to else part after skipping the body of if whenever the condition fails. The condition
may return ‘true’ or ‘false’ in both cases the statement x is executed.

Example :

if( code==1) boy=boy+1;


else girl=girl+1;

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page23


C Programming for Problem Solving I/II Semester Common to all branches

Flow Chart for If else construct

Nested if statement
It is used when a series of decisions are involved and have to use more than one if…else
statement.
Syntax :

if(condition 1)
{ if(condition 2)
{
body of if;
}
else
{
Body of else;
}
}
else
{
Body of else;
}
Statement x;

Example :

if( a>b)
{
if(a>c)

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page24


C Programming for Problem Solving I/II Semester Common to all branches

printf(“ a is greater”);
else
printf(“ c is greater”);
}
else
if(b>c)
Printf(“b is greater”);
else
Printf(“c is greater”);

The if… else… if ladder


To take multipath decisions or chain of ifs then we use the if …else…if ladder. It is in the
following general form
if(condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else
statement 4;

statement x;
The conditions are evaluated from the top of the ladder down words as soon as a true condition
is found. The compiler executes the ladder till a true condition is found, and when found a true
condition execute the statements associated with it. After executing the statements the control
passes to the statement x.
Example :
if(percentage >==80)
printf(“ Distinction”);
else if(percentage >==60)
printf(“ first class ”);
else if(percentage >==50)
printf(“ second class ”);
else
printf(“ failed “);

/* Write a Program to find all the possible Roots of Q.equation */


#include <stdio.h>
#include <math.h>

main()
{

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page25


C Programming for Problem Solving I/II Semester Common to all branches

float a,b,c;
float d;
float r1,r2;
printf("Enter Non-Zero Coefficients of A,B, C\n");
scanf("%f%f%f",&a,&b,&c);
printf(" A= %f B= %f C= %f \n",a,b,c);
if(a==0 || b==0 || c==0)
{
printf("Invalid Inputs ... Terminating from Program...\n");
getch();
exit(0);
}
d=b*b - 4*a*c;
if(d== 0)
{
printf("Roots are Equal & Real\n");
r1=r2= -b/(2*a);
printf("Root1 = %f \n",r1);
printf("Root2 = %f \n",r2);
}
else if( d > 0 )
{
printf("Roots are Distinct & Real\n");
r1 = ( -b + sqrt (d) )/(2*a);
r2 = ( -b - sqrt (d) )/(2*a);
printf("Root1 = %f \n",r1);
printf("Root2 = %f \n",r2);
}
else
{
printf("Roots are Complex \n");
r1 = -b/(2*a);
r2 = sqrt(fabs (d) )/(2*a);
printf("Root1 = %f + j %f\n",r1,r2);
printf("Root2 = %f - j %f\n",r1,r2);
}
}
===================================================================
OUTPUT
===================================================================
Run 1
Enter Non-Zero Coefficients of A,B, C
A= 1.000000 B= 0.000000 C= 5.000000
Invalid Inputs ... Terminating from Program...
===================================================================
Run 2
Enter Non-Zero Coefficients of A,B, C
A= 1.000000 B= -5.000000 C= 6.000000
Roots are Distinct & Real
Root1 = 3.000000
Root2 = 2.000000

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page26


C Programming for Problem Solving I/II Semester Common to all branches

===================================================================
Run 3
Enter Non-Zero Coefficients of A,B, C
A= 1.000000 B= -6.000000 C= 9.000000
Roots are Equal & Real
Root1 = 3.000000
Root2 = 3.000000
===================================================================
Run 4
Enter Non-Zero Coefficients of A,B, C
A= 1.000000 B= 4.000000 C= 5.000000
Roots are Complex
Root1 = -2.000000 + j 1.000000
Root2 = -2.000000 - j 1.000000
===================================================================
Don’t forget to include math.h in the program.

SWITCH STATEMENT ( Multi way Branching )

A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case.

Syntax
The syntax for a switch statement in C programming language is as follows −

switch(expression) {

case 1 :
statement(s);
break; /* optional */

case 2 :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The following rules apply to a switch statement −


1. The expression used in a switch statement must have an integral or character data
type.No floating point values are allowed.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page27


C Programming for Problem Solving I/II Semester Common to all branches

2. You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
3. The constant-expression for a case must be the same data type as the variable in
the switch, and it must be a constant or a literal.
4. When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
5. When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
6. Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
7. A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none of
the cases is true. No break is needed in the default case.

Example
#include <stdio.h>

int main () {

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page28


C Programming for Problem Solving I/II Semester Common to all branches

/* local variable definition */


char grade = 'B';

switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}

printf("Your grade is %c\n", grade );

return 0;
}

When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B

Before we discuss more about break statement, guess the output of this C program.
#include <stdio.h>
int main()

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page29


C Programming for Problem Solving I/II Semester Common to all branches

{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
case 2:
printf("Case2 ");
case 3:
printf("Case3 ");
case 4:
printf("Case4 ");
default:
printf("Default ");
}
return 0;
}
Output:
Case2 Case3 Case4 Default
I passed a variable to switch, the value of the variable is 2 so the control jumped to the
case 2, However there are no such statements in the above program which could break
the flow after the execution of case 2. That’s the reason after case 2, all the subsequent
cases and default statements got executed.

How to avoid this situation?


We can use break statement to break the flow of control after every case block.
Break statement in Switch Case
Break statements are useful when you want your program-flow to come out of the
switch body. Whenever a break statement is encountered in the switch body, the control
comes out of the switch case statement.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page30


C Programming for Problem Solving I/II Semester Common to all branches

Example of Switch Case with break


I’m taking the same above that we have seen above but this time we are using break.
#include <stdio.h>
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
}
return 0;
}
Output:
Case 2
Why didn’t I use break statement after default?
The control would itself come out of the switch after default so I didn’t use it, however if
you want to use the break after default then you can use it, there is no harm in doing
that.

Few Important points regarding Switch Case


1) Case doesn’t always need to have order 1, 2, 3 and so on. They can have any integer
value after case keyword. Also, case doesn’t need to be in an ascending order always, you
can specify them in any order as per the need of the program.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page31


C Programming for Problem Solving I/II Semester Common to all branches

2) You can also use characters in switch case. for example –


#include <stdio.h>
int main()
{
char ch='b';
switch (ch)
{
case 'd':
printf("CaseD ");
break;
case 'b':
printf("CaseB");
break;
case 'c':
printf("CaseC");
break;
case 'z':
printf("CaseZ ");
break;
default:
printf("Default ");
}
return 0;
}
Output:

CaseB
3) The expression provided in the switch should result in a constant value otherwise it
would not be valid.
For example:
Valid expressions for switch –
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions –
switch(ab+cd)
switch(a+b+c)
4) Nesting of switch statements are allowed, which means you can have switch
statements inside another switch. However nested switch statements should be avoided
as it makes program more complex and less readable.
5) Duplicate case values are not allowed. For example, the following program is
incorrect:
This program is wrong because we have two case ‘A’ here which is wrong as we cannot
have duplicate case values.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page32


C Programming for Problem Solving I/II Semester Common to all branches

#include <stdio.h>
int main()
{
char ch='B';
switch (ch)
{
case 'A':
printf("CaseA");
break;
case 'A':
printf("CaseA");
break;
case 'B':
printf("CaseB");
break;
case 'C':
printf("CaseC ");
break;
default:
printf("Default ");
}
return 0;
}
6) The default statement is optional, if you don’t have a default in the program, it would
run just fine without any issues. However it is a good practice to have a default statement
so that the default executes if no case is matched. This is especially useful when we are
taking input from user for the case choices, since user can sometime enter wrong value,
we can remind the user with a proper error message that we can set in the default
statement.

Quadratic equation using Switch Statement.


#include <stdio.h>
#include <math.h>

main()
{
Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page33
C Programming for Problem Solving I/II Semester Common to all branches

float a,b,c;
float d;
float r1,r2;
int ch;
printf("Enter Non-Zero Coefficients of A,B, C\n");
scanf("%f%f%f",&a,&b,&c);
printf(" A= %f B= %f C= %f \n",a,b,c);
if(a==0 || b==0 || c==0)
{
printf("Invalid Inputs ... Terminating from Program...\n");
exit(0);
}
d=b*b - 4*a*c;
ch=(d==0)?1:(d>0)?2:3 ;
switch(ch)
{
case 1: printf("Roots are Equal & Real\n");
r1=r2= -b/(2*a);
printf("Root1 = %f \n",r1);
printf("Root2 = %f \n",r2);
break;
case 2: printf("Roots are Distinct & Real\n");
r1 = ( -b + sqrt (d) )/(2*a);
r2 = ( -b - sqrt (d) )/(2*a);
printf("Root1 = %f \n",r1);
printf("Root2 = %f \n",r2);
break;
case 3: printf("Roots are Complex \n");
r1 = -b/(2*a);
r2 = sqrt(fabs (d) )/(2*a);
printf("Root1 = %f + j %f\n",r1,r2);
printf("Root2 = %f - j %f\n",r1,r2);
break;
}
}

Looping Statements in C
What are Loops?
In looping, a program executes the sequence of statements many times until the stated
condition becomes false. A loop consists of two parts, a body of a loop and a control

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page34


C Programming for Problem Solving I/II Semester Common to all branches

statement. The control statement is a combination of some conditions that direct the body
of the loop to execute until the specified condition becomes false.
Types of Loops
Depending upon the position of a control statement in a program, a loop is classified into
two types:
1. Entry controlled loop
2. Exit controlled loop
In an entry-controlled loop, a condition is checked before executing the body of a loop. It
is also called as a pre-checking loop.
In an exit-controlled loop, a condition is checked after executing the body of a loop. It is
also called as a post-checking loop.
The control conditions must be well defined and specified otherwise the loop will execute
an infinite number of times. The loop that does not stop executing and processes the
statements number of times is called as an infinite loop. An infinite loop is also called as
an "Endless loop."
Following are some characteristics of an infinite loop:
1. No termination condition is specified.
2. The specified conditions never meet.

'C' programming language provides us with three types of loop constructs:


1. The while loop
2. The do-while loop
3. The for loop

While Loop
A while loop is the most straightforward looping structure. The basic format of while
loop is as follows:
while (condition)

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page35


C Programming for Problem Solving I/II Semester Common to all branches

{
statements;
}
It is an entry-controlled loop. In while loop, a condition is evaluated before processing a
body of the loop. If a condition is true the body of a loop is executed. After the body of a
loop is executed then control again goes back at the beginning, and the condition is
checked if it is true, the same process is executed until the condition becomes false. Once
the condition becomes false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are immediately after the
loop. The body of a loop can contain more than one statement. In while loop, if the
condition is not true, then the body of a loop will not be executed, not even once.

#include<stdio.h> OUTPUT
#include<conio.h>
int main() 1
{ 2
int num=1; 3
while(num<=10) 4
{ 5
printf("%d\n",num); 6
num++; 7
} 8
9
} 10

Example Programs :
Write a Program to find GCD & LCM of Two Positive Integers & output the results
along with given Integers.Use Euclid's algorithm
# include <stdio.h>
main()
{

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page36


C Programming for Problem Solving I/II Semester Common to all branches

int m,n;
int a,b;
printf("Enter Two Non-Zero Numbers\n");
scanf("%d%d",&m,&n);
printf("M = %d\t N= %d\n",m,n);
a=m;
b=n;
while(m!=n)
{
if (m>n)
m=m-n;
else
n=n-m;
}
printf("GCD = %d\n", m);
printf("LCM = %d\n", (a*b)/m);

Write a C program to reverse a given Integer & check whether it is Palindrome or not.
Output the given number with suitable message.
#include <stdio.h>
main()
{
int n;
int rev=0,temp,rem;
printf("Enter the Integer Number...\n");
scanf("%d",&n);
temp=n;
while(n!=0)
{ rem=n%10;
rev =rev *10 + rem;
n = n/10;
}
if(rev == temp)
printf("%d is Palindrome...\n",temp);
else
printf("%d is not Palindrome...\n",temp);
getch();
}

Do.. WHILE Loop

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page37


C Programming for Problem Solving I/II Semester Common to all branches

A do-while loop is similar to the while loop except that the condition is always executed
after the body of a loop. It is also called an exit-controlled loop. The basic format of while
loop is as follows:
do {
statements
} while (expression); (Note that there should be semicolon at the end )
As we saw in a while loop, the body is executed if and only if the condition is true. In some
cases, we have to execute a body of the loop at least once even if the condition is false. This
type of operation can be achieved by using a do-while loop.
In the do-while loop, the body of a loop is always executed at least once. After the body is
executed, then it checks the condition. If the condition is true, then it will again execute the
body of a loop otherwise control is transferred out of the loop.
Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed.

#include<stdio.h> OUTPUT:
#include<conio.h> 2
int main() 4
{ 6
int num=1; 8
do 10
{ 12
printf("%d\n",2*num); 14
num++; 16
}while(num<=10); 18
20
}

Differences between While & Do While loop

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page38


C Programming for Problem Solving I/II Semester Common to all branches

While Loop Do While Loop


Entry controlled loop/Pre conditional Exit controlled loop / Post conditional
loop loop
Body of the loop gets executed if Irrespective of the condition body of
condition is true. loop gets executed at least once
Body of loop may not be executed if the Irrespective of the condition body of
condition is false loop gets executed at least once
Syntax : while( cond) Syntax: do
{ {
Body of the loop; Body of the loop;
} }while(condition);
BREAK Statement in Loops:
The break statement is used mainly in in the switch statement. It is also useful for
immediately stopping a loop.We consider the following program which introduces a
break to exit a while loop:
#include <stdio.h>
int main()
{
int num = 5;
while (num > 0)
{
if (num == 3)
break;
printf("%d\t", num);
num--;
}
}
Output: 5 4
Whenever a break statement is encountered in loops , it causes the loop to terminate. No
condition shall be checked and directly the loop gets terminated.

Continue statement in Loops:

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page39


C Programming for Problem Solving I/II Semester Common to all branches

The continue statement when specified in loops forces to skip the statements below the
continue statement and goes to beginning of the loop. The statements below the continue
statements upto the end of the loop are entirely skipped.
#include <stdio.h>
int main()
{
int nb = 7;
while (nb > 0)
{
nb--;
if (nb == 5)
continue;
printf("%d\", nb);
}
}

OUTPUT : 6 4 3 2 1

The value 5 is not printed as there is a condition if nb==5 continue;


so the
printf statement will not be executed.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page40


C Programming for Problem Solving I/II Semester Common to all branches

For loop
A for loop is a more efficient loop structure in 'C' programming. The general structure of
for loop is as follows:
for (initial value; condition; increment or decrement
{
statements;
}
• The initial value of the for loop is performed only once.
• The condition is a Boolean expression that tests and compares the counter to a
fixed value after each iteration, stopping the for loop when false is returned.
• The increment/decrement increases (or decreases) the counter by a set value.

Following program illustrates the use of a simple for loop:


#include<stdio.h>
int main()
{
int number;
for(number=1;number<=10;number++)
{
printf("%d\t",number);
}
}
OUTPUT :1 2 3 4 5 6 7 8 9 10

Loop within loops :

for( i=1; i<=10;i++)


{
for(j=1; j<=5;j++)
{
Statements to be executed;
}
}
i loop is called as outer loop and jth loop is called as inner loop.For each and every itera
th

tion of i the jth loop is performed 5 times; So totally 50 times the statements within the lo
op are executed.
When you place a semicolon at the end of the loop the compiler doesn’t rise any
errors while compiling the program, but it will treat the loop as executable statement and t
he statements within the loop are executed only once.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page41


C Programming for Problem Solving I/II Semester Common to all branches

Write a Program to find the Sine of an Given angle & number of terms

Sin(x) = x - x3/3! +x5/5!................ N terms


# include <stdio.h>

main()
{
float x,y;
float term,nr,dr;
int i,n;
float sum;
printf("Enter the Angle ....\n");
scanf("%f",&x);
y=x;
printf("Enter the Number of terms...\n");
scanf("%d",&n);
x= (x*3.1415)/180 ;
nr=x;
dr=1.0;
sum =0.0;
for(i=1;i<=n;i++)
{
term = nr/dr;
sum = sum + term;
nr = -nr * x * x ;
dr = dr *( 2*i) *(2*i+1);
}
printf("Sin( %f) = %f\n",y,sum);
}

Write a C program to display the following pattern using for loop.


1 main()

1 2 {

1 2 3 int i,j;
for(i=1;i<=5;i++)
1 2 3 4
{
1 2 3 4 5
for(j=1;j<= i; j++ )
printf(“%d\t”, j);
printf(“\n”);
}
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page42


C Programming for Problem Solving I/II Semester Common to all branches

1 main()

2 2 {

3 3 3 int i,j;
for(i=1;i<=5;i++)
4 4 4 4
{
5 5 5 5 5
for(j=1;j<= i; j++ )
printf(“%d\t”, i);
printf(“\n”);
}
}

Write a C program to display the following pattern using for loop.


1 main()

2 3 {

4 5 6 int i,j, k=1;


for(i=1;i<=5;i++)
7 8 9 10
{
11 12 13 14 15
for(j=1;j<= i; j++ )
printf(“%d\t”, k++

);
printf(“\n”);
}
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page43


C Programming for Problem Solving I/II Semester Common to all branches

Write a Program to find the Cosine of an angle from 0 to 180 in steps of 10 for 4
terms using the series Cos(x) = 1 - x2/2! +x4/4! -x6/6!
# include <stdio.h>
main()
{
float x,y;
float term,nr,dr,acc;
float sum;
int i;
for(y=0.0;y<=180.0;y+=10.0)
{
x=y;
x= (x*3.1415)/180 ;
nr=1.0;
dr=1.0;
sum =0.0;
for(i=1;i<=4;i++)
{
term = nr/dr;
sum = sum + term;
nr = -nr * x * x ;
dr = dr *( 2*i) *(2*i-1);
}
printf("Cos( %f) = %f\n",y,sum);
}
}
OUTPUT
Cos( 0.000000) = 1.000000
Cos( 10.000000) = 0.984809
Cos( 20.000000) = 0.939696
Cos( 30.000000) = 0.866033
Cos( 40.000000) = 0.766058
Cos( 50.000000) = 0.642807
Cos( 60.000000) = 0.500027
Cos( 70.000000) = 0.342054
Cos( 80.000000) = 0.173689
Cos( 90.000000) = 0.000046
Cos( 100.000000) = -0.173597
Cos( 110.000000) = -0.341967
Cos( 120.000000) = -0.499947
Cos( 130.000000) = -0.642736
Cos( 140.000000) = -0.765998
Cos( 150.000000) = -0.865987
Cos( 160.000000) = -0.939664
Cos( 170.000000) = -0.984792
Cos( 180.000000) = -1.000000

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page44


C Programming for Problem Solving I/II Semester Common to all branches

Unit- III Arrays.

Assume a situation where in you need to distribute an invitation card among your
relatives who are at Bangalore, Madras, Bombay , Delhi & Kolkatta. You start your journey
from Tumkur and go to all these cities randomly. Think about the time you required to
visit each of your relative. Tremendously it is very high.
Instead of this if all your relatives stay in a city in a colony with adjacent houses , how
much time you would require to visit all of them ? Tremendously it is very low.
The same is the concept of arrays.
Definition: Array is a group of elements that have a common variable name and
are identified separately from one another, by a subscript.

or

Array can be defined as a set of order data elements. Array refers to a list of data
elements stored together in a memory that have common variable name.

There are two types of array they are

1. Single dimensional array


2. Two dimensional array

One-dimensional array : It is a linear list of fixed number of data items of same type. All
these data items are accesses using the same name using a single subscript. It is similar to
a row or column matrix. It is also called as single dimensional array or one subscrpted
variable.

Array Declaration: Suppose the marks scored by the give statements are to be stored in to
an array. Then array is declared as using the syntax given below.

Data type array_name[size];


int marks[5];

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page45


C Programming for Problem Solving I/II Semester Common to all branches

The above statement create an array by name marks. The size of the array is mentioned.
With in the square braces ( [ ] ) the data type in the integer when the array is declared it is
the memory as shown below.
Marks:
0
1
2
3
4

The elements of the array can be occurred by using the subscript values the first
elements of the array states from zero hence to refer first location we can write marks[0]
similarly we can write marks[1], marks[2], marks [3] etc. for referring other location in
the array. The following statement will store data elements in to the array.
Marks [0]=800
Marks [1]=850
Marks [2]=700
Marks [3]=1000
Marks [4]=400
800
850
700
1000
400

In the above figure 0,1,2,3,4, represent the position of the array elements, can are also
called as subscripts. When the array is created all the elements are consequently
represented as shown in the figure.
In a common method to access the elements of the array for loop is used. Once the
array is declared of particular data type then the array holds similar type of elements.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page46


C Programming for Problem Solving I/II Semester Common to all branches

In the above example the array marks is declared of type int then only integer type of
elements can be stored into the array, it is not possible to stole either or character type
of data.
Accessing the elements of array
Accessing is nothing but reading and writing from or in to the array. In the above
example marks[0]=800; will store or write the number 800 in to array marks at position 0.
N=marks [0];
This statement read the 0th position or element from the array marks and the content will
be stored in to variable x.
The elements of array are also stored as shown in the below. --------Number [5] ---is the
name as the array whose size are 5 the elements can be stored in to the array
number [5]= {1,2,3,4,5};

1
2
3
4
5

Figure(1)
Operations on array
1. Like any other variable array variable name with individual elements
subscript can be used in arithmetic expression relationonal expression or
assignment statement.

Ex:-Consider the above array number the statement


X=number [4]; is assignment statement. the 4th elements are stored in to the
variable x i.e.
X=5

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page47


C Programming for Problem Solving I/II Semester Common to all branches

The array variable can be used in arithmetic operation i.e.


Y=number [ 0 ]+number [ 3 ];

Y=1+4
Y=5
Similarly relational operator can be used here the
elements [1] number [0]> number [4]

In the above figure(1) the indents 0,1,2,3 and 4 represent the position of the array elements,
and each element can be accessed by representing the index value listed in the figure(1).

In the common method to access the elements of the array for loop is used. Once the array
is declared of particulate data type then the array holds similar type of elements. In the
above example the array marks is declared of type into the integer type of elements can be
stored into array, it is not possible to store either float or character type of data.

Accessing the elements of array

Accessing is nothing but reading and writing from or in to the array. In the above
example marks[0]=800; will store or write the number 800 in to array marks at position 0.
N= marks [0];

This statements read the 0th position of elements from the array marks and the content
will be stored in to variable x.
The elements of array are also stored as shown in the below. -----------number[5]---is the
name as the array whose size is 5 the elements can be stored in to the array
number [5] ={1, 2, 3, 4, 5} ;
1
2
3
4

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page48


C Programming for Problem Solving I/II Semester Common to all branches

5
Operations on array
1. Like any other variable name with individual elements subscript can be used in
Arithmetic expression ,relational expression or in assignment statement.
Ex:- Consider the above array number the statement
X=number[4]; is a assignment statement. The 4th elements is stored in to the
variable x i.e. X=5
The array variable can be used in arithmetic operations i.e.
Y=number[0]+ number [3];
Y =1+4;
Y=5
Similarly relational operator can be used here the element [1] number [0]>number[4]
Here the element 1 is compared with 5
2. A new value can be stored or existing value of the array element can be changed.
Ex : number[4] =100;
In this the 4th element of the array is replaced by a new value 100 and old value 5
will be erased.
3. Array elements can be read and stored in array one by one using loop control
Statement.
Ex :- for (i=0; i<4; i ++)
Scanf(“%d”, &number [i ]);
4. Individual array elements can be printed using print function.
Ex:- printf (“%d”, number [4 ]);
5. Individual array elements can appear in expressions.
For ex :-
Let y= 10 and 4th (elements ) position is added y and sum should be stored in to
variable x. Then we can write the expression
X= y +number[4];
X=10 +5
X=15

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page49


C Programming for Problem Solving I/II Semester Common to all branches

Advantages of array
1. It is very easy to read and write elements from or into the array.
2. using for loop the elements of the array can be easily accessed.
Disadvantages of array
1. In the array once the size is declared it is fixed.
2. Direct insertion or deletion of elements is not possible in the array.
3. Once the data type is declared the other type of values can not be stored in array.

Simple Programs Using Arrays


Write a program using array to store 5 integer elements and print all the elements

# include <stdio.h >


main( )
{
int name[10 ], n=5, i;
for (i=0;i<n; i ++ )
{
scanf (“%d”, &name[i ]);
}
for (i=0; i<n; i ++)

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page50


C Programming for Problem Solving I/II Semester Common to all branches

{
printf (“%d \t”, name[i]);
}

Result : 46 12 45 13
46 12 45 1 3.

Write a program using array to store and print 5 real nos.


# include <stdio.h>
main( )
{
float real[10];
int n=5,i ;
for(i= 0 ; i< n; i ++)
{
scanf (“%f”, &real[i]);
}
for (i=0 ; i<n; i ++)
{
printf (“%d \t’, real[i]);
}

SORTING
Sorting is a process to arranging the elements either in ascending order or in Descending
order .
There are different methods available for sorting the elements they are

1. Selection sort
2. Bubble sort
3. Quick sort
4. Merge sort

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page51


C Programming for Problem Solving I/II Semester Common to all branches

5. Heap sort
Selection Sort

41 5 -1 -1 -1 -1 -1 -1 -1
5 41 41 41 5 5 5 5 5
-1 -1 5 5 41 41 6 6 6
6 6 6 6 6 6 41 41 8
8 8 8 8 8 8 8 8 41
pass 1 Pass 2 pass 3 pass 4

In selection sort beginning with the first element in the array a search is performed
to locate the element which is the smallest. When the element is formed it is inter changed
with the first element of the array. This interchange places the first smallest element in the
first position of the array. A search for second smallest all the elements in the array. In
the last pass all the elements are arranged in the ascending order.

In the above example the elements 41, 5, –1, 6, 8 are arranged in the ascending
order. The number of passes required to arrange the element is 1 less than number of
elements the formula is
Number of passes = (n-1)

Where n= no. of elements in the array we can observe from the above example that
in the first pass first least element is placed in the first position. Similarly in the second
pass second least element is placed in the second position . In the finally pass the all the
elements are arranged in the ascending order.
Arrange the elements in the ascending order using selection sort the elements are
-21, 98, 6, 3.

-21 -21 -21 -21 -21 -21 -21 -21 -21


98 98 98 98 98 6 3 3 3
6 6 6 6 6 98 98 98 6

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page52


C Programming for Problem Solving I/II Semester Common to all branches

3 3 3 3 3 3 6 6 98
Pass 1 Pass 2 Pass 3
write a program to sort the given number in Descending order using selection sort
main()
{
int a[10],n,i,j;
int mpos,temp;
printf("Enter the Length fo array\n");
scanf("%d",&n);
printf("Enter %d Elements to Array...\n",n);
for(i=1;i<=n;i++)
scanf(" %d",&a[i]);
for(i=1;i<=n-1;i++)
{
mpos=i;
for(j=i+1;j<=n;j++)
{
if(a[j] > a[mpos] )
{
mpos=j;
}
}
temp =a[mpos];
a[mpos]=a[i];
a[i] =temp;
}
printf("Sorted Elemenst are....\n");
for(i=1;i<=n;i++)
printf("%d\t",a[i]);
}
Bubble Sort
In this method the elements with small keys to move or Bubble up. After the first pass,
the largest elements will be kept in the nth position or each successive pass the elements
with next largest keys will be placed in the position in the order (n-1), (n-2), (n-3)-------
---
In the Bubble sort the elements are stored in the opposite direction to that or selection sort.
In the bubble sort it may take (n-1) passes or even less than that.
Bubble sort method. The elements are 9,8,-6,4,3.
9 8 8 8 8 8 -6 -6 -6 -6 -6 -6 -6
8 9 -6 -6 -6 -6 8 4 4 4 4 3 3

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page53


C Programming for Problem Solving I/II Semester Common to all branches

-6 -6 9 4 4 4 4 8 3 3 3 4 4
4 4 4 9 3 3 3 3 8 8 8 8 8
3 3 3 3 9 9 9 9 9 9 9 9 9
Pass 1 Pass 2 Pass 3
# include <stdio.h>
main()
{
int a[10],n,i,j,temp;
printf("Enter the Length of Array\n");
scanf("%d",&n);
printf("N= %d\n",n);
printf("Enter %d Non-Repeated Elements ....\n",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n-1;i++)
{
for(j=1;j<=n-i;j++)
{
if(a[j] > a[j+1])
{
temp =a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nSorted Array is ......\n");
for(i=1;i<=n;i++)
printf("%d\t",a[i]);
}
Searching
Searching is a process which is used to find the given elements known as
key element in the array.If the elements is present the search is successful otherwise the
search is unsuccessful there are two methods is searching.
Linear search: In linear search method the elements to be checked is compared with first
elements in array. If both are equal the search is successful. If not the key elements is
compared with the second element in the array. This comparison is done with the all
elements in the array, the elements is present output as successful otherwise, output has
unsuccessful. This method is suitable when the size of the array is small. If the size of the

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page54


C Programming for Problem Solving I/II Semester Common to all branches

array is large this method takes lot of time to search for the key elements if the element is
place in.
Write a program, algorithm flowchart to search for the key element in the array.
Using linear method.

#include<stdio.h>
#include<process.h>
main()
{
int a [20],n,j,key,found=0;
printf (“\nEnter the size of the array : ”);
scanf(“%d”,&n);
printf (“\nEnter the elements in to the array \n”);
for (i=1;i<=n;i++)
scanf (“%d”,&a[i]);
printf (“\nEnter the key element : ”);
scanf (“%d”,&key);
for (i=1;i<=n;i++)
{
if(a[i]==key)
{
found=1;
break;
}
}
If(found==1)
Printf(“\nSearch is Successful”);
else
printf (“\nThe search is un Unsuccessful”);

}
Binary search method

In binary search method all the elements should be in ascending order. The binary
search method is the best searching technique compare to linear search, because number
of comparison required or less.
In Binary search method first the value of mid is found using the formula.
mid = Low + high
2

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page55


C Programming for Problem Solving I/II Semester Common to all branches

where low is the starting location of the array and high is nth location of the array then
mid value is compared with the key element . if mid value is equal to key elements then
search is successful, if the mid value is less than key element than change the low value=
mid –1. Repeat the same process until low is less than or equal to high.

Write a Program to find the key element in the array using binary search method.
#include <stdio.h >
main ( )
{
int a [20], i, low, high, mid, key, n;
printf (“\nEnter the size of the array : “);
scanf (“%d”, &n );
printf (“\nEnter the elements in to the array \n “);
for (i=1; i<=n; i++)
scanf (“%d”, &a[i]);
printf(“\nEnter the key element : “);
scanf (“%d”, &key);
low =1;
high =n;
while (low <=high)
{
mid =(low +high )/2;
if (a[mid ] ==key )
{
found=1;
break;
}
if (a [mid ]< key )
low =mid +1;
else
high =mid –1
}

If (found==1)
printf (“\nThe search is successful “);
else
printf (“\nThe search is unsuccessful “);
}

Two dimensional array

Single dimensional array is represented as a [m ] where a is the name of the array and m
is the number of elements in the array.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page56


C Programming for Problem Solving I/II Semester Common to all branches

Two dimensional array is represented as a [m ] [n ] where m is the size of rows and n is


the size of colunns . Very commonly two dimensional array is used to represent matrix.
Another type of array is multi dimensional array which is represented as a [x] [y] [z] this
is used to represent three dimensional objects.

Ex :- Consider a 2 x 2 matrix represented as a [2] [2] then the array is 1 2 each element in
the matrix has got position.

3 4

The first element position is 1,1 and second element is 1,2 third element is 2,1 and fourth
element is 2,2. When it is represented by two dimensional array the position of the
elements are A11 , A12, A21, A22.

Write a program to store the elements is to a matrix print the element in to a after matrix.

# include <stdio.h >


main ( )
{
int a [5][5], i, j, m, n;
printf (“\nEnter the size of the matrix : “);
scanf (“%d%d”, &m, &n);
printf(“\nEnter the elements in to the matrix \n “);
for (i=1; i<=m; i++)
{
for (j=1; j<=n; j++)
{
scanf(“%d”, &a [i][j]);
}
}
printf (“ \nThe Given Elements in Matrix Format \n”);
for (i=1; i<=m; i++)
{
for (j=1; j<=n; j++)
{
printf (“%d\t” , a[i] [j]);
}
printf (“\n”);
}
}

Consider the two matrix A & B the matrix A 1 2 and B 4 9


3 4 6 7

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page57


C Programming for Problem Solving I/II Semester Common to all branches

The addition of a matrix is carried out W.R.T the position of the elements in the matrix i.e.
the element which is in first row first column of A is added to the element first row first
column of B the result is stored in to the one more matrix C in the first column. This is
represent of all the elements in the matrix.

It is noted that for addition of the two matrix, they should be off same type other wise
addition is not possible
for Ex:-If A is 2X2 Matrix them b should also be 2X2 matrix.

Write a program to add the two matrix A and B and store the result in the matrix C.
#include<stdio.h>

main()
{
int a[5][5],b[5][5],c[5][5];
int i,j,m,n,p,q;
printf (“\n Enter the size of the First Matrix : “);
scanf (“%d%d”,&m,&n”);
printf (“\nEnter the size of the Second Matrix : ”);
scanf (“%d%d”,&p,&q);
if ((m==p)&&(n==q))
{
printf (“\nEnter the First Matrix Element \n”);
for (i=1;i<=m;i++)
{
for (j=1;j<=n;j++)
{
scanf (“%d”,&a[i][j]);
}
}
printf (“\nEnter the Second Matrix Elements \n”);
for (i=1;i<=p;i++)
{
for (j=1;j<=q;j++)
{
scanf (“%d”,&b[i][j]);
}
}
for (i=1;i<=p;i++)
{
for (j=1;j<=q;j++)
{
c[i][j]= (a[i][j] + b[i][j]);
}
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page58


C Programming for Problem Solving I/II Semester Common to all branches

printf (“\nThe Sum of Two Matrix are\n“);


for (i=1;i<=m;i++)
{
for (j=1;j<=n;j++)
{
printf (“\t%d”,c[i][j]);
}
printf (“\n”);
}
else
printf (“ Addition is not possible\n”);
}
}

Unit IV: Strings: Character Array


Strings are actually one-dimensional array of characters terminated by a null character
'\0'. Thus a null-terminated string contains the characters that comprise the string
followed by a null.
The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array containing
the string is one more than the number of characters in the word "Hello."

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page59


C Programming for Problem Solving I/II Semester Common to all branches

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as
follows –
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C

Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try
to print the above mentioned string
#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}

How to declare a string?

char s[5];

Now S is a string capable of holding 5 characters including a NULL character.


Read string in C using scanf()

In C language, the scanf() function is used to read primitive type data. The string is also
the group of characters, so it also can be used to read the string. There are several ways
and limitations for using the scanf() function to read the string.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page60


C Programming for Problem Solving I/II Semester Common to all branches

Read string in C using scanf() with %s

The String may be read by using the %s conversion with the function scanf(), but there are
some restrictions
An address operator is not required to read string since it is already a pointer. It is optional
to use the address operator (&) to read string. If we use it then no error occurs.

#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string:");
scanf("%s",&str);
printf("String = %s",str);
return 0;
}

Output:-
Enter String: Language
String = Language

The scanf() function read-only first word, when white space came then it stops reading.
If we try to read “Know Program” then it will read-only “Know”.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter String: ");
scanf("%s",str);
printf("String = %s", str);
return 0;
}
Output:-

Enter String: Language


String = Language

Enter String: Know Program


String = Know

There should be enough space to read the string. If there is no enough space then the
program will be terminated.
#include<stdio.h>
int main()
{
char str[5];

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page61


C Programming for Problem Solving I/II Semester Common to all branches

printf("Enter String: ");


scanf("%s",str);
printf("String = %s", str);
return 0;
}
Output:- Enter String: Language

*** stack smashing detected ***: terminated

Aborted (core dumped)

In string, size should be large enough to store all data. If it is not large enough then it will
destroy whatever follows the array in memory. Therefore, we must make sure we don’t
exceed the length of the data.
We can protect against the user entering too much data by using width in the field
specification. We already discussed in detail about width:- width modifier using printf.
The width specifies the maximum number of characters to be read.
#include<stdio.h>
int main()
{
char str[5];
printf("Enter a string: ");
scanf("%4s",str);
printf("String = %s",str);
return 0;
}

Output:-

Enter a string: Programming


String = Prog

Read string in C using scanset conversion code ( […] )


The scanset conversion facility provided by scanf() is a useful string input method. This
conversion facility allows the programmer to specify the set of characters that are
acceptable as part of the string. A scanset conversion consists of a list of acceptable
characters enclosed within square brackets.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string in lower case: ");
scanf("%[a-z]",str);
printf("String = %s\n",str);

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page62


C Programming for Problem Solving I/II Semester Common to all branches

return 0;
}
Output:-

Enter a string in lower case: knowProgram


String = know

Enter a string in lower case: know program


String = know

The above program only reads lowercase characters whenever it encounters another
character except for lowercase character then it stops reading. In “knowProgram” it reads
only “know” because the next character is in capital letter. When “know program” input
is given then also it reads only “know” because space is a special character, not a lowercase
character. In the third input-output “Know Program”, the first character is an uppercase
character, so it will not read the string. If any digits came then also it will not read from
the digit.
scanf("%[A-Z]",str);
It will read only uppercase characters, whenever other characters came then it will stop
reading the characters.
scanf("%[a-z,A-Z]",str);
The above program will read uppercase characters, lowercase characters, and digits.
Except these whenever any other character is encountered then scanf() will stop reading.

Read string in C using scanset with [^\n] (single line)


The circumflex (^) plays an important role while taking input. [^\n] will read input until
the user press the enter key, otherwise, it will keep reading input from the screen.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string: ");
scanf("%[^\n]",str);
printf("String = %s\n",str);
return 0;
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page63


C Programming for Problem Solving I/II Semester Common to all branches

Multiline input using scanset

One can use a bracketed string read, %[…] where the square brackets are used to enclose
all characters which are permissible in the input. If any character other than those listed
within the brackets occurs in the input string, further reading is terminated.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string, terminated with a star(*): ");
scanf("%[^*]",str);
printf("String = %s\n",str);
return 0;
}

The above program will read input until the user enters the star * symbol. After * symbol,
it will stop reading. In this way, we can read multiple lines of characters. It will read white
space also, Only stop reading when a * symbol came. Otherwise, it will keep reading the
input from the user.
[^*] :- It will stop reading only when a * is entered.

[^~] :- It will stop reading only when a tilde(~) is entered.

[^k] :- It will stop reading only when a lower case character 'k' is entered.

[^9] :- It will stop reading only when the digit 9 is entered.

[^(0-9)]:-It will stop reading only when any digit is entered.

[^*~?] :- It will stop reading only when * or ~ or ? is entered.

String Handling Functions in C Language

1) strlen( ) Function :
strlen( ) function is used to find the length of a character string.
Example: int n;
char st[20] = “Bangalore”;
n = strlen(st);
• This will return the length of the string 9 which is assigned to an integer variable n.
• Note that the null character “\0‟ available at the end of a string is not counted.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page64


C Programming for Problem Solving I/II Semester Common to all branches

2) strcpy( ) Function :
strcpy( ) function copies contents of one string into another string. Syntax for strcpy
function is given below.
Syntax: char * strcpy (char * destination, const char * source);
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t be
copied into destination string.
For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and
remaining 10 characters won’t be copied and will be truncated.
Example : char city[15];
strcpy(city, “BANGALORE”) ;

This will assign the string “BANGALORE” to the character variable city.
3) strcat( ) Function :
strcat( ) function in C language concatenates two given strings. It concatenates source
string at the end of destination string. Syntax for strcat( ) function is given below.
Syntax : char * strcat ( char * destination, const char * source );

Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.

• As you know, each string in C is ended up with null character (‘\0′).


• In strcat( ) operation, null character of destination string is overwritten by source
string’s first character and null character is added at the end of new destination string
which is created after strcat( ) operation.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page65


C Programming for Problem Solving I/II Semester Common to all branches

4 strcmp( ) Function :
strcmp( ) function in C compares two given strings and returns zero if they are same. If
length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0
value.
Syntax : int strcmp ( const char * str1, const char * str2 );
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.
Example :
char city[20] = “Madras”;
char town[20] = “Mangalore”;
strcmp(city, town);
This will return an integer value “-10‟ which is the difference in the ASCII values of the
first mismatching letters “D‟ and “N‟.
5 strrev() function :
strrev() function reverses a given string in C language.
Syntax : char *strrev(char *string);
Example :
char name[20]=”ftl”; then
strrev(name)= ltf

Program to Concatenate two strings without using Built in functions


#include<string.h>
main()
{
char str1[100],str2[100];
int i,j,len1=0,len2=0;
printf("Enter String1....\n");
gets(str1);
printf("Enter String2....\n");
gets(str2);
for(i=0;str1[i]!='\0';i++)
len1++;
for(i=0;str2[i]!='\0';i++)
len2++;
for(j=0;str2[j]!='\0';j++)
str1[len1+j]=str2[j];
printf("The Concatenated String is...... %s\n",str1);
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page66


C Programming for Problem Solving I/II Semester Common to all branches

Program to implement STRCPY without using Built in functions

#include<string.h>
main()
{
char str1[100],str2[100];
int i,j,len1=0,len2=0;
printf("Enter String1....\n");
gets(str1);
for(i=0;str1[i]!='\0';i++)
str2[i]=str1[i];
printf("The Copied String is...... %s\n",str2);
}

Program to implement STRREV without using Built in functions

#include<string.h>
main()
{
char str1[100],temp;
int i,j,len1=0,len2=0;
printf("Enter String1....\n");
gets(str1);
i=0;
while(str1[i]!='\0')
{
len1++;
++i;
}
i=0;
j=len1-1;
while(i<len1/2)
{
temp=str1[i];
str1[i]=str1[j];
str1[j]=temp;
i++;
j--;
}
printf("Reversed String is .... %s\n",str1);
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page67


C Programming for Problem Solving I/II Semester Common to all branches

* Write a Program to read N names, store them in form of array and sort them in
Alphabetical manner. Output the given names & sorted names with suitable headings
# include <stdio.h>
main()
{
char a[10][25];
int n;
int i,j;
char temp[25];
printf("Enter the Length of Array\n");
scanf("%d",&n);
printf("N= %d\n",n);
printf("Enter %d Non-Repeated Names ....\n",n);
for(i=1;i<=n;i++)
{
scanf("%s",a[i]);
}
for(i=1;i<=n-1;i++)
{
for(j=0;j<=n-i;j++)
{
if ( strcmp(a[j] , a[j+1])>0)
{
strcpy(temp,a[j]);
strcpy(a[j],a[j+1]);
strcpy(a[j+1],temp);
}
}
}
printf("\nSorted Names are ......\n");
for(i=1;i<=n;i++)
printf("%s\t",a[i]);
getch();
}
/*
OUTPUT
=================================================================
Enter the Length of Array
N= 5
Enter 5 Non-Repeated Names ....
Zameer Arun Kumar Prasanna Varini
Sorted Names are ......
Arun Kumar Prasanna Varini Zameer
=================================================================

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page68


C Programming for Problem Solving I/II Semester Common to all branches

/* Write a Program to find the Number of Vowels in a String..... */


# include <string.h>
# include <conio.h>
main()
{
char str[100];
int i, acount=0 , ecount=0, , icount=0 , ,ocount=0, ,ucount=0 ,,others=0;
printf("Enter the String.......\n");
gets(str);
printf("The Entered String is....\n");
puts(str);
i=0;
for(i=0;str[i]!='\0';i++)
switch(toupper(str[i]) )
{
case 'A': ++acount;
break;
case 'E': ++ecount;
break;
case 'I': ++icount;
break;
case 'O': ++ocount;
break;
case 'U': ++ucount;
break;
}
printf("Vowel A|a appears %d times\n",acount);
printf("Vowel E|e appears %d times\n",ecount);
printf("Vowel I|i appears %d times\n",icount);
printf("Vowel O|o appears %d times\n",ocount);
printf("Vowel U|u appears %d times\n",ucount);
printf("Consonats appears %d times\n", i-
(acount+ecount+icount+ocount+ucount));
getch();
}
=================================================================
OUTPUT
Enter the String.......
The Entered String is....
beautifoul
Vowel A|a appears 1 times
Vowel E|e appears 1 times
Vowel I|i appears 1 times
Vowel O|o appears 1 times
Vowel U|u appears 2 times
Consonants appears 4 times
=================================================================

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page69


C Programming for Problem Solving I/II Semester Common to all branches

Pointers
A Pointer in C language is a variable which holds the address of another variable of same
data type.
Pointers are used to access memory and manipulate the address.
Pointers are one of the most distinct and exciting features of C language. It provides power
and flexibility to the language. Although pointers may appear a little confusing and
complicated in the beginning, once you understand the concept, you will be able to do so
much more with C language. Before we start understanding what pointers are and what
they can do, let's start by understanding what does "Address of a memory location"
means?

Address in C
Whenever a variable is defined in C language, a memory location is assigned for it, in
which it's value will be stored. We can easily check this memory address, using
the & symbol.
If var is the name of the variable, then &var will give it's address.
Let's write a small program to see memory address of any variable that we define in our
program.
#include<stdio.h>
void main()
{
int var = 7;
printf("Value of the variable var is: %d\n", var);
printf("Memory address of the variable var is: %x\n", &var);
}

Value of the variable var is: 7


Memory address of the variable var is: bcc7a00
You must have also seen in the function scanf(), we mention &var to take user input for
any variable var.
scanf("%d", &var);This is used to store the user inputted value to the address of the
variable var.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page70


C Programming for Problem Solving I/II Semester Common to all branches

Concept of Pointers
Whenever a variable is declared in a program, system allocates a location i.e an address
to that variable in the memory, to hold the assigned value. This location has its own
address number, which we just saw above.
Let us assume that system has allocated memory location 80F for a variable a.

int a = 10;

We can access the value 10 either by using the variable name a or by using its
address 80F.
The question is how we can access a variable using it's address? Since the memory
addresses are also just numbers, they can also be assigned to some other variable. The
variables which are used to hold memory addresses are called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an address of some
other variable. And the value of a pointer variable gets stored in another memory
location.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page71


C Programming for Problem Solving I/II Semester Common to all branches

Benefits of using pointers


Below we have listed a few benefits of using pointers:

1. Pointers are more efficient in handling Arrays and Structures.

2. Pointers allow references to function and thereby helps in passing of function as


arguments to other functions.
3. It reduces length of the program and its execution time as well.
4. It allows C language to support Dynamic Memory management.

Declaring, Initializing and using a pointer variable in C


General syntax of pointer declaration is, datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer
variable is pointing. void type pointer works with all data types, but is not often used.
Here are a few examples:
int *ip // pointer to integer variable

float *fp; // pointer to float variable

double *dp; // pointer to double variable

char *cp; // pointer to char variable

Initialization of C Pointer variable


Pointer Initialization is the process of assigning address of a variable to a pointer variable.
Pointer variable can only contain address of a variable of the same data type. In C
language address operator & is used to determine the address of a variable.
The & (immediately preceding a variable name) returns the address of the variable

associated with it.


#include<stdio.h>

void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variable always point to variables of same datatype. Let's have an example to
showcase this:

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page72


C Programming for Problem Solving I/II Semester Common to all branches

#include<stdio.h>

void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}
If you are not sure about which variable's address to assign to a pointer variable while
declaration, it is recommended to assign a NULL value to your pointer variable. A pointer
which is assigned a NULL value is called a NULL pointer.
#include <stdio.h>

int main()
{
int *ptr = NULL;
return 0;
}

Using the pointer or Dereferencing of Pointer


Once a pointer has been assigned the address of a variable, to access the value of the
variable, pointer is dereferenced, using the indirection operator or dereferencing
operator *.
#include <stdio.h>

int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer

printf("%d", *p); //this will print the value of 'a'

printf("%d", *&a); //this will also print the value of 'a'

printf("%u", &a); //this will print the address of 'a'

printf("%u", p); //this will also print the address of 'a'

printf("%u", &p); //this will print the address of 'p'

return 0;
}
Points to remember while using pointers
1. While declaring/initializing the pointer variable, * indicates that the variable is a
pointer.
2. The address of any variable is given by preceding the variable name with
Ampersand &.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page73


C Programming for Problem Solving I/II Semester Common to all branches

3. The pointer variable stores the address of a variable. The declaration int *a doesn't
mean that a is going to contain an integer value. It means that a is going to contain
the address of a variable storing integer value.
4. To access the value of a certain address stored by a pointer variable, *is used.
Here, the * can be read as 'value at'.
Direct and Indirect Access Pointers
In C, there are two equivalent ways to access and manipulate a variable content
• Direct access: we use directly the variable name
• Indirect access: we use a pointer to the variable
Let's understand this with the help of program below
#include <stdio.h>
/* Declare and initialize an int variable */
int var = 1;
/* Declare a pointer to int */
int *ptr;
int main( void )
{
/* Initialize ptr to point to var */
ptr = &var;
/* Access var directly and indirectly */
printf("\nDirect access, var = %d", var);
printf("\nIndirect access, var = %d", *ptr);
/* Display the address of var two ways */
printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);
/*change the content of var through the pointer*/
*ptr=48;
printf("\nIndirect access, var = %d", *ptr);
return 0;}

After compiling the program without any errors, the result is:

Direct access, var = 1


Indirect access, var = 1

The address of var = 4202496


The address of var = 4202496

Indirect access, var = 48

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page74


C Programming for Problem Solving I/II Semester Common to all branches

Pointers Arithmetic :The pointer operations are summarized in the


following figure

If a P pointer points to an X variable, then * P can be used wherever X can be written.


The following expressions are equivalent:

int X =10
int *P = &Y;
For the above code, below expressions are true

Expression Equivalent Expression

Y=*P+1 Y=X+1
*P=*P+10 X=X+10
*P+=2 X+=2
++*P ++X
(*P)++ X++

Pointer and Arrays


Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page75
C Programming for Problem Solving I/II Semester Common to all branches

When an array is declared, compiler allocates sufficient amount of memory to contain all
the elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler. Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing to the
first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In
short, arr has two purpose - it is the name of the array and it acts as a pointer pointing
towards the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr; // Or
p = &arr[0]; //both the statements are equivalent.

Now we can access every element of the array arr using p++ to move from one element
to another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.

Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use that
pointer to access the array elements. Lets have an example,

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page76


C Programming for Problem Solving I/II Semester Common to all branches

#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}

return 0;
}
In the above program, the pointer *p will print all the values stored in the array one by
one. We can also use the Base address (a in above case) to act as a pointer and print all
the values.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page77


C Programming for Problem Solving I/II Semester Common to all branches

Pointer to Multidimensional Array


A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to
such an array. As we know now, name of the array gives its base address. In a[i][j], a will
give the base address of this array, even a + 0 + 0 will also give the base address, that is
the address of a[0][0]element.
Here is the generalized form for using pointer with multidimensional arrays.

*(*(a + i) + j) which is same as, a[i][j]

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page78


C Programming for Problem Solving I/II Semester Common to all branches

Functions in C
A function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions. You can divide up your code into separate functions. How you divide up your
code among different functions is up to you, but logically the division is such that each
function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call.
For example, strcat() to concatenate two strings, memcpy() to copy one memory location
to another location, and many more functions. A function can also be referred as a method
or a sub-routine or a procedure, etc.

Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name (parameter list)
{
body of the function
}
A function definition in C programming consists of a function header and a function
body. Here are all the parts of a function −

• Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
• Function Body − The function body contains a collection of statements that define
what the function does.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page79


C Programming for Problem Solving I/II Semester Common to all branches

Example
Given below is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum value between the two −

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
the following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top
of the file calling the function.

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function.
A called function performs a defined task and when its return statement is executed or
when its function-ending closing brace is reached, it returns the program control back to
the main program.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page80


C Programming for Problem Solving I/II Semester Common to all branches

To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.
For example −

#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}

/* function returning the max between two numbers */


int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

We have kept max() along with main() and compiled the source code. While running the
final executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a
function −
i) Call by Value
ii) Call by Address (Reference)

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page81


C Programming for Problem Solving I/II Semester Common to all branches

Call by Value : This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter inside the
function have no effect on the argument.
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
By default, C programming uses call by value to pass arguments. In general, it means the
code within a function cannot alter the arguments used to call the function. Consider the
function swap() definition as follows.
/* function definition to swap the values */
void swap(int x, int y) {

int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */

return;
}

Now, let us call the function swap() by passing actual values as in the following example
#include <stdio.h>

/* function declaration */
void swap(int x, int y);

int main () {

/* local variable definition */


int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */


swap(a, b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0;
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page82


C Programming for Problem Solving I/II Semester Common to all branches

Let us put the above code in a single C file, compile and execute it, it will produce the
following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there are no changes in the values, though they had been changed inside
the function.
Call by Address(Reference) : This method copies the address of an argument into the
formal parameter. Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect the argument.
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. It means the changes made to the parameter affect the
passed argument.
To pass a value by reference, argument pointers are passed to the functions just like any
other value. So accordingly you need to declare the function parameters as pointer types
as in the following function swap(), which exchanges the values of the two integer
variables pointed to, by their arguments.
/* function definition to swap the values */
void swap(int *x, int *y) {

int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */

return;
}

Let us now call the function swap() by passing values by reference as in the following
example –

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page83


C Programming for Problem Solving I/II Semester Common to all branches

#include <stdio.h>

/* function declaration */
void swap(int *x, int *y);

int main () {

/* local variable definition */


int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.


* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0;
}

Let us put the above code in a single C file, compile and execute it, to produce the
following result −

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

It shows that the change has reflected outside the function as well, unlike call by value
where the changes do not reflect outside the function.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page84


C Programming for Problem Solving I/II Semester Common to all branches

Category of Functions

A function depending an whether the arguments are present or not and whether a value
is returned or not, may belong to one of following categories
1. Function with no return values, no arguments
2. Functions with arguments, no return values
3. Functions with arguments and return values
4. Functions with no arguments and return values.
1.)In this category, the function has no arguments. It does not receive any data from the
calling function. Similarly, it doesn’t return any value. The calling function doesn’t
receive any data from the called function. So, there is no communication between calling
and called functions.
Example

#include <stdio.h>

void checkPrimeNumber();

int main()
{
checkPrimeNumber(); // argument is not passed
return 0;
}

// return type is void meaning doesn't return any value


void checkPrimeNumber()
{
int n, i, flag = 0;

printf("Enter a positive integer: ");


scanf("%d",&n);

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page85


C Programming for Problem Solving I/II Semester Common to all branches

The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside he main() function
indicates that no argument is passed to the function. The return type of the function is void.
Hence, no value is returned from the function.
2.) In this category, function has some arguments . it receives data from the calling
function, but it doesn’t return a value to the calling function. The calling function doesn’t
receive any data from the called function. So, it is one way data communication between
called and calling functions.

#include <stdio.h>
void checkPrimeAndDisplay(int n);

int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);

// n is passed to the function


checkPrimeAndDisplay(n);

return 0;
}
// return type is void meaning doesn't return any value
void checkPrimeAndDisplay(int n)
{
int i, flag = 0;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page86


C Programming for Problem Solving I/II Semester Common to all branches

The integer value entered by the user is passed to the checkPrimeAndDisplay() function.
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a
prime number or not and displays the appropriate message.
3) In this category, functions have some arguments and it receives data from the calling
function. Similarly, it returns a value to the calling function. The calling function receives
data from the called function. So, it is two-way data communication between calling and
called functions.

#include <stdio.h>
int checkPrimeNumber(int n);

int main()
{
int n, flag;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the checkPrimeNumber() function


// the returned value is assigned to the flag variable
flag = checkPrimeNumber(n);

if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);

return 0;
}
// int is returned from the function
int checkPrimeNumber(int n)
{
int i;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
return 1;
}

return 0;
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page87


C Programming for Problem Solving I/II Semester Common to all branches

The input from the user is passed to the checkPrimeNumber() function.


The checkPrimeNumber() function checks whether the passed argument is prime or not.
If the passed argument is a prime number, the function returns 0. If the passed argument
is a non-prime number, the function returns 1. The return value is assigned to
the flag variable.
Depending on whether flag is 0 or 1, an appropriate message is printed from
the main() function.

4.)In this category, the functions has no arguments and it doesn’t receive any data from
the calling function, but it returns a value to the calling function. The calling function
receives data from the called function. So, it is one way data communication between
calling and called functions.

#include <stdio.h>
int getInteger();
int main()
{
int n, i, flag = 0;
n = getInteger(); // no argument is passed
for(i=2; i<=n/2; ++i)
{
if(n%i==0){
flag = 1;
break;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}

int getInteger() // returns integer entered by the user


{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
return n;
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page88


C Programming for Problem Solving I/II Semester Common to all branches

The empty parentheses in the n = getInteger(); statement indicates that no argument is


passed to the function. And, the value returned from the function is assigned to n.

Recursion: A function that calls itself is known as a recursive function. And, this technique
is known as recursion.

void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}

The recursion continues until some condition is met to prevent it.


To prevent infinite recursion, if...else statement (or similar approach) can be used where
one branch makes the recursive call, and other doesn’t

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page89


C Programming for Problem Solving I/II Semester Common to all branches

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);

int main() {
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}

int sum(int n) {
if (n != 0)
// sum() function calls itself with n-1 as argument.
return n + sum(n-1);
else
return n;

Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed
to the sum() function. This process continues until n is equal to 0.
When n is equal to 0, the if condition fails and the else part is executed returning the sum
of integers ultimately to the main() function.

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page90


C Programming for Problem Solving I/II Semester Common to all branches

/* Write a Recursive Function to Compute Factorial of a Number */


# include <stdio.h>
main()
{
int n;
printf("Enter the Value of n...\n");
scanf("%d",&n);
printf("N= %d\n",n);
printf(" %d != %d\n",n,fact(n));
}
int fact(int n)
{
if( n== 0) return 1;
else
return ( n * fact(n-1));
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page91


C Programming for Problem Solving I/II Semester Common to all branches

/* Write a Recursive Function to compute Power of a Number */

# include <stdio.h>

float power(float y , int m)


{
if( m== 0) return 1;
else if ( m > 0 ) return( y* power(y,--m));
else return( (1/y) * power(y,++m));
}

int main()
{
int n;
float x,k;
printf("Enter the Base(Float) & Power(Integer) \n");
scanf("%f%d",&x,&n);
k=power(x,n);
printf("%f Power %d = %f\n",x,n,k);
}

Implement the Following Functions


a) To Read an Array of N elements
b) To Display an Array of N elements
c) To Sort the Array Elements using Bubble Sort
d) To conduct binary Search for the given key element
Display With Suitable headings in Main Program For Sorted & Unsorted Array
#include<stdio.h>

void Read_Array(int a[10], int);


void Print_Array(int a[10], int);
void Bubble_Sort(int a[10],int);
int Binary_Search(int a[10],int low , int high , int key );

void main()
{
int a[10],n;
clrscr();
printf("Enter the Number of Lements in the Array....\n");
scanf("%d",&n);
Read_Array(a,n);
printf("Unsorted Array Elements are....\n");
Print_Array(a,n);
Bubble_Sort(a,n);
printf("Sorted Array Elements are....\n");
Print_Array(a,n);
printf("Enter the Key Element to be Searched......\n");

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page92


C Programming for Problem Solving I/II Semester Common to all branches

scanf("%d",&key);
k=Binary_Search(a,1,n,key);
if(k== -1)
printf("Element %d Not Found in the Search.....\n",key);
else
printf("Element %d found at Position %d\n",key,k);
}

void Read_Array(int a[10], int n)


{ int i;
printf("Enter %d Elements to Array....\n",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
}
void Print_Array(int a[10], int n)
{ int i;
for(i=1;i<=n;i++)
printf("%d\n",a[i]);
}
void Bubble_Sort(int a[10],int n)
{ int i,j,temp;
for(i=1;i<=n-1;i++)
{
for(j=1;j<=n-i;j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
int Binary_Search(int a[10],int low,int high ,int key )
{
int mid;
while(low<=high)
{
mid =(low + high)/2;
if(a[mid] == key ) return mid;
else if( key > a[mid] ) low = mid +1;
else
high = mid - 1;
}
return -1;
}

Prof.Prasanna Kumar K R, Dept of CSE, SIT Tumakuru Page93

You might also like