JNTUA JNTUH JNTUK_B Tech_1 1_Handwritten Notes_EEE_PSPC Programming for Problem Solving Using C_FirstRanker.com
JNTUA JNTUH JNTUK_B Tech_1 1_Handwritten Notes_EEE_PSPC Programming for Problem Solving Using C_FirstRanker.com
com
Syllabus for ECE. JNTUK w. e. f. 2019-20
I Year - I Semester L T P C
3 0 0 3
PROGRAMMING FOR PROBLEM SOLVING USING C (ES1101)
COURSE OBJECTIVES:
The objectives of Programming for Problem Solving Using C are
UNIT I
Introduction to Computers: Computer Systems, Computing Environments, Computer languages,
Creating and running Programs, Computer Numbering System, Storing Integers, Storing Real
Numbers
om
UNIT II
Bitwise Operators: Exact Size Integer Types, Logical Bitwise Operators, Shift Operators, Tips and
.F
Selection & Making Decisions: Logical Data and Operators, Two Way Selection, Multiway
w
Selection, More Standard Functions, Tips and Common Programming Errors, Key Terms,
w
UNIT III
Arrays: Concepts, Using Array in C, Array Application, Two Dimensional Arrays, Multidimensional
Arrays, Programming Example – Calculate Averages, Tips and Common Programming Errors, Key
Terms, Summary, Practice Set.
Strings: String Concepts, C String, String Input / Output Functions, Arrays of Strings, String
Manipulation Functions String/ Data Conversion, A Programming Example – Morse Code, Tips and
Common Programming Errors, Key Terms, Summary, Practice Set.
Enumerated, Structure, and Union: The Type Definition (Type def), Enumerated Types, Structure,
Unions, Programming Application, Tips and Common Programming Errors, Key Terms, Summary,
Practice Set.
www.FirstRanker.com
www.FirstRanker.com R-19 www.FirstRanker.com
Syllabus for ECE. JNTUK w. e. f. 2019-20
UNIT IV
Pointers: Interdiction, Pointers to pointers, Compatibility, L value and R value, Tips and Common
Programming Errors, Key Terms, Summary, Practice Set.
Pointer Applications: Arrays, and Pointers, Pointer Arithmetic and Arrays, Memory Allocation
Function, Array of Pointers, Programming Application, Tips and Common Programming Errors,
Key Terms, Summary, Practice Set.
Processor Commands: Processor Commands, Tips and Common Programming Errors, Key Terms,
Summary, Practice Set.
UNIT V
Text Input / Output: Files, Streams, Standard Library Input / Output Functions, Formatting Input /
Output Functions, Character Input / Output Functions, Tips and Common Programming Errors,
Key Terms, Summary, Practice Set.
Binary Input / Output: Text versus Binary Streams, Standard Library, Functions for Files,
Converting File Type, Tips and Common Programming Errors, Key Terms, Summary, Practice Set.
Functions: Designing, Structured Programs, Function in C, User Defined Functions, Inter-Function
Communication, Standard Functions, Passing Array to Functions, Passing Pointers to Functions,
Recursion, Passing an Array to Function, Tips and Common Programming Errors, Key Terms,
Summary, Practice Set.
om
COURSE OUTCOMES:
r.c
ke
selection.
irs
3) Acquire knowledge to select the best loop construct for a given problem.
.F
TEXT BOOKS:
w
REFERENCE:
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
UNIT-1
INTRODUCTION TO COMPUTERS
What is a Computer?
The word “Computer” comes from the word “compute” which means to calculate. A computer
is an electronic device, which stores and processes data to give meaningful information.
Processing is done with the help of instructions given by the user, which are also stored within
the computer.
Data refers to all the basic elements that can be produced or processed by a computer.
Data is a collection of facts and figures which has to be processed by some processing system,
(whether a human being or a machine) to be understandable.
Information: It is the processed form of data, which makes some sense and helps in reaching
aconclusion.
Characteristics of Computers
Speed
Storage
Logical decision
Super Efficiency and Automation
Accuracy
Reliability
Versatility
om
Input device
an
Central ProcessingUnit
tR
Output device
irs
.F
Input device
w
Input means putting the raw data through input device into the processing device Input Unit
w
allows us to communicate with the computer. An input unit converts the numbers, alphabet or
w
other signals into the internal binary code (will be discussed later). Keyboard, mouse, joystick,
light pen are the examples of input unit. We will discuss about the input device in details later.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Output device
The devices, through which we get the processed information or the desired result, are known as
the output devices. There are a variety of output devices which return the information given by
the user. The most popularly used output devices are Visual Display Unit (VDU) or monitor,
printers, plottersetc.
Central Processing Unit: Central Processing Unit (CPU) is the processing device of computer. It
inhere that the actual work is done. The CPU is like the `brain' of the computer. It takes information
from the input unit and memory and uses or processes it according to the instructions given. It may
put information into the memory or give results to the output unit.
om
r.c
ke
an
tR
irs
.F
ALU (Arithmetic and Logic Unit) In the ALU, calculations such as addition, multiplication etc. of
w
w
numbers is carried out. The ALU can also carry out logicaloperations like comparing two numbers to
w
see which is the larger. A modern computer can perform a single addition in nanoseconds (1 nano
second = 10-9seconds)
Control Unit: It controls the overall activities of a computer system. It getsinformation from the input
unit, sends information to the output unit or transfers information to or from the computer's memory.
It is important that everything is done in exactly the right order and at the right time, so there is an
accurate clock within the computer which is connected to the control unit.
Internal Memory / Primary Memory Ina PC, internal memory is usually contained insilicon chips. It
holds instructions and data which the computer is currently working on, and which can be accessed
by the CPU whenever required. Internalmemory needs to work very rapidly because the speed of the
CPU is very high and requires information to be readilyavailable.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
RAM (Random Access Memory) is an electronic memory which is used to storedata and instructions
from the operating system and any program you are using. RAM Storesinformation temporarily.If
the power is interrupted, even for an instant the information is lost forever. The CPU accepts
information from RAM as and when required, processes it and returns toRAM.
ROM (Read Only Memory) ROM or Read Only Memory holds sets of instructions which tell the
computer what to do. For instance, a ROM will tell the processor how to recognize which key has
been pressed and how to light up the screen. Information stored in ROM can be “read” it can notbe
erased or added to because when chip is manufactured it is made non-writable. The information
stored in ROM is not erased even if Power is switchedoff.
Disk Drives
Disk drives provide a means of storing work, or data. Floppy disks are transportable from PC to
PC and come in two sizes, 31/2” and 51/4” diameter. Hard disks are fixed inside the system unit
and have much higher storage capacities thanfloppies.
Hard disks (or fixed disks) work on the same principle as floppy disks but are fixed inside the
PC in a sealed unit. They can store a great deal more information than floppy disks and range in
capacity from 10MB to several hundred MB. Access times (i.e. the time taken to read and write
information) for hard disks are much faster than for floppy disks. Manufacturers often quote
access times as well as capacities for harddisks.
Information is stored on disk in the form of files. A file might be a program or data such as a
om
The Monitor
ke
an
The monitor provides display output from the PC. Monitors vary in screen resolution and
colours available. Monitors are available in colour and monochrome versions and in different
tR
screensizes.
irs
.F
The Keyboard
w
w
The keyboard allows you to input commands and information into the PC. The keyboard is
w
normally connected to the main unit via a 5 pin DIN type socket.
Peripherals
As well as the essential keyboard and monitor, peripheral items such as printers and mice are
often found connected to PCs.
Printer Types
Printers can be grouped by the method with which they print.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Dot-Matrix Printers
Laser Printers
Inkjet Printers
Plotters
The Mouse
A mouse is a device which moves a pointer around the screen, options being selected by
pressing (or `clicking') a mouse button. In present day Software a mouse is essential. Graphical
User Interfaces, such as Windows require the use of a mouse.
The Keyboard
This section covers the use of the keyboard.
There are two styles of keyboard in common use, the older 84-key and the now more common
102-key expanded keyboard. The 102-key keyboard normally consists of four main parts;
A typewriter-style alphanumeric keyboard with four extra keys labeled Esc (Escape), Ctrl
(Control), and Alt (Alternate).
A numeric keypad, situated at the far right of the keyboard, providing the digits 0 to 9, a decimal
point and plus and minus signs, together with four special keys labeled Num Lock (Number
Lock), Scroll Lock, Ins (Insert) and Del (Delete). On the 84-key keyboard the numeric keys are
om
also used as cursor control keys. In between the alphabetic keys and the numeric keypad there
are two groups of keys. The top group repeats the functions on the numeric keypad. Below there
r.c
are four cursor keys. These are not present on the 84-keykeyboard.
ke
A set of twelve function keys situated in a single row above the main typewriter keyboard
an
and labeled F1 to F12. On the 84-key keyboards there are ten function keys situated to the left of
the main typewriter keys.
tR
irs
The layout of these keys is shown in figure and their general uses are described in the
.F
following sections. The position of some of the keys may be different from that describedbelow.
w
w
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
What is Hardware ?
Hardware is the physical part of a computer, something which we can touch, feels with
our hand. Technically, we can define the Hardware as all the equipment and electronic circuits
that make up the computer i.e. keyboard, screen, disk drives, printers etc. However the hardware
can do nothing without the software
What is Software?
Software is the set of operational instructions to the hardware, which tells the computer
what to do, how to act, how to generate picture, how to print a bio-data and other documents and
so on. Technically we can define the software as the information that the computer needs to
work on. The information can be instructions, which tell the computer what to do or the data that
is used by the instruction. For example to perform addition, the actual numbers that are entered
into the computer for addition are the data.
A set of instructions that performs a task is known as a program. You cannot touch the software;
it can only be stored on floppy disk, hard disk drive, Compact Disks (CDs), just the way music
is stored in cassettes and CDs.
Types of Software
System Software: this is the most important software which is used as an interpreter between the
user and the computer. It also manages the input and output devices of a computer.
om
Application Software: this is customized software created for user’s specific need and is done
r.c
Computer LANGUAGES
an
tR
Introduction:
irs
A language is the main medium of communicating between the Computer systems and the
most common are the programming languages. As we know a Computer only understands binary
.F
numbers that is 0 and 1 to perform various operations but the languages are developed for different
w
types of work on a Computer. A language consists of all the instructions to make a request to the
w
system for processing a task. Here we will go in the detail of the Computer language and its types.
w
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Low level languages are the machine codes in which the instructions are given in machine language
in the form of 0 and 1 to a Computer system. It is mainly designed to operate and handle all the
hardware. The main function of the Low level language is to operate, manage and manipulate the
hardware and system components. There are various programs and applications written in low level
languages that are directly executable without any interpretation or translation. Low level language
is also divided into two parts are Machine language and Assembly language.
Machine Language is one of the low-level programming languages which is the first
generation language developed for communicating with a Computer. It is written in machine
om
code which represents 0 and 1 binary digits inside the Computer string which makes it easy
to understand and perform the operations. As we know a Computer system can recognize
r.c
electric signals so here 0 stands for turning off electric pulse and 1 stands for turning on
ke
electric pulse. It is very easy to understand by the Computer and also increases the processing
an
speed.
tR
The main advantage of using Machine language is that there is no need of a translator or
irs
interpreter to translate the code, as the Computer directly can understand. But there are some
.F
disadvantages also like you have to remember the operation codes, memory address every time you
w
write a program and also hard to find errors in a written program. It is a machine dependent and can
w
Assembly Language is the second generation programming language that has almost similar
structure and set of commands as Machine language. Instead of using numbers like in
Machine languages here we use words or names in English forms and also symbols. The
programs that have been written using words, names and symbols in assembly language are
converted to machine language using an Assembler. Because a Computer only understands
machine code languages that’s why we need an Assembler that can convert the Assembly
level language to Machine language so the Computer gets the instruction and responds
quickly.
The main disadvantage of this language is that it is written only for a single type of CPU and does
not run on any other CPU. But its speed makes it the most used low level language till today which
is used by many programmers.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
The high level languages are the most used and also more considered programming languages that
helps a programmer to read, write and maintain. It is also the third generation language that is used
and also running till now by many programmers. They are less independent to a particular type of
Computer and also require a translator that can convert the high level language to machine
language. The translator may be an interpreter and Compiler that helps to convert into binary code
for a Computer to understand. There is various high level programming languages like C,
FORTRAN or Pascal that are less independent and also enables the programmer to write a
program.
The Compiler plays an important role on the Computer as it can convert to machine language and
also checks for errors if any before executing. There are several high level languages that were used
earlier and also now like COBOL, FORTRAN, BASIC, C, C++, PASCAL, LISP, Ada, Algol,
Prolog and Java. It is user-friendly as the programs are written in English using words, symbols,
characters, numbers that needs to be converted to machine code for processing.
Step 1 : Edit
Step 2 : Compiling
tR
irs
1. Compiling C Program : C Source code with Extension is given as input to compiler and
.F
3. Compiler Checks for errors . If source code is error-free then Code is converted into
1. During Compilation Compiler will check for error, If compiler finds any error then it will
report it.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Number System:
When we type some letters or words, the computer translates them in numbers as computers
can understand only numbers. A computer can understand the positional number system where
there are only a few symbols called digits and these symbols represent different values depending
on the position they occupy in the number.
Each position represents a specific power of the base (10). For example, the decimal
number 1234 consists of the digit 4 in the units position, 3 in the tens position, 2 in the hundreds
r.c
1000 + 200 + 30 + 4
irs
1234
.F
3 Hexa Decimal Number System Base 16. Digits used: 0 to 9, Letters used : A- F
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Example:-
Binary Number: 101012
Calculating Decimal Equivalent −
Each position in an octal number represents a 0 power of the base (8). Example 80
irs
.F
Last position in an octal number represents a x power of the base (8). Example
8x where x represents the last position – 1
w
w
w
Example
Octal Number: 125708
Calculating Decimal Equivalent −
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Example
Hexadecimal Number: 19FDE16
Calculating Decimal Equivalent −
Step 2 19FDE16 ((1 x 164) + (9 x 163) + (15 x 162) + (13 x 161) + (14 x 160))10
om
Introduction to C Language:
tR
computer programs. The History of C started in 1972 at the Bell Laboratories, USA where Dennis
.F
M. Ritchie proposed this language. In 1983 the American National Standards Institute (ANSI)
w
established committee whose goal was to produce “an unambiguous and machine independent
w
C is the programming language most frequently associated with UNIX. Since the 1970s, the
bulk of the UNIX operating system and its applications have been written in C. Because the C
language does not directly rely on any specific hardware architecture, UNIX was one of the first
portable operating systems. In other words, the majority of the code that makes up UNIX does not
know and does not care which computer it is actually running on. Machine-specific features are
isolated in a few modules within the UNIX kernel, which makes it easy for you to modify them
when you are porting to different hardware architecture.
C was first designed by Dennis Ritchie for use with UNIX on DEC PDP-11 computers. The
language evolved from Martin Richard's BCPL, and one of its earlier forms was the B language,
which was written by Ken Thompson for the DEC PDP-7. The first book on C was The C
Programming Language by Brian Kernighan and Dennis Ritchie, published in 1978.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
It appears that there will be yet another ANSI C standard officially dated 1999 or in the
early 2000 years; it is currently known as "C9X."
IDENTIFIERS :
Names of the variables and other program elements such as functions, array,etc,are known
as identifiers.
There are few rules that govern the way variable are named(identifiers).
1. Identifiers can be named from the combination of A-Z, a-z, 0-9, _(Underscore).
id1, id2, id3 are the names of variable we use. In case of single variable no commas are
required.
r.c
eg float a, b, c;
ke
DATA TYPES :
irs
.F
To represent different types of data in C program we need different data types. A data type
w
is essential to identify the storage representation and the type of operations that can be performed
w
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Derived datatypes are used in ‘C’ to store a set of data values. Arrays and Structures are
.F
Char name[20];
w
Integer num1,num2;
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
VARIABLE:
A variable in simple terms is a storage place which has some memory allocated to it.
Basically, a variable used to store some form of data. Different types of variables require different
amounts of memory, and have some specific set of operations which can be applied on them.
Variable Declaration:
A typical variable declaration is of the form:
type variable_name;
or for multiple variables:
type variable1_name, variable2_name, variable3_name;
Constants
If you want to define a variable whose value cannot be changed, you can use the const keyword.
This will create a constant. For example,
const double PI = 3.14;
Notice, we have added keyword const.
Here, PI is a symbolic constant; its value cannot be changed.
const double PI = 3.14;
om
PI = 2.9; //Error
r.c
Scope of a VARIABLE:
ke
an
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. There are three places where variables
tR
Local Variables
Variables that are declared inside a function or block are called local variables. They can be
used only by statements that are inside that function or block of code. Local variables are not
known to functions outside their own. The following example shows how local variables are used.
Here all the variables a, b, and c are local to main() function.
Global Variables
Global variables are defined outside a function, usually on top of the program. Global
variables hold their values throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
A global variable can be accessed by any function. That is, a global variable is available for
use throughout your entire program after its declaration. The following program show how global
variables are used in a program.
STORAGE CLASSES IN C:-
Type refers to the data type of a variable. And, storage class determines the scope, visibility and lifetime of a variable.
Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist only inside the
block in which it is declared.
Let's take an example.
#include <stdio.h>
int main(void) {
When you run the above program, you will get an error undeclared identifier i. It's because i is declared inside
the for loop block. Outside of the block, it's undeclared.
r.c
int main() {
an
void func() {
irs
This means you cannot access the n1 variable inside func() as it only exists inside main(). Similarly, you cannot access
w
Global Variable
Variables that are declared outside of all functions are known as external or global variables. They are
accessible from any function inside the program.
int main()
{
++n;
display();
return 0;
}
void display()
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
{
++n;
printf("n = %d", n);
}
Output
n=7
Register Variable
The register keyword is used to declare register variables. Register variables were supposed to be faster than
local variables.
However, modern compilers are very good at code optimization, and there is a rare chance that using register
variables will make your program faster.
Unless you are working on embedded systems where you know how to optimize code for the given
application, there is no use of register variables.
Static Variable
A static variable is declared by using the static keyword. For example;
static int i;
The value of a static variable persists until the end of the program.
int main()
{
r.c
display();
display();
ke
}
void display()
an
{
static int c = 1;
tR
c += 5;
irs
printf("%d ",c);
}
.F
w
w
1. const
2. volatile
1. CONST KEYWORD:
1. Constants are also like normal variables. But, only difference is, their values can’t be modified by the
program once they are defined.
2. They refer to fixed values. They are also called as literals.
3. They may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Please refer C – Constants topic in this tutorial for more details on const keyword.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
2. VOLATILE KEYWORD:
1. When a variable is defined as volatile, the program may not change the value of the variable explicitly.
2. But, these variable values might keep on changing without any explicit assignment by the program.
These types of qualifiers are called volatile.
3. For example, if global variable’s address is passed to clock routine of the operating system to store the
system time, the value in this address keep on changing without any assignment by the program. These
variables are named as volatile variable.
Syntax:
volatile data_type variable_name; (or) volatile data_type *variable_name;
1 24 + 5 * 4
an
Here we have two operators + and *, Which operation do you think will be evaluated
first, addition or multiplication? If the addition is applied first then answer will
tR
be 116 and if the multiplication is applied first answer will be 44. To answer such
irs
As a result, the operator with higher precedence is evaluated before the operator
w
w
with lower precedence. Operators that appear in the same group have the same
precedence. The following table lists operator precedence and associativity.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
OPERATO DESCRIPTION
R ASSOCIATIVIT
Y
() Parentheses (function call) (see Note 1)
Prefix increment/decrement
++ —
Unary plus/minus
om
+–
Logical negation/bitwise complement
r.c
* Dereference
.F
&
w
w
Multiplication/division/modul
* / % left-to-right
us
+ – Addition/subtraction left-to-right
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
|| Logical OR left-to-right
ke
an
= Assignment
w
w
+= -= Addition/subtraction assignment
w
*= /= Multiplication/division assignment
right-to-left
%= &= Modulus/bitwise AND assignment
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
TYPE CASTING
Type casting is a way to convert a variable from one data type to another data type. For example,
if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You
can convert the values from one type to another explicitly using the cast operator as follows −
(type_name) expression
Consider the following example where the cast operator causes the division of one integer variable
by another to be performed as a floating-point operation.
#include <stdio.h>
main() {
Type conversions can be implicit which is performed by the compiler automatically, or it can be
r.c
specified explicitly through the use of the cast operator. It is considered good programming
ke
practice to use the cast operator whenever type conversions are necessary.
an
Integer Promotion
tR
Integer promotion is the process by which values of integer type "smaller" than int or unsigned
irs
int are converted either to int or unsigned int. Consider an example of adding a character with an
.F
integer −
w
w
#include <stdio.h>
w
main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
When the above code is compiled and executed, it produces the following result −
Value of sum : 116
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Here, the value of sum is 116 because the compiler is doing integer promotion and converting the
value of 'c' to ASCII before performing the actual addition operation.
om
r.c
ke
an
tR
irs
.F
w
w
The usual arithmetic conversions are not performed for the assignment operators, nor for the
w
logical operators && and ||. Let us take the following example to understand the concept
#include <stdio.h>
main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed, it produces the following result −
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
om
r.c
ke
an
tR
irs
.F
w
w
w
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
UNIT-II
DECISION MAKING STATEMENTS
The if Statement is a powerful decision making statement and is used to control the flow of
execution of statements.it is basically a two-way decision statement and is used in conjunction with
an expression.
They are 3 syntax of if statements
Simple if
If else
And nested
Simple if:
If(test expression)
{
Statement-block;
}
The statement-block may be a single statement or a group of statements. If the expression is true
the statement-block will be executed. Otherwise the statement-block will be skipped and the
execution will jump after the closing brace.
om
Test True
Expression
r.c
ke
an
False Statement
tR
Block
irs
.F
w
w
w
End
#include<stdio.h>
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
int main()
{
int marks;
printf(“\n enter marks”);
scanf(“%d”,&marks”);
if(marks>=90)
printf(“Grade A”);
return 0;
}
Syntax of if else:
if(expression)
{
Statement_block(1);
}
else
{
Statement_block(2);
}
om
Test True
Expression
r.c
ke
an
False Statement
tR
Block1
irs
.F
Statement
w
Block2
w
w
End
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
#include<stdio.h>
int main()
{
int year;
printf(“enter year”);
scanf(“%d”,&year);
if(year%4==0)
printf(“leap year”);
else
printf(“not leap year”);
return0;
}
Nested of if-else
When a series of decision are involved, we may have to use more than one if-else statement in
nested form.
Syntax:
if(cond-1)
Stmt1;
elseif(cond-2)
Stmt2;
elseif(cond-3)
om
Stmt3;
else
r.c
Stmt4;
ke
an
#include<stdio.h>
irs
int main()
.F
{
w
int marks;
w
printf(“enter marks”);
w
scanf(“%d”,&marks);
if(marks>=90)
printf(“gradeA”);
else if(marks>=80)
printf(“Grade B);
else if(marks>=70)
printf(“Grade C”);
else
printf(“Fail”);
return 0;
}
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
#include<stdio.h>
int main()
{
int marks;
printf(“enter marks”);
Scanf(“%d”,&marks);
if((marks>=90)&&(marks<=100)
Printf(“Grade A”);
if((marks>=80)&&(marks<90))
Printf(“GradeB”);
if((marks>=70)&&(mark<80)
printf(“Grade C”);
return 0;
}
#include<stdio.h>
int main()
{
char op;
printf(“\n enter y for yes and n for No”);
scanf(“%c”,&op);
if(op==’Y’||op=’y’)
printf(“the selected option is ye”);
om
if(op==’N’||op=’n’)
printf(“The selected option is No”);
r.c
return 0;
ke
}
an
When one of the many alternatives is to be selected,we can design a program using if
irs
statements to control the selection.C has a built-in multi way decision statement known as ‘switch’.
.F
The Switch statement tests the value of a given variable or expression against a list of case values
w
and when a match is found, a block of statements associated with that caseis executed.
w
w
Syntax:
switch(expression)
{
case value1: block-1;
break;
case value2: block-2;
break;
……….
default: default-block;
break;
}
The expression is an integer expression or characters value1, value2…… are constants and are
known as case labels. Each of these values should be unique within a switch statement.block1,
block2…. Are statements lists and may contain zero or more statements.There is noneed to put
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
braces around these blocks .case labels end with colon(:). When the switchis executed, the value of
the expression is successively compared against the values value-1,Value-2….. if a case is found
whose value matches with the value of the expression,then theblock of statements that follow the
case are executed.
The break statement at the end of each block signal the end of a particular case and causesan exit
from the witch statement,transferring the control to the statements following the switch.The default
is an optional case.when present,it will be executed if the value of theexpression does not match
with any of these case values.if not present , no action takesplace if all matches fail and control
goes to the next statement of switch.
case ‘+’:sum=a+b;
Printf(“sum=%d\n”,sum);
r.c
break;
ke
break;
tR
printf(“product=%\n”,product);
.F
break;
case ‘/’: division=a/b;
w
w
printf(“division=%d\n”,product);
w
break;
default: printf(“error”);
break;
}
getch();
}
Goto Statement:
The goto statement is used to branch unconditionally from one point to another in the program.The
goto requires a label in order to identify the place where the branch is tobemade.The label is made
immediately before the statement where the control is tobetransferred.
goto label;
label: statement;
….. …
The label: can be anywhere in the program either or after the goto label.
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Loops:
There may be a situation, when we need to execute a block of code several number of times. In
general, statements are executed sequentially. i.e., The first statement in a function is executed first,
followed by the second, and so on. Programming languages provide various control structures that
allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of loop statements in most of the programming languages.
for loop
while loop
do loop
Syntax:
initialization is an expression with side –effect that initializes a control variable (typically an
assignment), which can also be a declaration with initialization
r.c
printf(“%d”,i);
w
Syntax:
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
Since, by making use of a block, it is possible to group several statements into a single composite
statement, it is in fact possible to have more than one statement in the body of the loop.
Execution of loop:
Hence , the body of the loop is executed as the condition says true . As soon as it becomes false we
exit the loop and continue with the following statement.
int i =0;
while (i<100)
{
printf(“*”);
i++;
}
The do loop
In a while loop, the condition of end of loop is checked at the beginning of each iteration.
om
A do loop is similar to a while loop,with the only difference that the condition of end of loop is
r.c
Syntax :
irs
.F
do
w
{
w
statement
w
}while (condition);
Execution:
int = 0;
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
do {
printf (“%d”, i);
i++;
}while(i< 100);
int main()
{
r.c
int n, sum,i;
ke
sum=0;
tR
for(i=1;i<=n;i++)
irs
{
.F
sum =sum+i;
w
}
w
return 0;
}
www.FirstRanker.com
www.FirstRanker.com www.FirstRanker.com
om
r.c
ke
an
tR
irs
.F
w
w
w
www.FirstRanker.com