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

cnotes

A computer is an electronic device that processes data through hardware and software, performing functions such as input, processing, output, and storage. The Central Processing Unit (CPU) consists of the Control Unit and Arithmetic Logic Unit (ALU), managing operations and calculations. Additionally, algorithms and flowcharts are essential for problem-solving and programming, while operating systems manage resources and facilitate user interaction.

Uploaded by

akhilakodam02
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

cnotes

A computer is an electronic device that processes data through hardware and software, performing functions such as input, processing, output, and storage. The Central Processing Unit (CPU) consists of the Control Unit and Arithmetic Logic Unit (ALU), managing operations and calculations. Additionally, algorithms and flowcharts are essential for problem-solving and programming, while operating systems manage resources and facilitate user interaction.

Uploaded by

akhilakodam02
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

A computer is an electronic device that manipulates information or "data.

" It has the ability to store, retrieve,


and process data.

All types of computers consist of two basic parts – hardware and software.
Hardware is any part of your computer that has a physical structure, such as the computer monitor or
keyboard. If you can touch it, it is hardware.

Software is any set of instructions that tells the hardware what to do. It is what guides the hardware and tells it
how to accomplish each task.

A computer has four functions:

a. accepts data Input


b. processes data Processing
c. produces output Output
d. stores results Storage

Block Diagram of Computer:

Input Unit: Computers need to receive data and instruction in order to solve any problem. Therefore we need to
input the data and instructions into the computers. The input unit consists of one or more input devices.
Keyboard is the one of the most commonly used input device. Other commonly used input devices are the
mouse, floppy disk drive, magnetic tape, etc.

Storage Unit: he storage unit of the computer holds data and instructions that are entered through the input unit,
before they are processed. It preserves the intermediate and final results before these are sent to the output
devices. It also saves the data for the later use. The various storage devices of a computer system are divided
into two categories.
1. Primary Storage: Stores and provides very fast. This memory is generally used to hold the program being
currently executed in the computer, the data being received from the input unit, the intermediate and final results
of the program. The primary memory is temporary in nature. The data is lost, when the computer is switched
off. In order to store the data permanently, the data has to be transferred to the secondary memory.
The cost of the primary storage is more compared to the secondary storage. Therefore most computers have
limited primary storage capacity.
2. Secondary Storage: Secondary storage is used like an archive. It stores several programs, documents, data
bases etc. The programs that you run on the computer are first transferred to the primary memory before it is
actually run. Whenever the results are saved, again they get stored in the secondary memory. The secondary
memory is slower and cheaper than the primary memory. Some of the commonly used secondary memory
devices are Hard disk, CD, etc.,

Output Unit: The output unit of a computer provides the information and results of a computation to outside
world. Printers, Visual Display Unit (VDU) are the commonly used output devices. Other commonly used
output devices are floppy disk drive, hard disk drive, and magnetic tape drive.

Arithmetic Logical Unit: All calculations are performed in the Arithmetic Logic Unit (ALU) of the computer.
It also does comparison and takes decision. The ALU can perform basic operations such as addition,
subtraction, multiplication, division, etc and does logic operations viz, >, <, =, ‘etc. Whenever calculations are
required, the control unit transfers the data from storage unit to ALU once the computations are done, the results
are transferred to the storage unit by the control unit and then it is send to the output unit for displaying results.

Control Unit: It controls all other units in the computer. The control unit instructs the input unit, where to store
the data after receiving it from the user. It controls the flow of data and instructions from the storage unit to
ALU. It also controls the flow of results from the ALU to the storage unit. The control unit is generally referred
as the central nervous system of the computer that control and synchronizes its working.

Central Processing Unit:


The control unit and ALU of the computer are together known as the Central Processing Unit (CPU). The CPU
is like brain performs the following functions:
• It performs all calculations.
• It takes all decisions.
• It controls all units of the computer.

Hardware the physical parts of the computer.


Software the programs (instructions) that tell the computer what to do
Data individual facts like first name, price, quantity ordered

features of a computer

Speed A computer can do billions of actions per second.


Reliability Failures are usually due to human error, one way or another. (Blush for us all!)
Storage A computer can keep huge amounts of data.

ALGORITHM
An algorithm is a finite set of instructions, which, if followed, accomplish a particular task. In addition every
algorithm must satisfy the following criteria:
1. Input: there are zero or more quantities which are externally supplied;
2. Output: at least one quantity is produced;
3. Definiteness: each instruction must be clear and unambiguous;
4. Finiteness: if we trace out the instructions of an algorithm, then for all cases the algorithm
will terminate after a finite number of steps;
5. Effectiveness: every instruction must be sufficiently basic that a person using only pencil
and paper can in principle carry it out.

A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get
the solution of a problem.

A flow chart can therefore be used to:

 Define and analyze processes;


 Build a step-by-step picture of the process for analysis, discussion, or communication; and
 Define, standardize or find areas for improvement in a process

Flowcharts are usually drawn using some standard symbols; Some standard symbols, which are frequently
required for flowcharting many computer programs are below:

Start or end of the program

Computational steps or processing function of a program

Input or output operation

Decision making and branching

Connector or joining of two parts of program

Connector or joining of two parts of program

EXAMPLE
ADVANTAGES OF USING FLOWCHARTS

The benefits of flowcharts are as follows:

1. Communication: Flowcharts are better way of communicating the logic of a system to all concerned.
2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which is needed
for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program
development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of
flowchart. It helps the programmer to put efforts more efficiently on that part

OPERATING SYSTEM

An operating system is the most important software that runs on a computer. It controls the memory needed
for computer processes, manages disk space, controls peripheral devices, and allows you to communicate with
the computer without knowing exactly how a computer works

An Operating System is a software that acts as an intermediate between the hardware and the user. It is a
kind of resource manager that manages both hardware and software resources of a system.

Goal of an Operating System:


The fundamental goal of a Computer System is to execute user programs and to make tasks easier. Various
application programs along with hardware system are used to perform this work. Operating System is a software
which manages and control the entire set of resources and effectively utilize every part of a computer.

To achieve the goals of an Operating system, the Operating System performs a number of functionalities.
They are:

 Process Management: At a particular instant of time, the CPU may have a number of processes
that are in the ready state. But at a time, only one process can be processed by a processor. So, the
CPU should apply some kind of algorithm that can be used to provide uniform and efficient access
to resources by the processes
 Memory Management: For the execution of a process, the whole process is put into the main
memory and the process is executed and after the execution of the process, the memory is freed and
that memory can be used for other processes. So, it is the duty of the Operating System to manage
the memory by allocating and deallocating the memory for the process.
 I/O Device Management: There are various I/O devices that are present in a system. Various
processes require access to these resources and the process should not directly access these devices.
So, it is the duty of the Operating System to allow the use of I/O devices by the various process that
are requiring these resources.
 File Mangement: There are various files, folders and directory system in a particular computer. All
these are maintained and managed by the Operating System of the computer

NUMBER SYSTEM.

 Decimal Number System


 It is a base 10 numbering system consisting of 10 numbers . 0,1,2,3,4,5,6,7,8 and 9.
 Also called Denary.
 Represented as (123)10 (here 10 is the radix of a decimal number system)

Binary System

 A number expressed in binary form i.e 0 and 1. It is represented by base 2. eg (10)2


 Computer use this number system for their internal processing.
 1 indicates high voltage and o indicates low voltage.
 1 is yes or on and 0 is no or off.
 Invented by Francis Bacon in 1623 AD

Octal Number System

 Octal means eight which came from Latin “octo”.


 It is a base 8 number system consisting of eight digits 0,1,2,3,4,5,6 and 7.
 The octal system is used in programming as a compact means of representing binary numbers.
 Represented as (23)8

Hexadecimal Number System

 The hexadecimal system used the digits 0 to 9 and the letters A to F to represent the decimal numbers
10 to 15.
 16 digits are used(0,1,2,3,4,5,6,7,8,9,A,B,C,D,E and F)
 It is a base 16 system.
 Represented as (2A)16.
The programming language C was originally developed by Dennis Ritchie at the Bell Laboratories in 1972.

Keywords

C keeps a small set of keywords for its own use. These keywords cannot be used as identifiers in the program

Here is the list of keywords used in Standard C; you will notice that none of them use upper-case letters.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Identifiers

Identifiers:- identifiers are names given to program elements such as variables , arrays & functions. Basically
identifiers are the sequences of alphabets or digits.

Rules for forming identifier name


 the first character must be analphabet (uppercase or lowercase) or an underscore
 all succeeding characters must be letters or digits.
 no special characters or punctuation symbols are allowed except the underscore"_".
 no two successive underscores are allowed.
 keywords shouldn't be used as identifiers.

Variable Names

Informally, a variable (also called an object) is a place you can store a value.

Within limits, you can give your variables and functions any names you want. These names (the formal term is
``identifiers'') consist of letters, numbers, and underscores.

Rules for naming variables (also functions and other C identifiers):

1. 1-31 characters
2. 'a' - 'z', 'A' - 'Z', '0' - '9', and '_' only
3. first character must be a letter
4. cannot be a C keyword
5. case-sensitive
 Constants
 A constant is just an immediate, absolute value found in an expression. The simplest constants are
decimal integers, e.g. 0, 1, 2, 123
Declarations

A declaration tells the compiler the name and type of a variable you'll be using in your program. In its simplest
form, a declaration consists of the type, the name of the variable, and a terminating semicolon:

char c;
int i;
float f;

You can also declare several variables of the same type in one declaration, separating them with commas:

int i1, i2;

A declaration for a variable can also contain an initial value. This initializer consists of an equals sign and an
expression, which is usually a single constant:

int i = 1;
int i1 = 10, i2 = 20;

OPERATORS

Arithmetic Operators

The basic operators for performing arithmetic are the same in many computer languages:

+ Addition

- Subtraction

* Multiplication

/ Division

Modulus
%
(remainder)

Assignment Operators

The assignment operator = assigns a value to a variable. For example,

x=1 sets x to 1
The expression
i=i+1
is, as we've mentioned elsewhere, the standard programming idiom for increasing a variable's value by 1: this
expression takes i's old value, adds 1 to it, and stores it back into i.

c=a=b
which is equivalent to
c = (a = b)
and assigns b's value to both a and c.

x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as follows

Shorthand assignment operators

Statement with Statement with


simple shorthand operator
assignment operator

a=a+1 a += 1

a=a–1 a -= 1

a = a * (n+1) a *= (n+1)

a = a / (n+1) a /= (n+1)

a=a%b a %= b

Relational Operators

Often it is required to compare the relationship between operands and bring out a decision and program
accordingly. This is when the relational operator come into picture. C supports the following relational
operators.

Operato Meaning
r

< is less than

<= is less than or equal to

> is greater than

>= is greater than or equal to

== is equal to

!= is not equal to

It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using relational
operators.

Given below is a list of examples of relational expressions and evaluated values.

6.5 <= 25 TRUE


-65 > 0 FALSE
10 < 7 + 5 TRUE
Logical operators

C has the following logical operators, they compare or evaluate logical and relational expressions.

Operato Meaning
r

&& Logical AND

|| Logical OR

! Logical NOT

Logical AND (&&)

This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the
expressions to the left and to the right of the logical operator is true then the whole compound expression is true.

Example

a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both
expressions are true i.e., if a is greater than b and x is equal to 10.

Logical OR (||)

The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2
expressions is true.

Example

a < m || a < n

The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is
less than either m or n and when a is less than both m and n.

Logical NOT (!)

The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to
false if the expression is true. In other words it just reverses the value of the expression.

For example

! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y

Increment and Decrement Operators

The increment and decrement operators are one of the unary operators which are very useful in C language.
They are extensively used in for and while loops. The syntax of the operators is given below
1. ++ variable name
2. variable name++
3. – –variable name
4. variable name– –

The increment operator ++ adds the value 1 to the current value of operand and the decrement operator – –
subtracts the value 1 from the current value of operand. ++variable name and variable name++ mean the same
thing when they form statements independently, they behave differently when they are used in expression on the
right hand side of an assignment statement.

Consider the following

m = 5;
y = ++m; (prefix)

In this case the value of y and m would be 6

Suppose if we rewrite the above statement as

m = 5;
y = m++; (post fix)

Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and then the
result is assigned to the variable on the left. On the other hand, a postfix operator first assigns the value to the
variable on the left and then increments the operand.

Conditional operators

The conditional operator consists of 2 symbols the question mark (?) and the colon (:)
The syntax for a ternary operator is as follows

exp1 ? exp2 : exp3

The ternary operator works as follows

exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes the value of the
expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression. Note that only
one of the expression is evaluated.

For example

a = 10;
b = 15;
x = (a > b) ? a : b

Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is
assigned to x.
Bitwise Operators

C has a distinction of supporting special operators known as bitwise operators for manipulation data at bit level.
A bitwise operator operates on each bit of data. Those operators are used for testing, complementing or shifting
bits to the right on left. Bitwise operators may not be applied to a float or double.

Operato Meaning
r

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive

<< Shift left

>> Shift right

Expressions

Arithmetic Expressions

An expression is a combination of variables constants and operators written according to the syntax of C
language. In C every expression evaluates to a value i.e., every expression results in some value of a certain type
that can be assigned to a variable. Some examples of C expressions are shown in the table given below.

C Expression
Algebraic Expression
axb–c a*b–c

(m + n) (x + y) (m + n) * (x + y)

(ab / c) a*b/c

3x2 +2x + 1 3*x*x+2*x+1

(x / y) + c x/y+c

Evaluation of Expressions

Expressions are evaluated using an assignment statement of the form


Variable = expression;

Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first and
then replaces the previous value of the variable on the left hand side. All variables used in the expression must
be assigned values before evaluation is attempted.

Example of evaluation statements are

x=a*b–c
y=b/c*a
z = a – b / c + d;

The following program illustrates the effect of presence of parenthesis in expressions.

main ()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (“x = %fn”,x);
printf (“y = %fn”,y);
printf (“z = %fn”,z);
}

output

x = 10.00
y = 7.00
z = 4.00

Precedence in Arithmetic Operators

An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of
operators. There are two distinct priority levels of arithmetic operators in C.

High priority * / %
Low priority + -

Precedence and Order of Evaluation

The precedence and associativity of C operators affect the grouping and evaluation of operands in expressions.
An operator's precedence is meaningful only if other operators with higher or lower precedence are present.
Expressions with higher-precedence operators are evaluated first. Precedence can also be described by the word
"binding." Operators with a higher precedence are said to have tighter binding.
The following table summarizes the precedence and associativity (the order in which the operands are
evaluated) of C operators, listing them in order of precedence from highest to lowest. Where several operators
appear together, they have equal precedence and are evaluated according to their associativity. The operators in
the table are described in the sections beginning with Postfix Operators. The rest of this section gives general
information about precedence and associativity.

Precedence and Associativity of C Operators


Symbol1 Type of Operation Associativity
[ ] ( ) . –> postfix ++ and postfix –– Expression Left to right
prefix ++ and prefix –– sizeof & * + – ~ ! Unary Right to left
typecasts Unary Right to left
*/% Multiplicative Left to right
+– Additive Left to right
<< >> Bitwise shift Left to right
< > <= >= Relational Left to right
== != Equality Left to right
& Bitwise-AND Left to right
^ Bitwise-exclusive-OR Left to right
| Bitwise-inclusive-OR Left to right
&& Logical-AND Left to right
|| Logical-OR Left to right
?: Conditional-expression Right to left
= *= /= %=

+= –= <<= >>=&= Simple and compound assignment2 Right to left

^= |=
, Sequential evaluation Left to right

Type conversions in expressions

Implicit type conversion

C permits mixing of constants and variables of different types in an expression.

C automatically converts any intermediate values to the proper type so that the expression can be evaluated
without loosing any significance. This automatic type conversion is know as implicit type conversion

During evaluation it adheres to very strict rules and type conversion. If the operands are of different types the
lower type is automatically converted to the higher type before the operation proceeds. The result is of higher
type.

The following rules apply during evaluating expressions

All short and char are automatically converted to int then


1. If one operand is long double, the other will be converted to long double and result
.....will be long double.
.
2. If one operand is double, the other will be converted to double and result will be double.
.
3. If one operand is float, the other will be converted to float and result will be float.
.
4. If one of the operand is unsigned long int, the other will be converted into unsigned
.....long int and result will be unsigned long int.
.
5. If one operand is long int and other is unsigned int then
.....a. If unsigned int can be converted to long int, then unsigned int operand will be
..........converted as such and the result will be long int.
.....b. Else Both operands will be converted to unsigned long int and the result will be
..........unsigned long int.
.
6. If one of the operand is long int, the other will be converted to long int and the result will be long int. .
7. If one operand is unsigned int the other will be converted to unsigned int and the
.....result will be unsigned int.

Explicit Conversion

Many times there may arise a situation where we want to force a type conversion in a way that is different from
automatic conversion.

Consider for example the calculation of number of female and male students in a class

........................female_students
Ratio =........-------------------
........................male_students

Since if female_students and male_students are declared as integers, the decimal part will be rounded off and its
ratio will represent a wrong figure. This problem can be solved by converting locally one of the variables to the
floating point as shown below.

Ratio = (float) female_students / male_students

The operator float converts the female_students to floating point for the purpose of evaluation of the expression.
Then using the rule of automatic conversion, the division is performed by floating point mode, thus retaining the
fractional part of the result. The process of such a local conversion is known as explicit conversion or casting a
value. The general form is

(type_name) expression

Input and Output in C

When we say Input, it means to feed some data into a program. An input can be given in the form of a file or
from the command line. C programming provides a set of built-in functions to read the given input and feed it
to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C programming provides
a set of built-in functions to output the data on the computer screen
We can classify I/O function into two categories:

1. Console I/O function


2. File I/O function

Console Input-Output functions

Console simply means screen and keyboard. There are two types of a console I/O functions:
 Formatted input-output function
 Unformatted input-output function

The major difference is that formatted function allows us to format the input from the keyboard and the output
to be displayed on the screen.

We can see that printf( ) and scanf( ) are formatted input/output function.

So let’s discuss printf( ) and scanf( ):

C programming I/O function: printf( )

printf( ) is the standard library function that is used for precise output formatting.

syntax of printf( ) function:


printf( format-control-string, other-arguments );

Format control string in printf( ) function describes the output format which consists of conversion specifiers,
precisions, flags, field widths and literal characters.

Each conversion specifier starts with % sign and ends with a conversion specifier.

scanf( ) is the standard library function that is used for precise input formatting.
syntax of scanf( ) function:
scanf( format-control-string, other-arguments );

Format control string in scanf( ) function describes the input format and other argument are pointers to list of
variables.

Each conversion specifier starts with % sign and ends with a conversion specifier.

CONTROL STRUCTURES

Control structures are used to alter the flow of execution of the program.

 1) Sequence structure (straight line paths)


 2) Selection structure (one or many branches)
 3)Loop structure (repetition of a set of activities
 Sequential: default mode. Sequential execution of code statements (one line after another)
o Selection: used for decisions, branching -- choosing between 2 or more alternative paths.
o if
o if/else
o switch
o Repetition: used for looping, i.e. repeating a piece of code multiple times in a row.
o while
o do/while
o for

Selection structures

Selection structure
Selection structures are used to perform ‘decision making‘ and then branch the program flow based on the
outcome of decision making. Selection structures are implemented in C with If, If Else and Switch statements. If
and If Else statements are 2 way branching statements where as Switch is a multi branching statement.

The simple If statement

The syntax format of a simple if statement is as shown below.

if (expression) // This expression is evaluated. If expression is TRUE statements inside the braces will be
executed
{
statement 1;
statement 2;
}
statement 1;// Program control is transfered directly to this line, if the expression is FALSE
statement 2;

The expression given inside the brackets after if is evaluated first. If the expression is true, then statements
inside the curly braces that follow if(expression) will be executed. If the expression is false, the statements
inside curly braces will not be executed and program control goes directly to statements after curly braces.

#include
void main()
{
int num;
printf("Hello user, Enter a number");
scanf("%d",&num); // Collects the number from user
if(num==1)
{
printf("UNITED STATES");
}
if(num==2)
{
printf("SPAIN");
}
if(num==3)
{
printf("INDIA");
}
}

The If Else statement.

Syntax format for If Else statement is shown below.

if(expression 1)// Expression 1 is evaluated. If TRUE, statements inside the curly braces are executed.
{ //If FALSE program control is transferred to immedate else if statement.

statement1;
statement2;
}
else if(expression 2)// If expression 1 is FALSE, expression 2 is evaluated.
{
statement1;
statement2;
}
else if(expression 3) // If expression 2 is FALSE, expression 3 is evaluated
{
statement1;
statement2;
}
else // If all expressions (1, 2 and 3) are FALSE, the statements that follow this else (inside curly braces) is
executed.
{
statement1;
statement2;
}
other statements;
The execution begins by evaluation expression 1. If it is TRUE, then statements inside the immediate curly
braces is evaluated. If it is FALSE, program control is transferred directly to immediate else if statement. Here
expression 2 is evaluated for TRUE or FALSE. The process continues. If all expressions inside the different if
and else if statements are FALSE, then the last else statement (without any expression) is executed along with
the statements 1 and 2 inside the curly braces of last else statement.

Example program to demo “If Else”

#include
void main()
{
int num;
printf("Hello user, Enter a number");
scanf("%d",&num); // Collects the number from user
if(num==1)
{
printf("UNITED STATES");
}
else if(num==2)
{
printf("SPAIN");
}
else if(num==3)
{
printf("INDIA");
}
else
{
printf("WRONG ENTRY");
}
}

Switch statement

Switch is a multi branching control statement. Syntax for switch statement is shown below.

switch(expression)// Expression is evaluated. The outcome of the expression should be an integer or a character
constant
{
case value1: // case is the keyword used to match the integer/character constant from expression.
//value1, value2 ... are different possible values that can come in expression
statement1;
statement2;
break; // break is a keyword used to break the program control from switch block.
case value2:
statement1;
statement2;
break;
default: // default is a keyword used to execute a set of statements inside switch, if no case values match the
expression value.
statement1;
statement2;
break;
}
Execution of switch statement begins by evaluating the expression inside the switch keyword brackets. The
expression should be an integer (1, 2, 100, 57 etc ) or a character constant like ‘a’, ‘b’ etc. This expression’s
value is then matched with each case values. There can be any number of case values inside a switch statements
block. If first case value is not matched with the expression value, program control moves to next case value and
so on. When a case value matches with expression value, the statements that belong to a particular case
value are executed.

Notice that last set of lines that begins with default. The word default is a keyword in C. When used inside
switch block, it is intended to execute a set of statements, if no case values matches with expression value. So if
no case values are matched with expression value, the set of statements that follow default: will get executed.

Note: Notice the break statement used at the end of each case values set of statements. The word break is
a keyword in Cused to break from a block of curly braces. The switch block has two curly braces { }. The
keyword break causes program control to exit from switch block.

Example program to demo working of “switch”

#include
void main()
{
int num;
printf("Hello user, Enter a number");
scanf("%d",&num); // Collects the number from user
switch(num)
{
case 1:
printf("UNITED STATES");
break;
case 2:
printf("SPAIN");
break;
case 3:
printf("INDIA");
default:
printf("WRONG ENTRY");
}
}

Loop structures

Loop Structure
A loop structure is used to execute a certain set of actions for a predefined number of times or until a particular
condition is satisfied. There are 3 control statements available in C/C++ to implement loop structures. While,
Do while and For statements.

The while statement

Syntax for while loop is shown below:

while(condition)// This condition is tested for TRUE or FALSE. Statements inside curly braces are executed as
long as condition is TRUE
{
statement 1;
statement 2;
statement 3;
}

The condition is checked for TRUE first. If it is TRUE then all statements inside curly braces are executed.Then
program control comes back to check the condition has changed or to check if it is still TRUE. The statements
inside braces are executed repeatedly, as long as the condition is TRUE. When the condition turns FALSE,
program control exits from while loop.

Note:- while is an entry controlled loop. Statement inside braces are allowed to execute only if condition inside
while is TRUE.

#include
void main()
{
int num;
int count=0; // count is initialized as zero to start printing from zero.
printf("Hello user, Enter a number");
scanf("%d",&num); // Collects the number from user
while(count<=num) // Checks the condition - if value of count has reached value of num or not.
{ printf("%d",count); count=count+1; // value of count is incremented by 1 to print next number. } }

The do while statement

Syntax for do while loop is shown below:

do
{
statement 1;
statement 2;
statement 3;
}
while(condition);

Unlike while, do while is an exit controlled loop. Here the set of statements inside braces are executed first. The
condition inside while is checked only after finishing the first time execution of statements inside braces. If the
condition is TRUE, then statements are executed again. This process continues as long as condition is TRUE.
Program control exits the loop once the condition turns FALSE.
Example program to demo working of "do while"

#include
void main()
{
int num;
int count=0; // count is initialized as zero to start printing from zero.
printf("Hello user, Enter a number");
scanf("%d",&num); // Collects the number from user
do
{
printf("%d",count); // Here value of count is printed for one time intially and then only condition is checked.
count=count+1; // value of count is incremented by 1 to print next number.
}while(count<=num); }

The for statement

Syntax of for statement is shown below:

for(initialization statements;test condition;iteration statements)


{
statement 1;
statement 2;
statement 3;
}

The for statement is an entry controlled loop. The difference between while and for is in the number of
repetitions. The for loop is used when an action is to be executed for a predefined number of times. The while
loop is used when the number of repetitions is not predefined.

Working of for loop:

The program control enters the for loop. At first it execute the statements given as initialization statements. Then
the condition statement is evaluated. If conditions are TRUE, then the block of statements inside curly braces is
executed. After executing curly brace statements fully, the control moves to the "iteration" statements. After
executing iteration statements, control comes back to condition statements. Condition statements are evaluated
again for TRUE or FALSE. If TRUE the curly brace statements are executed. This process continues until the
condition turns FALSE.

Note 1:- The statements given as "initialization statements" are executed only once, at the beginning of a for
loop.
Note 2: There are 3 statements given to a for loop as shown. One for initialization purpose, other for condition
testing and last one for iterating the loop. Each of these 3 statements are separated by semicolons.

Example program to demo working of "for loop"

#include
void main()
{
int num,count;
printf("Hello user, Enter a number");
scanf("%d",&num); // Collects the number from user
for(count=0;count<=num;count++)// count is initialized to zero inside for statement. The condition is checked
and statements are executed. { printf("%d",count); // Values from 0 are printed. } }

You might also like