0% found this document useful (0 votes)
17 views93 pages

Overview of Computer Systems and Software

USEFUL

Uploaded by

Pravalika Ponna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views93 pages

Overview of Computer Systems and Software

USEFUL

Uploaded by

Pravalika Ponna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT - I

Introduction
System:system is a collection of components working together to perform a
specific task.

I. Components of a computer:computer can be abbreviated as

Commonly

Opearting

Machine

particularly

Used for

Trade

Education

Reasearch

A computer is a system made up of two major components:


hardware and software.
The computer hardware is the physical equipment.
The software is the collection of programs (instructions) that allow the hardware
to do its job.

Program :is a set of instructions that are grouped together to perform a


specific task.

Computer
System

Hardware Software
Computer Hardware

The hardware component of the computer system consists of five parts: input
devices, central processing unit (CPU) ,primary storage, output devices, and
auxiliary storage devices.

ALU,CU,memory

ALU:arithmetic logic unit:It is used to perform arithmetic operations.


The control unit (CU) is a component of a computer's central processing unit (CPU)
that directs the operation of the processor. It tells the computer's memory, arithmetic
logic unit and input and output devices how to respond to the instructions that have been
sent to the processor.
The input device is any hardware device where programs and data are entered
into the computers. Examples of other input devices include a mouse, a pen or
stylus, a touch screen, or an audio input unit.
[Link],mouse,joystick,scanner,webcam etc.

The central processing unit (CPU) is responsible for executing instructions


such as arithmetic calculations,comparisons among data, and movement of data
inside the system. Today’s computers may have one ,two, or more CPUs .

Memory:it is used to store the programs.

Memory can be categorised as

[Link] memory-RAM-Random access memory.


[Link] memory -ROM-read only memory.

Primary storage ,RAM-Random access memeory -also known as main


memory, is a place where the programs and data are stored temporarily during
processing. The data in primary storage are erased when we turn off a personal
computer or when we log off from a time-sharing system.

The output device is used to display output on the screen.

Auxiliary storage, also known as secondary storage, is used for both input
and output. It is the place where the programs and data are stored permanently.
When we turn off the computer, or programs and data remain in the secondary
storage, ready for the next time we need them.

[Link] disk,memory card,pendrive,CD,DVD etc.

Computer Software

Computer software is divided in to two broad categories:

system software and application software .

System software:It manages the computer resources .It provides the interface
between the hardware and the users.

Application software, on the other hand is directly responsible for helping users
to solve their problems.
System software:It manages the computer resources .It provides the interface between the
hardware and the users.

. An Operating System (OS) is an interface between a computer user and computer


hardware. An operating system is a software which performs all the basic tasks like file
management, memory management, process management, handling input and output, and
controlling peripheral devices such as disk drives and printers.
[Link] opearating system,windows etc.
System management software provides system utilities and other operating
services. Examples of system utilities are sort programs and disk format programs.

system development software, includes the language translators that convert


programs into machine language for execution ,debugging tools to ensure that
the programs are error free and computer –assisted software
engineering(CASE) systems.

Application software, on the other hand is directly responsible for helping users to solve
their problems.

Application software is broken in to two classes .


:general-purpose software
application – specific software.
General purpose software is purchased from a software developer and can be
used for more than one application. Examples of general purpose software
include word processors ,database management systems

Application –specific software can be used only for its intended purpose.
[Link]-used for accounting

The relationship between system and application software is shown in [Link] this
figure, each circle represents an interface point .
The inner core is hard ware. The user is represented by the outer layer. To work
with the system user uses some form of application software. The application
software in turn interacts with the operating system ,which is apart of the system
software layer. The system software provides the direct interaction with the hard
ware
A motherboard is the main circuit board inside a computer that connects the
different parts of a computer together.

[Link] Environments
The different types of computing environments are
1. Personal Computing Environment
2. Time-Sharing Environment
3. Client/Server Environment
4. Distributed Computing
1. Personal Computing Environment
In the personal computing environment,there is a single computer system.
In a personal computer, all the hardware components are tied together, so that it can be
used for general purpose.

The ENIAC (Electronic Numerical Integrator and Computer) was the first electronic
programmable computer .

[Link]-Sharing Environment
The time sharing computing environment allows multiple users to share the system
simultaneously. Each user is provided a time slice and the processor switches rapidly among
the users according to it. Because of this, each user believes that they are the only ones using
the system.

In the time-sharing environment, all computing must be done by the central computer. The
central computer has many duties: It must control the shared resources
[Link]/Server Environment
In client server computing, the client requests a resource and the server provides that
resource.

Both the client and server usually communicate via a computer network but sometimes
they may reside in the same system.
[Link] Computing

It is the technique of linking together multiple computer servers over a network into a
cluster, to share data and to coordinate processing power. Such a cluster is referred to as a
“distributed system.”
[Link] Languages:
software Evolution:
1940’s Machine level Languages- uses 0s and 1s-binary

1950’s Assembly language- uses Symbolic or mnemonic codes ex. Add a,b
.
,Subtract a from b,div a,b etc. mul a,b,push a.

1960’s High-Level Languages-normal english like statements.


1972 c language -Dennis ritche at AT & T bell labs,usa.
1982-83 c++ language -de veloped by bjarne stroustrup at AT and T bell labs
1990’s java language -introduced by sun micro sysytems.

Machine Languages

Each computer has its own machine language, which is made of streams of 0’s
and 1’s.

The only language understood by computer hardware is machine language.


Advantages:
1) High speed execution .
2) The computer can understood instructions immediately.
3) No translation is needed.
Disadvantages: 1) Machine dependent
2) Programming is very difficult
3) Difficult to understand
4) Difficult to write bug free programs .
5) Difficult to isolate an error.

Symbolic Languages:
Computer uses symbolic codes to write a program.
Computer does not understand symbolic language or mnemonic codes - it must be
translated to the machine language. A special program called assembler translates
symbolic code into machine language.
Symbolic program is developed by in early In early 1950’s Admiral Grace
Hopper, A mathematician.
Advantages: 1) Easy to understand and use
2) Easy to modify and isolate error
3) High efficiency
4) More control on hardware
Disadvantages:
1) Machine Dependent Language
2) Requires translator
3) Difficult to learn and write programs
4) Slow development time
High Level Languages: are is easy to read, write, and maintain as it is written in English
like words.
Advantages:
1) Easy to write and understand
2) Easy to isolate an error .
3) Machine independent language.
4) Easy to maintain .
5) Better readability .
6) Low Development cost.
7) Easier to document.
8) Portable
Disadvantages: 1) Needs translator
2) Requires high execution time .
4) Less efficient
Example:
C program for addition of two numbers.
#include<stdio.h>
void main()
{
int a,b,c;
scanf("%d%d%",&a,&b);
c=a+b;
printf("%d",c);
}

Language Translators
These are the programs which are used for converting the programs in one language into
machine language instructions, so that they can be excuted by the computer.
1) Compiler:
-It is a program which is used to convert the high level language programs into
machine language .
Ex.c,c++.
2) Assembler: It is a program which is used to convert the assembly level language
programs into machine language .
3) Interpreter: It is a program, it takes one statement of a high level language program,
translates it into machine language instruction and then immediately executes the resulting
machine language instruction and so on.
[Link].

COMPILER INTERPRETER
A Compiler is used to compile an entire An interpreter is used to translate each line of
program and an executable program is the program code immediately as it is entered
generated through the object program
The executable program is stored in a The executable program is generated in
disk for future use or to run it in RAM
another computer and the interpreter is required for each run of
the program
The compiled programs run faster The Interpreted programs run slower.

Most of the Languages use compiler A very few languages use interpreters.
[Link] AND RUNNING
PROGRAMS OR PROCESS OF
COMPILING AND RUNNING THE
PROGRAM
The procedure for turning a program written in C into machine Language.
The following are the four steps in this process.
1) Writing and Editing the program
2) Compiling the program
3) Linking the program with the required modules.
4) Executing the program
Sl. No. Phase Name of Code Tools File Extension
1 TextEditor Source Code C Compilers .C
Edit,
Notepad Etc..,
2 Compiler Object Code C Compiler .OBJ
3 Linker Executable C Compiler .EXE
Code
4 Runner Executable C Compiler .EXE
Code

Writing and Editing Programs


The software used to write programs is known as a text editor. A text editor helps us
to enter, change and store character data. Once we write the program in the text editor we save it
using a filename stored with an extension of .C. This file is referred as source code file.
Compiling Programs
The entire high level program is converted into the executable machine code file. The
Compiler which executes C programs is called as C Compiler. Example Turbo C, Borland C, GC etc.,
The C Compiler is actually two separate programs:
The Preprocessor

The Translator
The Preprocessor reads the source code and prepares it for the translator. Preprocessors are the
programs that process our source code before compilation.
Ex.#include<math.h>
#incude<stdio.h>
Translator Translator is a program who convert the Source code into object code.
Linking Programs
a linker is a computer program that takes one or more object files generated by a compiler and
combines them into one, executable program.
Loader: Loader is the program of the operating system which loads the executable program from
the disk into the primary memory(RAM) for execution.
Executing Programs

When everything is loaded the program takes control and it begin execution.

[Link]
An algorithm is a procedure or step-by-step instructions for solving a problem.
The characteristics of a good algorithm are:
• Precision – the steps are precisely stated (defined).
• Uniqueness – results of each step are uniquely defined and only depend
on the input and the result of the preceding steps.
• Finiteness – the algorithm stops after a finite number of instructions are executed.
• Input – the algorithm receives input.
• Output – the algorithm produces output.
• Generality – the algorithm applies to a set of inputs.
Algorithm 1: Add two numbers entered by the user

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Q. Write a algorithm to find out given number is odd or


even?

Ans.
step 1 : start
step2:declare the vaiable number,rem
step 2 : read value for number
step 3 : remnumber mod 2
step4 : if rem=0 then
print "number
even"else
print "number odd"
end if
step 5 : stop

number 7
Rem=7 mod 2= 2)7(3-coefficient
6
____
1 remainder
Find the largest number among three numbers

Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c. a=3 b=4 c=5
Step 4: If a > b
If a > c
Display a is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number. Step5:stop

[Link]

Flowchart is a diagrammatic representation of an algorithm.


Different symbols are used for different states in flowchart, For example: Input/Output and
decision making has different symbols. The table below describes all the symbols that are used in
making flowchart

Symbol Purpose Description

Used to indicate the flow of logic by connecting


Flow line
symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Used for airthmetic operations and data-


Processing
manipulations.

Used to represent the operation in which there are


Desicion
two alternatives, true and false.
On-page Connector Used to join different flowline

Off-page Connector Used to connect flowchart portion on different page.

Predefined Used to represent a group of statements performing


Process/Function one processing task.

Examples of flowcharts in programming


Draw a flowchart to add two numbers entered by user.

Draw flowchart to find the largest among three different numbers entered by user.
wwww
[Link] TO C LANGUAGE

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
Eqquipment Corporation PDP-11 computer in 1972.

• C was invented to write an operating system called UNIX.x-cs


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

-B is a computer programming language designed by D. M. Ritchie and Ken


Thompson at Murray Hill, New Jersey. D. M. Ritchie and Ken Thompson, both
worked together at Bell Labs(Murray Hill).
The B programming language was derived from BCPL(Basic Combined
Programming Language).
USES OF C LANGUAGE
IT IS USED TO DEVELOP
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers - SPOOL is an acronym for simultaneous peripheral operations on-line.
• Network Drivers
• Modern Programs
• Data Bases
• Language Interpreters
And Utilities

• C
Program File
• All the C programs are writen into text files with extension ".c" for example hello.c. You
can use"vi" editor to write your C program into a file.
BASIC STRUCTURE OF C PROGRAMMING LANGUAGE #include<stdio.h>
#define pi 3.145
1. Documentation section: The documentation section consists of a set of

comment lines giving the name of the program, the author and other details,
which the programmer would like to use later./* program name */
2. Link section: The link section provides instructions to the compiler to link

functions from the system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such

using the #define directive.


4. 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. This section
also declares all the user-defined functions.
5. main () function section: Every C program must have one main function

section. This section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in

the executable part.


2. 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.
6. 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.

C TOKENS
C tokens are the basic buildings blocks in C language which are constructed
together to write a C program.
Each and every smallest individual unit in a C program is known
as C tokens. C tokens are of six types. They are
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: “total”

Special symbols (eg: (), {}),


Operators (eg: +, /,-,*)

C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The
keywords cannot be used as variable names.
The list of C keywords is given below:

auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void


volatile while
C IDENTIFIERS

An identifier is nothing but a name assigned to an element in a program. Example, name


of a variable, function, etc.
These are user defined names consisting of arbitrarily long sequence of letters and
digits with either a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c
identifiers:
-They must begin with a letter or underscore (_).
-They must consist of only letters, digits, or underscore. No other special character
is allowed.
-It should not be a keyword.
-It must not contain white space.
-It should be up to 31 characters long as only first 31 characters are
significant.

Some examples of c identifiers:


Name Remark
_A9 Valid
[Link] Invalid as it contains special character other than the underscore
void Invalid as it is a keyword
CONSTANTS
constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant,
a character constant, or a string literal.
INTEGER CONSTATNTS:An integer literal can be a decimal, octal, or hexadecimal
constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and
nothing for decimal.
Octal, also known as "base-8," is a number system that uses eight digits (0 - 7) to represent
any integer.
Being a Base-16 system, the hexadecimal numbering system therefore uses 16 (sixteen)
different digits with a combination of numbers from 0 through to 15.
Values are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.

85 /* decimal */
0213 /* octal */
0x4B /* hexadecimal */
30 /* int */

REAL CONSTANTS:Numbers with fractional part are called real constants.

Here the mantissa must be multiplied by 10^exponent for example 345.25E-4 is equal to
345.25*10-4 and 4.56E4 is equal to 4.56*104.
Single character constant:
A single alphabet, digit or any special symbol placed in single inverted commas is called a
single character constant.

1) ‘X’
2) `v`
3) “c”
4) ‘hello’
5) ‘5’
6) ‘=’
7) ‘\n’
Hide Answers
1) Valid
2) Invalid (Single inverted commas are directed towards right)
3) Invalid (Must not be placed in double inverted commas)
4) Invalid (Should have single character only)
5) Valid
6) Valid
7) Valid (\n is considered as single character )
2) It should be noted that character constants have numerical values known as
ASCII values, for example, the value of ‗A‘ is 65 which is its ASCII value.

ESCAPE CHARACTERS
3) C allows us to have certain non graphic characters in character constants. Non
graphic characters are those characters that cannot be typed directly from
keyboard, for example, tabs, carriage return, etc.
4) These non graphic characters can be represented by using escape sequences
represented by a backslash() followed by one or more characters.
5) NOTE: An escape sequence consumes only one byte of space as it represents a
single character.
6)
Escape Sequence Description
a Audible alert(bell)
b Backspace
f Form feed
n New line
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash
“ Double quotation mark
‘ Single quotation mark
? Question mark
Null
STRING CONSTANTS
7)

SPECIAL SYMBOLS

The following special symbols are used in C having some special


meaning and thus, cannot be used for some other purpose.
[] () {} , ; : * … = #
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.

VARIABLES
A variable is a name of the memory location.
It is used to store data. Its value can be changed, and it can be reused many times.
. Each variable in C has a specific type, which determines the size and layout of the
variable's memory;
the range of values that can be stored within that memory and the set of operations that
can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character
It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because C is case-sensitive.

the following basic variable types −BASIC DATA TYPES IN C

Int type Size( in bytes) Range allowed

int or signed int 2 -32,768 to 32767

unsigned int 2 0 to 65535


short int or signed short int 1 -128 to 127

unsigned short int 1 0 to 255

long int 4 -2,147,483,648 to 2,147,4

unsigned long int 4 0 to 4,294,967,295

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for
the variable. A variable definition specifies a data type and contains a list of one or
more variables of that type as follows −

type variable_list;

Here, type must be a valid C data type including char, w_char, int, float, double,
bool, or any user-defined object; and variable_list may consist of one or more
identifier names separated by commas. Some valid declarations are shown here −

int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; declares and defines the variables i, j, and k; which instruct
the compiler to create variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The


initializer consists of an equal sign followed by a constant expression as follows −
type variable_name = value;

Some examples are −

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
undefined.

OPERATORS AND EXPRESSIONS


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

[Link] Types of Operators Description

These are used to perform mathematical calculations


like addition, subtraction, multiplication, division and
1 Arithmetic_operators modulus (+,-,*,/,%)

These are used to assign the values for the variables


2 Assignment_operators in C programs.(=) ex. a=10;
These operators are used to compare the value of two
3 Relational operators variables.<,>

4 Logical operators
These operators are used to perform logical
operations on the given two variables.&&,||,not,!

These operators are used to perform bit operations on


5 Bit wise operators given two variables.&,|,not

Conditional (ternary) Conditional operators return one value if condition is


6 operators true and returns another value is condition is false.

( ?: )

Increment/decrement These operators are used to either increase or


7 operators decrease the value of the variable by one.++,--

8 Special operators &, *, sizeof( ) and ternary 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
[Link] Operators Operation Example

1 + Addition A+B

2 – Subtraction A-B

3 * multiplication A*B

4 / Division A/B

5 % Modulus A%B

EXAMPLE PROGRAM FOR C ARITHMETIC OPERATORS


In this example program, two values ―40‖ and ―20‖ are used to perform arithmetic operations
such as addition, subtraction, multiplication, division, modulus and output is displayed for each
operation.
#include <stdio.h>

int main()

int a=40,b=20, add,sub,mul,div,mod;

add = a+b;

sub = a-b;

mul = a*b;

div = a/b;

mod = a%b;

printf("Addi

tion of a, b

is : %d\n",

add);

printf("Subtraction of a, b is : %d\n", sub);

printf("Multiplication of a, b is : %d\n", mul);

printf("Division of a, b is : %d\n", div);

printf("Modulus of a, b is : %d\n", mod);

return 0;

}
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2

Modulus of a, b is : 0

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;

Other assignment operators in C language are given below.


Operators Example Explanation

Simple
assignment 10 is assigned
operator = sum = 10 to variable sum

sum += This is same as


+= 10 sum = sum + 10

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

sum *= This is same as


*= 10 sum = sum * 10

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

This is same as
sum %= sum = sum %
%= 10 10

This is same as
sum = sum &
&= sum&=10 10
Compound
assignment sum ^= This is same as
operators ^= 10 sum = sum ^ 10
/*Sum of first 10

natural numbers

*/

# include <stdio.h>
int main()
{

int total=0,i;
for(i=0;i<10;i++)
{

total+=i; // This is same as Total = Total+I;


}

printf("Total = %d", total);


return 0;
}
Output:

Total = 45

For loop:it is an iterative staement which allows code to be executed repeatedly.

Hai Hai Hai Hai Hai


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.
[Link] Operators Example Description

x is greater than
1 > x>y y

2 < x<y x is less than y

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

x is less than or
4 <= x <= y equal to y
5 == x == y x is equal to y

x is not equal to
6 != x != y y

In this program, relational operator (==) is used to compare 2 values whether they are
equalor not.
If both values are equal, output is displayed as values are equal. Else, output is displayed
as values are not equal.
Note: double equal sign (==) should be used to compare 2 values. We should not single
equal sign (=).
EXAMPLE PROGRAM FOR RELATIONAL OPERATORS IN C
/*Example of Relational operators */
#include<stdio.h>
int main()
{

int m=40,n=20;
if (m == n)
{

printf("m and n are equal");

else

printf("m and n are not equal");

return 0;
}
Output:
m and n are not equal
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 (||) andlogical
NOT (!).

[Link] Operators Name Example Description

It returns true
when both
logical conditions
1 && AND (x>5)&&(y<5) are true

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

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

If ((x>5)
&& (y<5))‖
is true,
logical NOT
logical operator
3 ! NOT !((x>5)&&(y<5)) makes it false

EXAMPLE PROGRAM FOR LOGICAL OPERATORS IN C:


#include<stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \"But, status is inverted as false\n");
}
return 0;
}

OUTPUT:

&& Operator : Both conditions are true


|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as 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 complement), ^ (XOR),
<< (left shift) and >> (right shift).

TRUTH TABLE FOR BIT WISE OPERATION BIT WISE OPERATORS

x x
& ^
x y x|y y y

0 0 0 0 0

0 1 1 0 1

1 0 1 0 1

1 1 1 1 0

Operator_symbol
Operator_name

& Bitwise_AND

| Bitwise OR

~ Bitwise_NOT

^ XOR
<< Left Shift

>> Right Shift

Bitwise AND operator &


The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either
bit of an operand is 0, the result of corresponding bit is evaluated to 0.

Let us suppose the bitwise AND operation of two integers 12 and 25


12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
00011001 &
________
00001000 = 8 (In decimal)

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
printf("Output = %d", a|b);

return 0;
}
Output:8
Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In
C Programming, bitwise OR operator is denoted by |.

Example 1
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)
Example 2: Bitwise OR
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}

Output = 29
Bitwise XOR (exclusive OR) operator ^
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite. It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
^00011001
________
00010101 = 21 (In decimal)
Example 3: Bitwise XOR
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
return 0;
}

Output
Output = 21
Bitwise complement operator ~
Bitwise compliment operator is an unary operator (works on only one operand). It
changes 1 to 0 and 0 to 1. It is denoted by ~.
35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

The bitwise complement of 35 (~35) is -36 instead of 220


For any integer n , bitwise complement of n will be -(n+1)

2 's Complement
Two's complement is an operation on binary numbers. The 2's complement of a
number is equal to the 1’s complement of that number plus 1.

Decimal Binary 2's complement =1’s compement+1


0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)
include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
return 0;
}

Output
Output = -36
Shift Operators in C programming
There are two shift operators in C programming:

• Right shift operator

• Left shift operator.

Right Shift Operator >>

Right shift operator shifts all bits towards right by certain number of specified bits. It is
denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)

Left Shift Operator <<


Left shift operator shifts all bits towards left by a certain number of specified bits. The
bit positions that have been vacated by the left shift operator are filled with 0. The
symbol of the left shift operator is <<.
212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 = 11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)

EXAMPLE PROGRAM FOR BIT WISE


OPERATORS IN C
In this example program, bit wise operations are performed and output is displayed in
decimal format.
#include <stdio.h>
int main()
{
int m = 40,n = 80,and_opr,or_opr,xor_opr,not_opr ;
and_opr = (m&n);
or_opr = (m|n);
not_opr = (~m);
xor_opr = (m^n);
printf("AND_opr value = %d\n",and_opr );
printf("OR_opr value = %d\n",or_opr );
printf("NOT_opr value = %d\n",not_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
Output:

AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

CONDITIONAL OR TERNARY OPERATORS IN C


Conditional operators return one value if condition is true and returns another value is
conditionis false.
This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);

A=10;
A > 100 ? 0 : 1
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.

/*TERNARY OPERATOR PROGRAM IN C*/


#include <stdio.h>
int main()
{

int x=1, y ;

y = ( x ==3 ? 100 : 0 ) ;

printf("x value is %d\n", x);


printf("y value is %d", y);
}
OUTPUT:
x value is 1
y value is 0

EXAMPLE 2
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditi
onal operator
return 0;
}

C – Increment/decrement Operator

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: pre increment ++var_name ;
( or) post increment operator var_name++;
Decrement operator: – -var_name; (or) var_name – -;

Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
#include<stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
Output:1 2 3 4 5 6 7 8 9
EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C
In this program, value of ―I is decremented one by one from 20 up to 11 using ―-i operator and output is
displayed as 20 19 18 17 16 15 14 13 12 11.
//Example for decrement operators

#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i); -20-19-18-17-16-15-14-13-12-11
i--;
}

Examples
a=5
b=++a; // b becomes 6
a=5
b=a++;

a=8;

b=a++; // b becomes 8

a=6;
b=--a; // b becomes 5

a=6;
b=a--; // b becomes 6
a=10;
b=a--;
//b value 10

A=30;
B=--A;
//B value is 29

[Link] Operator type Operator Description

1 Pre increment
++i Value of i is
incremented before
assigning it to variable
i.

Value of i is
incremented after
i++ assigning it to variable
2 Post–increment i.

Value of i is
decremented before
— –i assigning it to variable
3 Pre decrement i.

Value of i is
decremented after
i– — assigning it to variable
4 Post_decrement i.

SPECIAL OPERATORS
Below are some of special operators that C language offers.

[Link] Operators Description

This is used to get the address


of the variable.

Example : &a will give address


1 & of a.

This is used as pointer to a


variable.

Example : * a where, * is
2 * pointer to the variable a.
This gives the size of the
variable.

Example : size of (char) will


3 Sizeof () give us 1.
EXAMPLE PROGRAM FOR & AND * OPERATORS IN C
In this program, ―& symbol is used to get the address of the variable and ―
Pointer variable is used to store the address of a variable.
Syntax:
data_type *variable name;
• Is used to refer to a variable that the pointer is pointing to. It is also called as Dereferencing.

#include <stdio.h>
int main()
{

int *ptr , q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}

OUTPUT:

50

EXAMPLE PROGRAM FOR SIZEOF() OPERATOR IN C


sizeof() operator is used to find the memory space allocated for each C data types.
#include <stdio.h>

#include <limits.h>
int main()

int a;

char b;
float c;

double d;

printf("Storage size for int data type:%d \n",sizeof(a));

printf("Storage size for char data type:%d \n",sizeof(b));

printf("Storage size for float data type:%d \n",sizeof(c));

printf("Storage size for double data

type:%d\n",sizeof(d));

return 0;

OUTPUT:

Storage size for int data type:2


Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

EXPRESSIONS
Expression:It is a combination of operands and operators.
Arithmetic expression in C is a combination of variables, constants and operators written in a proper
syntax.
Operator Associativity is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right or Right to Left.

2+3-2 =3 the expression is evaluated from letft to right.


3+4+2=9 the expression is evaluated from letft to right.

100/10*10
=10*10=100
Operators precedence:
A=10

Operators precedence: The precedence of operators determines which operator is executed first if
there is more than one operator in an expression.

The highest precedence of operator is evaluated first than the lower precedence operator.
Note: C does not have any operator for exponentiation
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10

10 + 20 * 30 is calculated as 10 + (20 * 30)=610


EVALUATION OF EXPRESSION
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the
arithmetic expression is evaluated from left to right. There are two priority levels of operators inC.
High priority: */ %
Low priority: +-
The evaluation procedure of an arithmetic expression includes two left to right passes through
the entire expression.

In the first pass, the high priority operators are applied as they are encountered and in the
second pass, low priority operations are applied as they are [Link], we have an
arithmetic expression as:
For example : x = 9 – 12 / 3 + 3 *2 - 1
This expression is evaluated in two left to right passes as:
First Pass
For example,
x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are evaluated first
fromleft to right. The expression is now evaluated in three passes as:

First Pass

Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7

For example :x = 9 – ((12 / 3) + 3 * 2) – 1


The expression is now evaluated as:
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2

1. 5+2*4=13
2. (3+4)*2=14
3. 100+200/10-3*10=90

100+20-3*10
100+20-30
90

4.(10+20)*30
=30*30=900
4.A=5,b=6,c=4;
Res=--A*b- ++c;
4*6-5
24-5
19
5.--A*b-c++
=4*6-4
24-4=20
STORAGE CLASSES IN C
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the
scope, visibility and lifetime of a variable.
• The variable scope.
• The location where the variable will be stored.
• The initialized value of a variable.
• A lifetime of a variable.

Scope:it is the part of the program where the variable is accessible.


Life time: The lifetime of a variable or function is the time duration for which
memory is allocated to store it, and when that memory is released
There are 4 types of storage class:
automatic
external
static
register
Automatic (Auto) storage class
The variables declared inside a block are automatic or local variables. The local
variables exist only inside the block in which it is declared.
This is default storage class
All variables declared are of type Auto by default.
In order to Explicit declaration of variable use

auto int num1 ; // Explicit Declaration

Example program for auto or local variable.


#include<stdio.h>
void main()
{
auto int num= 20 ;
{
auto int num= 60 ;
printf("nNum : %d",num);
}
printf("nNum : %d",num);
}
Output :
nNum : 60
nNum : 20

/*program for auto variable*/

#include <stdio.h>

int main()
{
auto int a;
a=10;
printf("%d", a);
return 0;
}
Output: 10
Storage Memory

Scope Local / Block Scope


Life time Exists as long as Control remains in the
block

Default initial Garbage


Value

External variable or 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.

These variables are accessible throughout the program

Syntax :extern int a;

Example 1: Global Variable


#include <stdio.h>
void display();
extern int n = 5; // global variable
int main()
{
++n;
display(); //function call
…………….
return 0;
}

void display()
{
++n;
printf("n = %d", n);
}

Output
n=7
Storage Memory

Scope Global / File Scope


Life time Exists as long as variable is running
Retains value within the function

Default initial Value Zero

Static storage class: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.

The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope.

Example 2: Static Variable


#include <stdio.h>
void display();
int main()
{
display();
………………………..
display();
----------------
return 0;
}
void display()
{
static int c = 1;
c += 5;//c=c+5
printf("%d ",c);
}
Output
6 11
During the first function call, the value of c is initialized to 1. Its value is increased by
5. Now, the value of c is 6, which is printed on the screen.
During the second function call, c is not initialized to 1 again. It's because c is a static
variable. The value c is increased by 5. Now, its value will be 11, which is printed on
the screen.
Register Storage Class
register keyword is used to define local
variable.

Local variable are stored in register instead


of RAM.
As variable is stored in register, the Maximum size of variable = Maximum
Size of Register.
This is generally used for
faster access.
Common use is ―Counter―
Syntax
register int count;

Register storage classes example


#include<stdio.h>

int main()
{
int num1,num2; //local
register int sum;

printf("\nEnter the Number 1 : ");


scanf("%d",&num1);

printf("\nEnter the Number 2 : ");


scanf("%d",&num2);
sum = num1 + num2;

printf("\nSum of Numbers : %d",sum);

return(0);
}
Explanation of
program
Refer below animation which depicts the register storage classes –
In the above program we have declared two variables num1,num2. These two variables are
stored in RAM.
Another variable is declared which is stored in register variable. The only difference is that

the variables declared using register storage class are stored inside CPU registers
instead of a memory. Register has faster access than that of the main memory.

TYPE CONVERSION IN EXPRESSIONS


When variables and constants of different types are combined in an expression then they are
converted to same data type.
The process of converting one predefined type into another is called type conversion

Here, the value of a has been promoted from int to double and we have not had to
specify any type-casting operator. This is known as a standard conversion.

Type conversions can be divided into 2 types:

[Link] type conversion


[Link] type conversion

Implicit Type Conversion


The type conversion that is done automatically done by the compiler is known as
implicit type conversion. This type of conversion is also known as automatic
conversion.
Example :-implicit conversion program in c
#include<stdio.h>
void main()
{
int a=20;
double p;
clrscr();
p=a;//implicit conversion
printf(“implicit value is %d”,p);
}
Output:-
implicit value is 20.00000000
Data Loss During Conversion (Narrowing Conversion):
Narrowing conversion is used to convert from a larger size type to a smaller size.
Example :-conversion of larger data type to smaller data type program in c
#include<stdio.h>
void main()
{
clrscr();
Int a;
double p=20.26;
a=p;//implicit conversion
printf(“ value of a is %d”,a);
//printf(“value of a is %d”,p);
}
Output:- value is a is 20

Diagram shows conversion can be done from


Converting from smaller data type into larger data type is also called as type promotion-
widening.

Explicit Type Conversion


The type conversion is performed by the programmer by posing the data type of the
expression ofspecific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type)expression;
where, data_type is any valid c data type, and expression may be constant, variable
orexpression.

/* C program to demonstrate explicit type casting*/


#include<stdio.h>

int main()
{
double x = 1.2;
int sum;
// Explicit conversion from double to int
sum = (int)x + 1;

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

return 0;
}

Output:
sum = 2
C Input Output (I/O) or formatting i/o or introduction to stdin,stdout,stderror
C Output function
In C programming, printf() is one of the main output function.
It is used to display output on the [Link] function sends formatted output to the screen
based on format specification.
The format specification string, along with the data to be output, are the parameters to the
printf() function.
Syntax:printf (format, var1, var2,… );

printf(“welcome to vits”); //welcome to vits


x=10;
printf(“x”);//x

printf(“%d”,x);
output :10

int x=10,y=20;
printf(“%d%d”,x,y);//10,20
printf(“x,y”);x,y

x=10.00;
//x value is= 10
printf(“x value is=%f”,x);
x value is =10.000000.
Conversion Meaning
Character
d The data is converted to decimal (integer)
c The data is taken as a character.
s The data is a string and character from the string , are printed until a NULL,
character is reached.
f The data is output as float or double with a default Precision 6.
Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)
#include <stdio.h>
int main()
{
char chr = 'a';
// Displays the string inside quotations
printf("C Programming");
int testInteger = 5;
float number1 = 13.5;
double number2 = 12.4;

printf("Number = %d", testInteger);


printf("number1 = %f\n", number1);
printf("number2 = %lf", number2);

printf("character = %c", chr);


return 0; //exit satus
}
C programming
Number = 5
number1 = 13.500000
number2 = 12.400000
printf formats : Right justifying printf integer output
printf("%3d", 0); 0

printf("%3d", 123456789); 123456789

printf("%3d", -10); -10

printf("%3d", -123456789); -123456789

Left-justifying printf integer output

To left-justify integer output with printf, just add a minus sign (-) after
the % symbol, like this:

printf("%-3d", 0); 0
printf("%-3d", 123456789); 123456789

printf("%-3d", -10); -10

printf("%-3d", -123456789); -123456789

scanf() function to take input from the user and printf() function to display
output to the user.

Syntax:scanf(“format”,&var1,&var2……);
Int x;
scanf(“%d”,&x);

Int x,y;
Scanf(“%d%d”,&x,&y);

float z;

scanf(“%d%f”,&x,&z);
Int main()
{
Int x;
Printf(“enter x value”);
Scanf(“%d”,&x);
Printf(“enter y value”);
Scanf(“%d”,&y);
Printf(“total=%d”,(x+y));

}
Enter x value
10
Enter y value
20
Total=30
X 2001
y 3001

#include <stdio.h>
int main() {

int c;

printf( "Enter a value :");


c = getchar( );

printf( "\nYou entered: ");


putchar( c );

return 0;
}
The getchar() and putchar() Functions
The int getchar(void) function reads the next available character from the standard
input and returns it as an integer. This function reads only single character at a time.
the int putchar(int c) function :is used to write a character to standard output
device.
the passed character on the screen and returns the same character. This
function puts only single character at a time.
getch():
getch() is a nonstandard function and is present in conio.h header
file which is mostly used by MS-DOS compilers like Turbo C.
not part of the C standard library or ISO C-Like above functions, it
reads also a single character from keyboard. But it does not use
any buffer, so the entered character is immediately returned
without waiting for the enter key.

#include <stdio.h>
int main( ) {
int c;
printf( "Enter a value :");
c = getchar( );

printf( "\nYou entered: ");


putchar( c );

return 0;
}
Enter a value : hello
You entered: h
The Standard Files in c
C programming treats all the devices as files.
C standard files can be categorised as
1. Standard input
2. Standard output
3. Standard error

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file pointers are the means to access the file for reading and writing purpose.

The gets() and puts() Functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to
by s until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline
to stdout.

#include <stdio.h>
int main( ) {
char str[100];

printf( "Enter a value :");


gets( str );
printf( "\nYou entered: ");
puts( str );

return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads the
complete line till end, and displays it as follows −
Enter a value : this is test
You entered: this is test
statement that is used to control the flow of execution in a program is called control structure

1. Sequential statement, or sequential flow


2. Selection stetement, or conditional flow
3. Iteration statement, or repetitive flow

[Link] structures or sequential statements: In a C program, the flow of


execution is sequential by default, that is, one statement after another in their order
as in the source code of a function
[Link] flow statements

[Link] STATEMENTS:
A selection statement selects among a set of statements depending on the value of a
controlling expression.
The if-else statement in C is used to perform the operations based on some
specific condition. The operations specified in if block are executed if and only if
the given condition is true.

here are the following variants of if statement in C language.

o If statement

o If-else statement

o If else-if ladder

o Nested if

• If statement: It Checks whether the given Expression is Boolean or not !!


If Expression is True Then it executes the statement otherwise jumps to next_instruction

Syntax :
if
(
e
x
p
r
e
s
s
i
o
n
)
s
t
a
t
e
m
e
n
t
1
;

E
x
p
l
a
n
a
ti
o
n
:
• Expression is Boolean Expression
• It may have true or false value

Program to find the largest number of the three.


#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter three numbers?");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
{
printf("%d is largest",a);
}
if(b>a && b > c)
{
printf("%d is largest",b);
}
if(c>a && c>b)
{
printf("%d is largest",c);
}
if(a == b && a == c)
{
printf("All are equal");
}
}

Output

Enter three numbers?


12 23 34
34 is largest
IF-ELSE STATEMENT: if the value of test-expression is true, then the true block of statements will be
executed.
If the value of test-expression if false, then the else block of statements will be executed.

if(expression)
{
//code to be executed if condition is true
}
Else
{
//code to be executed if condition is false
}
/* program to check whether the given number is odd or even */
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is even number",number);
}
else{ 5/2=1
printf("%d is odd number",number);
}
return 0;
}

Output

enter a number:4
4 is even number
enter a number:5
5 is odd number
//Program to check whether a person is eligible to vote or not.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
}
}

Output

Enter your age?18


You are eligible to vote...
Enter your age?13
Sorry ... you can't vote

If else-if ladder Statement


The if-else-if ladder statement is an extension to the if-else statement. In if-else-if
ladder statement, if a condition is true then the statements defined in the if block
will be executed, otherwise if some other condition is true then the statements
defined in the else-if block will be executed, at the last if none of the condition is
true then the statements defined in the else block will be executed..

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
...
else{
//code to be executed if all the conditions are false
}

Flowchart of else-if ladder statement in C

Program to calculate the grade of the student according to


the specified marks.
#include <stdio.h>
int main()
{
int marks;
printf("Enter your marks");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A ...");
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B ...");
}
else if (marks > 30 && marks <= 40)
{
printf("You scored grade C ...");
}
else
{
printf("Sorry you are fail ...");
}
return 0;
}

Output

Enter your marks10


Sorry you are fail ...
Enter your marks40
You scored grade C ...
Enter your marks90
Congrats ! you scored grade A ...

NESTED IF STATEMENT:if the if statement contains another if statement is called


as nested if statement.

write a program to illustrate the use of nested if-else.


program checks if a number is less or greater than 10 and prints the result using nested if-else
construct.

#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Output:
The value is:1
The switch statement is a multiway branch [Link] is an alternative to if
statement.
The switch statement allows us to execute one code block among many
alternatives.
A switch statement allows a variable to be tested for equality against a list of values.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

• The switch expression is evaluated once


• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed
• . The break is a keyword in C which is used to bring the program control out of the loop. It
terminates the enclosing case associated code block.

default: If switch expression does not match with any case, default statements are
executed by the program.
/* uses the weekday number to calculate the weekday name:*/
simple Calculator
/* Program to create a simple calculator*/
#include <stdio.h>
int main() {
char operator;
double n1, n2;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);

switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;

// operator doesn't match any case constant +, -, *, /


default:
printf("Error! operator is not correct");
}

return 0;
}
Output
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
LOOP CONTROL STATEMENTS
In programming, loops are used to repeat a block of code until a specified
condition is met.
C programming has three types of loops.
[Link] loop
[Link] loop
[Link]...while loop

While statement:
The syntax of the while loop is:
while (testExpression)
{
// the body of the loop
}

If the test expression is true, statements inside the body of while loop are
executed. Then, the test expression is evaluated again.
The process goes on until the test expression is evaluated to false.
If the test expression is false, the loop terminates (ends).
While loop is also called as entry controlled loop.

Flowchart of while loop

Example 1: while loop


// Print numbers from 1 to 5

#include <stdio.h>
int main()
{
int i = 1;

while (i <= 5)
{
printf("%d\n", i);
++i;
}

return 0;
}
Output
1
2
3
4
5
Do...while loop
It is also called as exit controlled loop.
The do..while loop is similar to the while loop with one important difference.
The body of do...while loop is executed at least once. Only then, the test
expression is evaluated.
The syntax of the do...while loop is:
do
{
// the body of the loop
}
while (testExpression);

do...while loop works as follows


• The body of do...while loop is executed once. Only then, the test
expression is evaluated.

• If the test expression is true, the body of the loop is executed again
and the test expression is evaluated.

• This process goes on until the test expression becomes false.

• If the test expression is false, the loop ends.

Flowchart of do...while Loop

Working of do...while loop

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do
5. {
6. printf("%d \n",i);
7. i++;
8. }while(i<=10);
9.
10. return 0;
11. }
Output
1
2
3
4
5
6
7
8
9
10
for Loop
The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}

How for loop works?


The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is evaluated
to false, the for loop is terminated.
However, if the test expression is evaluated to true, statements inside the
body of the for loop are executed, and the update expression is updated.
Again the test expression is evaluated.
This process goes on until the test expression is false. When the test
expression is false, the loop terminates.

for loop Flowchart


Working of for loop

Example 1: for loop

// Print numbers from 1 to 10


#include <stdio.h>

int main() {
int i;

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


{
printf("%d ", i);
}

return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
the goto statement is a jump statement which jumps from one point to another point
within a function.

Syntax of goto statement

goto label;
----------
----------
label:
----------
----------

In the above syntax, label is an identifier. When, the control of program reaches to goto statement,
the control of the program will jump to the label: and executes the code after it.
The goto statement allows us to transfer control of the program to the specified label.

Example of goto statement


#include<stdio.h>

void main()
{
printf("\nStatement 1.");
printf("\nStatement 2.");
printf("\nStatement 3.");

goto last;

// printf("\nStatement 4.");
printf("\nStatement 5.");

last:
printf("\nStatement 5");

//printf("\nEnd of Program.");
}

Output :

Statement 1.
Statement 2.
Statement 3.
End of Program.

Break Statement
The break statement is used inside loop or switch statement.

The break in C or C++ is a loop control statement which is used to


terminate the loop. .

Example of break statement

#include<stdio.h>

void main()
{
int a=1;

while(a<=10)
{
if(a==5)
break;

printf("\nStatement %d.",a);
a++;
}
printf("\nEnd of Program.");
}

Output :

Statement 1.
Statement 2.
Statement 3.
Statement 4.
End of Program.
CONTINUE STATEMENT :The continue statement skips the current
iteration of the loop and continues with the next iteration.
Example of continue statement
Continue statement:
loop
{
continue;
//code
}
/*continue statement */
#include<stdio.h>

void main()
{
int a=0;

while(a<=10)
{

a++;

if(a==5)
continue;

printf("\nStatement %d.",a);

}
printf("\nEnd of Program.");
}
Output :

Statement 1.
Statement 2.
Statemnent 3.
Statement 4.
Statement 6.
Statement 7.
Statement 8.
Statement 9.
Statement 10.
End of Program.

Write a c program to print multiplication table using for loop.


Take input from user.

#include <stdio.h>
int main()
{
int n, i;

printf("Enter a Number ");


scanf("%d",&n);

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


{
printf("%d * %d = %d \n", n, i, n*i);
}

getch();

}
Output:enter a number 5 5*1=5 --5*2=10----5*3=15------5*10=50

/*factorial Program using loop.*/


#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
printf("Factorial of %d is: %d",number,fact);
return 0;
}

Output:

Enter a number: 5!=5*4*3*2*1=120

Factorial of 5 is: 120

Fact=1;number=5

for(i=1;i<=number;i++){ 1<=5
fact=fact*i;

fact=1*1

Fact=fact* i
1*1=1
Fact=1
1*2=2
Fact=2
2*3=6
Fact=6
6*4=24
Fact=24
24*5=120

/*sum of digits of a given number program in C.*/


#include<stdio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}
Output:
Enter a number:654
Sum is=15
Enter a number:123
Sum is=6
N=654
/*a simple c example to swap two numbers without using third variable.*/
#include<stdio.h>
int main()
{
int a=10, b=20; // a=25 b=20
printf("Before swap a=%d b=%d",a,b);
a=a+b;//a=30 (10+20) //a=45
b=a-b;//b=10 (30-20) //b=45-20=25---b=25
a=a-b;//a=20 (30-10) //45-25=20-a
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
Output:
Before swap a=10 b=20
After swap a=20 b=10

#include <stdio.h>
int main()
{
int var1, var2, temp;
printf("Enter two integersn");
scanf("%d%d", &var1, &var2);
printf("Before SwappingnFirst variable = %dnSecond variable = %dn", var1, var2);
temp = var1;
var1 = var2;
var2 = temp;
printf("After SwappingnFirst variable = %dnSecond variable = %dn", var1, var2);
return 0;
}
Output:
/*simple c example to print "hello world" using if statement and without using semicolon.*/
#include<stdio.h>
int main()
{
if(printf("hello world")) { }
return 0;
}
Output:
hello world
the program find the sum of odd numbers from 1 to N numbers using for loop.
#include<stdio.h>
int main()
{
int n, sum=0;

printf("Enter n value: ");


scanf("%d",&n);10

for(int i=1; i<=n; i++)


{
if(i%2!=0)
sum += i;//1//1+3//+5+7+9=25
}

printf("Sum of odd numbers from 1 to %d is: %d", n, sum);

return 0;
}

Enter n value: 10
Sum of odd numbers from 1 to 10 is: 25
Enter n value: 20
Sum of odd numbers from 1 to 20 is: 100

You might also like