0% found this document useful (0 votes)
10 views30 pages

Unit-Ii Psc-Ug

The document provides an overview of the C programming language, including its structure, characteristics, advantages, and disadvantages. It covers essential components such as data types, operators, control statements, and the compilation process for C programs. Additionally, it discusses the structure of a C program, including sections like documentation, link, definition, and the main function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views30 pages

Unit-Ii Psc-Ug

The document provides an overview of the C programming language, including its structure, characteristics, advantages, and disadvantages. It covers essential components such as data types, operators, control statements, and the compilation process for C programs. Additionally, it discusses the structure of a C program, including sections like documentation, link, definition, and the main function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Problem Solving in C

UNIT II
Introduction to C: Introduction – Structure of C Program –
Writing the first C Program –File used in C Program –
Compiling and Executing C Programs – Using Comments –
Keywords – Identifiers – Basic Data Types in C – Variables –
Constants – I/O Statements in C- Operators in C-
Programming Examples.
Decision Control and Looping Statements: Introduction to
Decision Control Statements– Conditional Branching
Statements – Iterative Statements – Nested Loops – Break
and Continue Statement – Goto Statement
Introduction: C language is a programming language used to write
C Programs.
Characteristics of C language:
 C is a programming language was developed in 1972 by
Dennis Ritchie at bell laboratories of AT&T (American
Telephone & Telegraph), located in U.S.A.
 It was developed to overcome the problems of previous
languages such as B, BCPL etc.

 This language
was developed
during the period when UNIX operating system is developed.
Many features that are required to write system programs are
added to C language.
 C is called middle-level language because it combines the
advantages of a machine level language and high-level
languages.
 C language can be used to write System programs as well as
Application Programs.
Advantages of C Language:
1. Stable language: C is 35 years old language and it is not
revised since last 20 years.
2. Modular language: Large programs can be divided into smaller
functions to reduce complexity.
3. Portable language: Programs written for one computer can be
executed on other computer.
Krishnaveni Degree College :: Narasaraopet Page No. : 1
Problem Solving in C
UNIT II
4. Concise language: There are only 32 keywords in C.
5. Extend itself: C language has the ability to extend itself.
6. Rich in operators: C language supports a rich set of built-
in operators.
Disadvantages of C Language
1. Case sensitive: It is a case sensitive language which makes
difficult while programming.
2. Less library functions: There is no enough library functions so
programmer has to develop functions.
3. Doesn’t support OOP’s: C does not have concept of OOP’s,
that’s why C++ is developed.
4. No Strict type checking: There is no strict type checking.
Applications:
1. C programming language can be used to design Operating
System.
2. C programming language can be used to design the compilers.
3. To Develop computer and mobile games.
4. MySQL, again being an open-source project, used in Database
Management Systems was written in C/C++.
5. Adobe Photoshop, one of the most popularly used photo editors
since olden times, was created with the help of C.

Structure of a C program: C program may contain one or more


functions out of which main function is compulsory function. Main
function may contain declarative statements and executable
statements. The structure of C program may contain one or more
sections as shown in figure below.

Krishnaveni Degree College :: Narasaraopet Page No. : 2


Problem Solving in C
UNIT II

Documentation section: The documentation section consists of a set


of comment lines giving the name of the program, purpose of the
program, name of the author and other details. Anything written
between /*…. */ is treated as a comment.
Ex: /* C Program to add two numbers */
Link section: The link section is used to link functions from the
system library to the program. Any statement started with #include
is an link statement.
Ex: #include<stdio.h>
Definition section: The definition section can be used to define
symbolic constants. Any statement started with # define is a define
statement.
Ex: #define PI 3.1415
Global declaration section: There are some variables that are used in
more than one function. Such variables are called global variables
and are declared in the global declaration section that is outside of
all the functions.
main() function section: Every C program must have one main
function section. This section contains two parts. They are
1. Declaration part and
2. Executable part
Declaration part: The declaration part declares all the variables used
in the executable part.

Krishnaveni Degree College :: Narasaraopet Page No. : 3


Problem Solving in C
UNIT II
Executable part: There is at least one statement in the executable
part. These two parts must appear between the opening and closing
braces. The program execution begins at the opening brace and
ends at the closing brace. The closing brace of the main function is
the logical end of the program. All statements in the declaration and
executable part end with a semicolon.
Subprogram section: If the program is a multi-function program then
the subprogram section contains all the user-defined functions that
are called in the main() function. User-defined functions are
generally placed immediately after the main() function, although
they may appear in any order.
All section, except the main () function section may be absent when
they are not required.

Writing the first C Program : Let us write simple C program to


add two numbers.
/* C Program to add two numbers */ -- Documentation Section
#include<stdio.h> -- Link Section
void main()
{
float a, b, sum; -- Declaration Statement
printf(“Enter any two numbers: “); main
function
scanf(“%f%f”,&a,&b);
sum=a+b; --Executable Statements
printf(“Sum = %f\n”, sum);
}

File used in C Program: A C program uses four types of files as


follows:

Figure: Files in c
Source Code File: This file includes the source code of the program.
The extension for these kind of files are '.c'. It defines the main and
many more functions written in C. main() is the starting point of the
program. It may also contain other source code files.

Krishnaveni Degree College :: Narasaraopet Page No. : 4


Problem Solving in C
UNIT II
Header Files: They have an extension '.h'. They contain the C
function declarations and macro definitions that are shared between
various source files. Standard header files used in C are
i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.
The header files are added at the start of the source code so that
they can be used by more than one function of the same file.
Object files: They are the files that are generated by the compiler
after the source code file is compiled. These files generally contain
the binary code of the function definitions. The object file is used by
the linker for producing an executable file for combining the object
files together. It has a '.o' extension.
Executable file: This file is generated by the linker. Various object
files are linked by the linker for producing a binary file which will be
executed directly.
They have an '.exe' extension.

Compiling and Executing C Programs: C programs are written in


high level language which is similar to English and mathematics with
certain syntax. But, computer cannot understand the high level
language. It can understand only low level language. So, the
program written in high level language needs to be converted into
low level language to make it understandable for the computer. This
conversion is performed using Compiler. Compiler is a program that
converts high level language instructions into low level language
instructions. Generally, compiler performs two things, first it verifies
the program errors, if errors are found, it returns list of errors
otherwise it converts the complete code into low level language.
To create and execute C programs in Windows Operating
System, we need to install Turbo C software. When we execute a C
program it undergoes with following process as shown below.

Krishnaveni Degree College :: Narasaraopet Page No. : 5


Problem Solving in C
UNIT II

The file which contains c program instructions in high level


language is said to be source code. Every c program source file is
saved with .c extension, for example Sample.c. Whenever we press
Alt + F9 the source file is submitted to the compiler. Compiler
checks for the errors, if there are any errors, it returns list of errors,
otherwise generates object code in a file with name Sample.obj and
submit it to the linker. Linker combines the code from specified
header file into object file and generates executable file as
Sample.exe. With this compilation process completes.
Now, we need to Run the executable file (Sample.exe). To run a
program we press Ctrl + F9. When we press Ctrl + F9 the executable
file is submitted to the CPU. Then CPU performs the task according
to the instructions written in that program and displays the result on
the UserScreen. Then we press Alt + F5 to open UserScreen and
check the result of the program.

Using Comments: Comments are used for program documentation


which helps the reader to understand the code. The compiler ignores
these comments when it translates the program into executable
code.
C language uses two different formats of comment
1. Block comment
2. Line comment
Block comment: A block comment is used when the comment will
span several lines.
Example:
/*This is a block comment
that covers two lines*/
Line comment: The line comment uses two slashes (//).Programmers
generally use this format for short comments.
Example:
Krishnaveni Degree College :: Narasaraopet Page No. : 6
Problem Solving in C
UNIT II
//This is a single line comment

Steps in learning a programming language: Any programming


language can be easily learned by following the diagram below.

C Character Set: The C character set is the set of characters used in


the C language. The characters in C are grouped into the
following categories. They are
1. Alphabets
2. Digits
3. Special Characters
4. White Spaces
These characters can be combined to form various tokens of the
language which are the building blocks to form a basic C program.
Letters:
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits:
0123456789
Special Characters:
, < > . _ ( ) ; $ :
% [ ] # ? ' & { } "
^ ! * / | - \ ~ +
White space Characters:
blank space, new line, horizontal tab, carriage return and form
feed

C Tokens: The smallest individual unit in a c program is known as a


token. C tokens can be classified as follows:

Krishnaveni Degree College :: Narasaraopet Page No. : 7


Problem Solving in C
UNIT II
Keywords: Keywords are the reserved words that have a
predefined meaning. Keywords cannot be used as an identifiers. As
C is a case sensitive language, all keywords must be written in
lowercase. Here is a list of all keywords allowed in ANSI C.
Auto Break Case char continu Const default do
e
double Else Enum extern float For goto if
Int Long Regist return short Signed sizeof static
er
struct Switch Typed union unsigne volatil while
Void
ef d e

Special Symbols: Special symbols in C having some special


meaning. Some of the special symbols are [] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start
and end of a block of code containing more than one executable
statement.
Parentheses(): These special symbols are used to indicate function
calls and function parameters.
Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.

Identifiers: Identifier refers to the name of variables, functions,


arrays etc. Identifier must be unique. Rules for writing an identifier
1. A valid identifier can have letters (both uppercase and
lowercase letters), digits and underscores.
2. The first letter of an identifier should be either a letter or an
underscore. However, it is discouraged to start an identifier
name with an underscore.
3. There is no rule on length of an identifier. However, the first 8
characters of identifiers are discriminated by the compiler.
4. Keywords cannot be used as an identifiers.
5. No spaces or any another special symbol can be used in an
identifier.

Constants: A constant is a value whose value cannot be altered in a


program. For example: 1, 2.5 etc.
Below are the different types of constants used in C.

Krishnaveni Degree College :: Narasaraopet Page No. : 8


Problem Solving in C
UNIT II

Integer constants: An integer constant is a numeric constant without


any fractional or exponential part. There are three types of integer
constants in C. They are
1. decimal constant(base 10)
2. octal constant(base 8)
3. hexadecimal constant(base 16)
In C programming, octal constant starts with a 0 and hexadecimal
constant starts with a 0x.
Ex:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
Floating-point constants: A floating point constant is a numeric
constant that has either a fractional form or an exponent form. For
example:
-2.0
0.0000234
-0.22E-5
Note: E-5 = 10-5
Character constants: A character constant is a character enclosed
between single quotes.
Ex: 'a', 'l', '&', '>'
String constants: String constants are the constants which are
enclosed in a pair of double-quote marks. For example:
Ex: "good" , “567”,""

Basic data types: Every variable in C has a data type. Data types
specify the amount of memory to be allocated and type of value
that can be stored in a variable. C language is rich in its data types
and they are classified into two data types. They are
1. Primitive data types or Basic data types or Primary data types
2. Non-primitive data types or Derived data types
The classification of data types in C are shown in figure below.

Krishnaveni Degree College :: Narasaraopet Page No. : 9


Problem Solving in C
UNIT II

Primitive Data Types:-The primitive data types are also commonly


referred to as basic data types. Primitive data types are classified
into three types. They are
1. Integer data types
2. Floatingpoint data types
3. Character data types
Integer data types: Integer data types are used to store whole
numbers that have no fractional part. Integer data types are
classified into three types. They are
1. short int
2. int
3. long int
short int: short int data type is a 16-bit integer number. The range
accepted by short int is -32,768 to 32,767 i.e. -2 15 to 215-1.
Ex: short int s = 10000;
short int r = -20000
int: int data type is a 16-bit integer number The range accepted by
short int is -32,768 to 32,767 i.e. -2 15 to 215-1. int is generally used
as the default data type for integer values.
Ex: int a = 100000, int b = -200000
long: Long data type is a 32-bit integer number. The range
accepted by long is -2,147,483,648 to 2,147,483,647 i.e. -2 31 to 231
-1. This type is used when a wider range than int is needed.
Ex: long a = 32867, long b = -42999

Krishnaveni Degree College :: Narasaraopet Page No. : 10


Problem Solving in C
UNIT II
Floating point data types: Floating point data types are used to store
numbers that have a fractional part. Floating point data types are
classified into two types. They are
1. float
2. double
3. long double
float: float data type is a 32-bit floating point number. float uses 6
bits of precision , i.e. no of bits after the decimal point is six.
Ex: float f1 = 234.5;
double: double data type is a 64-bit floating point number. float
uses 15 bits of precision.
Ex: double d1 = 123.4;
Long double: double data type is a 80-bit floating point number.
float uses 19 bits of precision.
Ex: long double d1 = 123.4;
Character data type: Character data type is a 8-bit integer number.
It is capable of storing a single character. The range accepted by
char is -128 to 127 i.e. -27 to 27 -1.
Ex: char ch = ‘a’;
Non-Primitive Data Types:- The non-primitive data types are also
commonly referred as derived data types. Non-Primitive data types
are classified into three types. They are
1. Arrays
2. Structures
3. Pointers
4. Enumerated data type
Arrays: An array is a group of similar data items referred to by a
common name.
Structures: An structure is a group of dissimilar data items referred
to by a common name. It acts as an user defined data type.
Pointer: Pointer is a variable which stores the address of another
variable.
Enumerated data type: Enumerated data type is a user defined data
type which assigns numbers to list of fruits etc.
Modifiers: A type modifier alters the meaning of the base type to
more precisely fit a specific need. The list of modifiers is shown here:
1. signed
2. unsigned
3. long
4. short
The list of modifiers along with the data types is shown here:
Type Storage Value range
size
Krishnaveni Degree College :: Narasaraopet Page No. : 11
Problem Solving in C
UNIT II
Char 1 byte -128 to 127 -27 to 27 -1
unsigned 1 byte 0 to 255 0 to 28 -1
char
signed char 1 byte -128 to 127 -27 to 27 -1
Int 2 bytes -32,768 to 32,767 -215 to 215 -1
unsigned int 2 bytes 0 to 65,535 0 to 216 -1
Short 2 bytes -32,768 to 32,767 -215 to 215 -1
unsigned 2 bytes 0 to 65,535 0 to 216 -1
short
Long 4 bytes -2,147,483,648 to -231 to 231 -1
2,147,483,647
unsigned 4 bytes 0 to 4,294,967,295 0 to 232 -1
long
Float 4 byte 1.2E-38 to 3.4E+38 6 Decimal
places
Double 8 byte 2.3E-308 to 1.7E+308 15 Decimal
places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 Decimal
places

Variables: A variable is a value whose value can be altered in a


program. Thus a variable is nothing but a name given to a storage
area which stores the value and our programs can manipulate this
value when required.
Defining a Variable in C: A variable definition tells the compiler the
name of the variable, how much memory to be allocated for the
variable. A variable definition specifies a data type and contains a
list of one or more variables of that data type.
type variable_list;
Ex: int i;
float a, b, c;

I/O Statements in C : The most fundamental operation in a C


program is to accept input values from a standard input device and
output the data produced by the program to a standard output
device. scanf function that reads data from the keyboard and stores
in the specified variable. printf function is used to send results to a
output device. printf and scanf are functions used in C to carry out
the input–output operations. These functions are collectively defined
in Standard Input/Output Library. Thus a program that uses standard

Krishnaveni Degree College :: Narasaraopet Page No. : 12


Problem Solving in C
UNIT II
input/output functions must contain the following statement at the
beginning of the program:
#include <stdio.h>
scanf(): The scanf()function is used to read formatted data from the
keyboard. The syntax of the scanf() function can be given as,
scanf ("control string", arg1, arg2, arg3 ...argn);
The control string specifies the type and format of the data that has
to be obtained from the keyboard and stored in the memory
locations pointed by the arguments, arg1, arg2, ...,argn. The
prototype of the control string can be given as,
% type
The type specifiers for scanf function are given in Table below. Type
specifiers are
Type Qualifying Input
%c For single characters
%d, %i For integer values
%e,%E,%f,%g, For floating point numbers
%G
%o For octal numbers
%s For a sequence of (string of) characters
%u For unsigned integer values
%x,%X For hexadecimal values
scanf function is used to store values in memory locations
associated with variables. For this, the function should have the
address of the variables. The address of the variable is denoted by
an & sign followed by the name of the variable.
int num;
scanf(" %d ", &num);
The scanf function reads integer number and stores into the address
or the memory location pointed by num.
Note: In case of reading strings, we do not use the & sign in the
scanf function.
printf(): The printf function is used to display information required by
the user and also prints the values of the variables. Its syntax can be
given as:
printf ("control string", arg1,arg2,arg3,...,argn);
After the control string, the function can have as many arguments as
specified in the control string.
% [width][.precision] type
Each control string must begin with a % sign. width is an optional
argument which specifies the minimum number of positions that the
output characters will occupy. If the number of output characters is
smaller than the specified width,then the output would be right
Krishnaveni Degree College :: Narasaraopet Page No. : 13
Problem Solving in C
UNIT II
justified with blank spaces to the left. However, if the number of
characters is greater than the specified width, then all the characters
would be printed. precision is an optional argument which specifies
the number of digits to print after the decimal point or the number of
characters to print from a string. The type specifiers for printf
function are same as given in Table above for scanf .
Ex: int x =700
printf ("X = %d”, x);

Operators in C: Depending on the operation performed by the


operator, the operators can be classified into seven categories. They
are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment/Decrement Operators
6. Bitwise Operators
7. Conditional Operator
8. Special operators
Arithmetic Operators: Arithmetic operators are the operators which
take numerical values as the input and produces numerical values as
the output. The following table lists the arithmetic operators:
Operator Purpose Example Result
+ Addition 12 + 4.9 16.9
– Subtraction(unary 12 - 4.9 7.1
minus)
* Multiplication 12 * 4.9 58.8
/ Division 12 / 4.9 2.45
% Modulus 12 % 5 2
The modulus operator, %, returns the remainder of a division
operation. It can be applied to only integer types.
Relational Operators: The relational operators determine the
relationship that one operand has to the other. Relational operators
are the operators which take numerical values as the input and
produces Boolean values as the output. The following table lists the
relational operators:
Operator Purpose Exampl Result
e
== Equal to 4 == 1 0(false)
!= Not equal to 4 != 1 1(true)
> Greater than 4>1 1(true)

Krishnaveni Degree College :: Narasaraopet Page No. : 14


Problem Solving in C
UNIT II
< Less than 4<1 0(false)
>= Greater than or equal 4 >= 1 1(true)
to
<= Less than or equal to 4 <= 1 0(false)

Logical Operators: Logical operators are the operators which take


Boolean values as the input and produces Boolean values as the
output. The following table lists the logical operators:
Operator Purpose Example Result
&& Logical AND 0 && 0 0(false)
0 && 1 0(false)
1 && 0 0(false)
1 && 1 1(true)
|| Logical OR 0 || 0 0(false)
0 || 1 1(true)
1 || 0 1(true)
1 || 1 1(true)
! Logical unary ! 0 1(true)
NOT !1 0(false)
Assignment Operators: Assignment operators are the operators
which assigns the value on R.H.S to the variable on L.H.S. The
assignment operator can combined with arithmetic operators to
form short hand assignment operators. The following table lists the
assignment operators:
Operator Purpose Example Result
= Assignment a=10 10
+= Addition assignment Take a=10; a+=10 20
-= Subtraction Take a=10; a-=10 0
assignment
*= Multiplication Take a=10; a*=10 100
assignment
/= Division assignment Take a=10; a/=10 1
%= Modulus assignment Take a=10; a%=10 0

Increment/Decrement Operators:- C allows two very useful operators


not generally found in other languages. These are the increment and
decrement operators. ++ is an increment operator which adds 1 to
the operand. -- is an decrement operator which subtracts 1 from the
operand. Depending on where the increment and decrement
operator is placed i.e. before the operand or after the operand these
operators are classified into two types they are
1. Postfix Increment/Decrement Operators

Krishnaveni Degree College :: Narasaraopet Page No. : 15


Problem Solving in C
UNIT II
2. Prefix Increment/Decrement Operators
operato Purpose Exampl Result
r e
++ Prefix b=++a Assume a=10
After executing
a = 11, b=11
++ Postfix b=a++ Assume a=10
After executing
a = 11, b=10
-- Prefix b=--a Assume a=10
After executing
a = 9, b=9
-- Postfix b=a-- Assume a=10
After executing
a = 9, b=10

Bitwise Operators: Bitwise operators operate on individual bits of


integer (int and long) values. The following table lists the Bitwise
operators:
Asuume a = 0011 and b = 0110
operato Purpose Example Resul
r t
~ Ones Complement ~0011 1100
& Bitwise AND 0011 & 0110 0010
| Bitwise OR 0011 | 0110 0111
^ Bitwise exclusive OR 0011 ^ 0110 0101
>> Shift right 0011 >> 1 0001
<< Shift left 0011 << 1 0110

The Conditional Operator: C includes a special ternary (three-way)


operator that can replace certain types of if-then-else statements.
Conditional operator (?:) is the ternary operator and its general form
is
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean
value. If expression1 is true, then expression2 is evaluated;
otherwise, expression3 is evaluated.
Ex: max=a>b?a:b;
Special Operator: C has some special operators. Comonly used
special operators are comma operator, sizeof() operator
The comma operator: The comma operator (,) works almost like the
semicolon ; that separates one C statement from another. Comma

Krishnaveni Degree College :: Narasaraopet Page No. : 16


Problem Solving in C
UNIT II
operator separates any kind of C statment from another statement.
The comma-separated expressions are evaluated from left to right
and the value of the whole comma-separated sequence is the value
of the rightmost expression in the sequence.
Ex: res=(x=2,y=3,x+y); Note: res=5 which is obtained by computing
x+y.
t=x,x=y,y=t; Note: Results in swapping of two numbers x,
y.
sizeof() operator: sizeof is a unary operator that returns the length,
in bytes, of the variable or data type specified
Ex: sizeof(int);
sizeof(i);

Programming Examples:
1. Write a C Program to calculate simple interest.
/* C Program to calculate simple interest */
#include<stdio.h>
void main() Step 1: Start
{ Step 2: Read P, T, R
float p,t,r,si;
Step 3: SI = (P * T * R)
clrscr();
printf("Enter principal, rate and /100
time : "); Step 4: Print SI
scanf("%f%f%f",&p,&t,&r); Step 5: End
si=p*t*r/100;
printf("Simple Interest =%.2f\n",si);
getch();
}

2. Write a C Program to convert centigrade temperature to


fahrenhiet temperature
/* C Program to convert centigrade temp to fahrenhiet temp */
#include<stdio.h>
void main() Step 1: Start
{ Step 2: Read cent
float cent,fahr; Step 3: fahr = 1.8 * cent
clrscr(); + 32
printf("Enter the cent temp : Step 4: Print fahr ");
scanf("%f ",&cent); Step 5: End
fahr=1.8 * cent + 32.0;
printf("Fahr temp =%.2f\n",fahr);
getch();
}
Krishnaveni Degree College :: Narasaraopet Page No. : 17
Problem Solving in C
UNIT II
3. Write a C program to find area of the triangle when height
and base are given.
/* C Program to find area of the triangle when height and base are
given */
#include<stdio.h>
void main()
{ Step 1: Start
float area, b, h; Step 2: Read b, h
clrscr(); Step 3: a = (b * h) /
printf("Enter base and height of the 2.0
triangle: "); Step 5: Print a
scanf("%f%f",&b,&h); Step 6: End
area=1/2.0*b*h;
printf("Area of the triangle = %.2f \n", area);
getch();
}
4. Write a C program to find area of the triangle when three
sides are given.

/* C Program to find area of the triangle when three sides are given
*/
#include<stdio.h> Step 1: Start
#include<math.h> Step 2: Read a, b, c
void main() Step 3: s = (a + b + c) / 2
{ Step 4: area=sqrt(s*(s-a)*(s-
float area, a, b, c, s; b)*(s-c))
clrscr(); Step 5: Print area
printf("Enter three sides of the Step 6: End
triangle: ");
scanf("%f%f%f",&a,&b,&c);
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of the triangle = %.2f \n", area);
getch();
}

5. Write a C program to find area of the circle when radius is


given.
/* C Program to find area of the circle when radius is given */
#include<stdio.h>
Step 1: Start
#define PI 3.1415
Step 2: pi = 3.1415
void main()
Step 3: Read r
{
Step 4: area= pi * r
Krishnaveni Degree College :: Narasaraopet * r; Page No. : 18
Step 5: Print area
Step 6: End
Problem Solving in C
UNIT II
float area, r;
clrscr();
printf("Enter radius of the triangle: ");
scanf("%f ",&r);
area=PI * r * r;
printf("Area of the circle = %.2f \n", area);
getch();
}

Introduction to Decision Control Statements: Control


statements are used to change the flow of execution of a program.
C’s control statements can be put into the following categories. They
are
1. Selection statements
2. Iteration statements and
3. Jump statements
Selection statements allow the program to choose different paths of
execution based upon the outcome of an expression. Iteration
statements enable program execution to repeat one or more
statements until the condition is satisfied. Jump statements allow the
program to jump to the required statement.

Conditional Branching Statements: Branching statements allow


the program to choose different paths of execution based upon the
outcome of an expression or the value of a variable. There are
various types of if statement in C. They are
a. if statement
b. if-else statement
c. nested if statement
d. if-else-if ladder
e. switch statement
Simple if Statement: The simple if statement initially tests the
condition. If the condition is true it executes the statement-block and
moves to the next statement. If the condition is false it skips the
statement-block and directly moves to the next statement.
Syntax: Flowchart:
if(condition)

{
statement-block;
}
next-statement;

Krishnaveni Degree College :: Narasaraopet Page No. : 19


Problem Solving in C
UNIT II
Example: Write a C program to find the absolute value of the
given number
/* C Program to find the absolute value of the given number using
simple if */
#include<stdio.h>
void main() Algorithm: Absolute
{ Step 1: Start
float num,abs; Step 2: Read num
printf("Enter any number: "); Step 3: abs=num
Step 4: if(num<0)
scanf("%f",&num);
abs = num; abs =-1*num
if(num < 0) Step 4: Print abs
abs = -1 *num; Step 5: End
printf("Absolute value = %.2f \n",abs);
}
if-else Statement: The if-else statement is an extension of simple if
statement. If-else statement initially tests the condition. If the
condition is true it executes the true-statement-block and moves to
the next statement. If the condition is
false it executes the false-statement-block and moves to the next
statement. In any case , either true-statement-block or false-
statement-block is executed and moves to the next statement.
Syntax: Flowchart:
if(condition)
{
true-statement-block;
}
else
{
false-statement-block;
}
next-statement;
Example: Write a C program
to find the absolute value of the given number
/* C Program to find the absolute value of the given number using
if-else*/
#include<stdio.h>
void main()
{ Algorithm: Absolute
float num,abs; Step 1: Start
printf("Enter any number: "); Step 2: Read num
Step 3: scanf("%f",&num);
if(num<0)
if(num < 0) abs =-1*num
else
Krishnaveni Degree College :: Narasaraopet Page abs=num
No. : 20
Step 4: Print abs
Step 5: End
Problem Solving in C
UNIT II
abs = -1 *num;
else
abs = num;
printf("Absolute value = %.2f \n",abs);
}
Example: Write a C program to check whether the given
number is even or odd.
/* Program to check whether the given number is even or odd */
#include<stdio.h>
Algorithm: EvenOdd
void main()
Step 1: Start
{
Step 2: Read num
int num;
Step 3: if(num %2 == 0)
printf("Enter any integer number: ");
print("even
scanf("%d",&num);
number)
if(num %2 == 0)
else
printf("%d is an even number\n",num);
print("odd
else
number)
printf("%d is an odd number\n",num);
Step 5: End
}
Nested – if: When one if statement is nested in another if statement
then it is called as nested if statement.
Syntax: Flowchart:
if(condition1)

{
if(condition2)
{
statement1-block;
}
else
{
statement2-block;
}
}
else
{
statement3-block;
}
next-statement;
Example: Write a
C Program to check
whether given year is
leap year or not
Krishnaveni Degree College :: Narasaraopet Page No. : 21
Problem Solving in C
UNIT II
/* C Program to find that entered year is leap year or not */
#include<stdio.h> Algorithm: LeapYear
#include<conio.h> Step 1: Start
void main() Step 2: Read year
{ Step 3: if(year%4 == 0)
int year; if( year%100 ==
clrscr(); 0)
printf("Enter any year: "); if (year%400 ==
scanf("%d",&year); 0)
if(year%4 == 0) print("leap
if( year%100 == 0) year”)
if (year%400 == 0) else
printf("%d is a leap year\n", year); print("not leap
else year”)
printf("%d is not a leap year\n", year); else
else print("leap year”)
printf("%d is a leap year\n", year ); else
else
printf("%d is not a leap year\n", year);
getch();
}
else-if ladder : When one if statement is added in the else part of
another if statement then it is called as else – if ladder statement.
Syntax: Flowchart:
if(condition1)
statement1-block;
else
if(condition2)
statement2-block;
else
if(condition3)
statement3-block;
else
statement4-block;
next-statement;
Example: Write a C Program
to find largest among 3 numbers.
/* C Program to find largest among 3 numbers */
#include<stdio.h> Algorithm: Maximum
#include<conio.h> Step 1: Start
void main() Step 2: Read a, b, c
{ Step 3: if((a>b)&&(a>c))
float a,b,c; print(a,"is maximum”)
Krishnaveni Degree College :: Narasaraopetelse Page No. : 22
if(b>c)
print(b,"is maximum”)
else
Problem Solving in C
UNIT II
clrscr();
printf("Enter any three numbers: ");
scanf("%f%f%f",&a,&b,&c);
if((a>b)&&(a>c))
printf("%.2f is largest", a);
else
if(b>c)
printf("%.2f is largest", b);
else
printf("%.2f is largest", c);
getch();
}
Multiway selection: switch: The switch statement is a multiway
branch statement. It provides an easy way to select one of the
option among several options. It often provides a better alternative
than a large series of if-else-if statements. Here is the general form
of a switch statement:
Syntax: Flowchart:
switch (expression)
{
case value1: statement1-
block;
break;
case value2: statement2-
block;
break;
...
case valueN: statementN-
block;
break;
default: defaultstatement-
block;
}
The expression must be of type int, or char. Each case value
must be a unique constant, not a variable. Duplicate case values are
not allowed.
The switch statement works like this: The value of the
expression is compared with each of the case values in the case
statements. If a match is found, the code sequence following that
case statement is executed. If none of the constants matches the
value of the expression, then the default statement is executed.
However, the default statement is optional. If no case matches and
no default is present, then no further action is taken. The break
Krishnaveni Degree College :: Narasaraopet Page No. : 23
Problem Solving in C
UNIT II
statement is used inside the switch to terminate a statement
sequence. When a break statement is encountered, execution
branches to the first line of code that follows the entire switch
statement. This has the effect of “jumping out” of the switch.
Example: Write a C program to display name of the day using
switch statement. Algorithm: DayName
/* C Program to display name of the day */ Step 1: Start
Step 2: Read dayno
#include<stdio.h> Step 3: switch(dayno)
#include<conio.h> case 1: Print(“Monday”)
case 2:
void main() Print(“Tuesday”)
{ case 3:
int dayno; Print(“Wednesday”)
case 4:
clrscr(); Print(“Thursday”)
printf("Enter the day number: "); case 5: Print(“Friday”)
case 6:
scanf("%d",&dayno); Print(“Saturday”)
switch(dayno)
{
case 1: printf("%d day in the week is Monday\n",dayno);
break;
case 2: printf("%d day in the week is Tuesday\n",dayno);
break;
case 3: printf("%d day in the week is Wednesday\n",dayno);
break;
case 4: printf("%d day in the week is Thursday\n",dayno);
break;
case 5: printf("%d day in the week is Friday\n",dayno);
break;
case 6: printf("%d day in the week is Saturday\n",dayno);
break;
case 7: printf("%d day in the week is Sunday\n",dayno);
break;
default: printf("%d is a wrong day number\n",dayno);
}
getch();
}

Iterative Statements: Iterative Statement repeats set of


instruction until the condition for termination is met. These
statements appear in the source code only once, but it execute
many times. Such kinds of statements are also called as loops.
Iteration Statement in C are mainly of three types
1. 'while' Statement
2. 'do while' Statement
Krishnaveni Degree College :: Narasaraopet Page No. : 24
Problem Solving in C
UNIT II
3. 'for' Statement
while Statement: The while loop is an entry controlled loop. It tests
the condition before executing the body of the loop. The condition
can be any relational or logical expression. The body of the loop will
be executed as long as the conditional expression is true. When
condition becomes false, control passes to the next line of code
immediately following the loop. The curly braces are unnecessary if
only a single statement is being repeated. The general form of the
while statement is
Syntax: Flowchart:
while(condition)

// body of loop

}
Next-statement

Example: Write a C program to display sum of natural numbers


/* C Program to display sum of natural numbers */
#include<stdio.h> Algorithm: Natural
#include<conio.h> Step 1: Start
void main() Step 2: Read n
{ Step 3: i=1
int i,n,sum; Step 4: sum=0
clrscr(); Step 5: while(i<=n)
printf("Enter how many natural numbers: "); {
scanf("%d",&n); print(i);
i=1; sum=sum+i;
sum=0; i = i + 1;
while(i<=n) }
{ Step 6: print(sum)
sum=sum+i; Step 7: End
i++;
}
printf("Sum of %d natural numbers is %d\n",n,sum);
getch();
}
do-while: The do-while loop is an exit controlled loop. The do-while
loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. Its general form is
Syntax: Flowchart:
Krishnaveni Degree College :: Narasaraopet Page No. : 25
Problem Solving in C
UNIT II
do
{
// body of loop
} while (condition);

Each iteration of the


do-while loop first
executes the body of the loop and then evaluates the conditional
expression. If this expression is true, the loop will repeat. Otherwise,
the loop terminates.
Example: Write a C program to find reverse of a given number
/* C Program to find reverse of a given number */
#include<stdio.h> Algorithm: Natural
#include<conio.h> Step 1: Start
void main() Step 2: Read n
{ Step 3: rev=0;
int n,rev,rem; Step 4: do
clrscr(); {
printf("Enter any integer number:"); rem = n%10;
scanf("%d",&n); rev =
rev=0; rev*10+rem;
do n=n/10;
{ }while(n>0)
rem = n%10; Step 5: print(rev)
rev = rev*10+rem; Step 6: End
n=n/10;
}while(n>0);
printf("Reverse number = %d",rev);
getch();
}
For loop: For loop executes group of statements as long as the
condition evaluates to true. For loop combines three elements i.e.
initialization statement, condition and increment or decrement
statement on the same line. Here is the general form of for
statement:
Syntax: Flowchart:
for(initialization; condition;
incrementation)
{
// body
}

Krishnaveni Degree College :: Narasaraopet Page No. : 26


Problem Solving in C
UNIT II

If only one statement is being repeated, there is no need for the


curly braces.
The for loop operates as follows. When the loop first starts, the
initialization portion of the loop is executed. Generally, this is an
expression that sets the value of the loop control variable, which
acts as a counter that controls the loop. It is important to understand
that the initialization expression is only executed once. Next,
condition is evaluated. This must be a relation or logical expression.
It usually tests the loop control variable against a target value. If this
expression is true, then the body of the loop is executed. If it is false,
the loop terminates. Next, the iteration portion of the loop is
executed. This is usually an expression that increments or
decrements the loop control variable. The loop then iterates, first
evaluating the conditional expression, then executing the body of
the loop, and then executing the iteration expression with each pass.
This process repeats until the controlling expression is false.
Example: Write a C Program to print multiplication table of
any number.
/* C Program to print multiplication table of any number */
#include<stdio.h>
#include<conio.h> Algorithm: Table
void main() Step 1: Start
{ Step 2: Read n
int i,n; Step 3: for(i=1;i<=10;i+
clrscr(); +)
printf("Enter any integer number: "); print(n, ”X”,
scanf("%d",&n); i ,“=”,n*i)
printf("%d multiplication table is asStep 4: End n);
follows\n",
for(i=1;i<=10;i++)
printf("%d X %d = %d\n",n,i,n*i);
getch();
}

Jump Statements: C supports three jump statements: break,


continue, and return. These statements transfer control of execution
to another part of the program.
break: In C, the break statement has three uses. First, as you have
seen, it terminates a statement sequence in a switch statement.
Second, it can be used to exit a loop. Third, it can be used as a
“civilized” form of goto. The last two uses are explained here.
Krishnaveni Degree College :: Narasaraopet Page No. : 27
Problem Solving in C
UNIT II
Example: Write a C Program to check whether the given
number is prime or not using break.
/* Program to check whether the given number is prime or not using
break */
#include<stdio.h>
void main()
{
int i,n,isprime=1;
printf("Enter any number: ");
scanf("%d",&n);
for(i=2;i<=n/2;i++)
if((n%i)==0)
{
isprime=0;
break;
}
if(isprime && (n!=1))
printf("%d is a prime number \n", n);
else
printf("%d is not a prime number \n", n);
}
continue: A continue statement causes control to be transferred
directly to the conditional expression that controls the loop.
Example: Write a C Program to check whether the given
number is prime or not using continue.
/* Program to check whether the number is prime or not using
continue */
#include<stdio.h>
void main()
{
int i,n,isprime=1;
printf("Enter any number: ");
scanf("%d",&n);
for(i=2;i<=n/2;i++)
{
if((n%i)!=0)
continue;
isprime=0;
}
if(isprime && (n!=1))
printf("%d is a prime number \n", n);
else
printf("%d is not a prime number \n", n);
Krishnaveni Degree College :: Narasaraopet Page No. : 28
Problem Solving in C
UNIT II
}
return: The return statement terminates the execution of a called
function and returns the control of execution to the calling function.
• Returning control from function that does not return value:
return;
• Returning control from function that returns value:
return <value>;

GOTO Statement: The goto statement is used to transfer the flow


of control to the specified label mentioned in the goto statement. It
is an unconditional jump statement. Label_name is an identifier
which specifies where the flow of control is to be jumped. The
Label_name is placed immediately before the statement and the
label_name must be followed by a colon(:). The label_name can be
placed anywhere in the program either before or after the goto
statement. If the label_name is placed after the goto statement then
it is called as forward jump and if the label_name is placed after the
goto statement then it is called as backward jump
Syntax:
goto label_name; label_name: C-
.. statement;
.. ..
label_name: C- ..
statement; goto label_name;
Forward Jump Backward Jump

/* Program to demonstrate goto statement */


#include <stdio.h>
void main()
{
int sum=0;
printf(“Enter series of +ve and -ve numbers and terminate by
using -1:\n”);
while(1)
{
read: scanf(“%d”, &num);
if(num>=0)
goto sum;
if(num==-1)
break;
if(num<0)
goto read;
sum: sum = sum+num;
Krishnaveni Degree College :: Narasaraopet Page No. : 29
Problem Solving in C
UNIT II
}
printf(“Sum of given positive numbers is %d\n”,sum);
}

Krishnaveni Degree College :: Narasaraopet Page No. : 30

You might also like