0% found this document useful (0 votes)
35 views23 pages

Wa0012.

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)
35 views23 pages

Wa0012.

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
You are on page 1/ 23

3

INTRODUCTION
Computer

Basically it is a fast calculating machine which is now a days used for


variety of uses ranging from house hold works to space technology. The
credit of invention of this machine goes to the English Mathematician
Charles Babbage.

Types of Computers:

Based on nature, computers are classified into Analog computers and


Digital computers. The former one deals with measuring physical quantities (
concerned with continuous variables ) which are of late rarely used. The
digital computer operates by counting and it deals with the discrete variables.
There is a combined form called Hybrid computer, which has both features.
Based on application computers are classified as special purpose
computers and general computers. As the name tells special computers are
designed to perform certain specific tasks where as the other category is
designed to cater the needs of variety of users.

Basic structure of a digital computer

The main components of a computer are Input unit (IU), Central


Processing unit (CPU) and Output unit (OU). The information like data ,
4

programs etc are passed to the computer through input devices. The
keyboard, mouse, floppy disk, CD, DVD, joystick etc are certain input
devices. The output device is to get information from a computer after
processing . VDU (Visual Display Unit), Printer, Floppy disk, CD etc are
output devices.

The brain of a computer is CPU. It has three components- Memory


unit, Control unit and Arithmetic and Logical unit (ALU)- Memory unit also
called storage device is to store information. Two types memory are there in
a computer. They are RAM (random access memory) and ROM (read only
memory ). When a program is called, it is loaded and processed in RAM.
When the computer is switched off, what ever stored in RAM will be deleted.
So it is a temporary memory. Where as ROM is a permanent memory, where
data, program etc are stored for future use. Inside a computer there is storage
device called Hard disk, where data are stored and can be accessed at any
time.
The control unit is for controlling the execution and interpreting of
instructions stored in the memory. ALU is the unit where the arithmetic and
logical operations are performed.

The information to a computer is transformed to groups of binary


digits, called bit. The length of bit varies from computer to computer, from 8
to 64. A group of 8 bits is called a Byte and a byte generally represents one
alphanumeric ( Alphabets and Numerals) character.
The Physical components of a computer are called hard wares. But
for the machine to work it requires certain programs ( A set of instructions is
called a program ). They are called soft wares. There are two types of soft
wares – System soft ware and Application soft ware – System soft ware
includes Operating systems, Utility programs and Language processors.

ASCII Codes:
American standard code for information interchange. These are binary
codes for alpha numeric data and are used for printers and terminals that are
connected to a computer systems for alphabetizing and sorting.

Operating Systems

The set of instructions which resides in the computer and governs the
system are called operating systems, without which the machine will never
function. They are the medium of communication between a computer and
the user. DOS, Windows, Linux, Unix etc are Operating Systems.

Utility Programs
5

These programs are developed by the manufacturer for the users to do


various tasks. Word, Excel, Photoshop, Paint etc are some of them.

Languages.
These programs facilitate the users to make their own programs.
User’s programs are converted to machine oriented and the computer does
the rest of works.

Application Programs

These programs are written by users for specific purposes.

Computer Languages

They are of three types –


1 Machine Language ( Low level language )
2 Assembly language ( Middle level language )
3 User Oriented language ( Higher level language )

Machine language depends on the hard ware and comprises of 0 and


1 .This is tough to write as one must know the internal structure of the
computer. At the same time assembly language makes use of English like
words and symbols. With the help of special programs called Assembler,
assembly language is converted to machine oriented language. Here also a
programmer faces practical difficulties. To over come this hurdles user
depends on Higher level languages, which are far easier to learn and use. To
write programs in higher level language, programmer need not know the
characteristics of a computer. Here he uses English alphabets, numerals and
some special characters.
Some of the Higher level languages are FORTRAN, BASIC, COBOL,
PASCAL, C, C++, ADA etc. We use C to write programs. Note that Higher
level languages can not directly be followed by a computer. It requires the
help of certain soft wares to convert it into machine coded instructions. These
soft wares are called Compiler, Interpreter, and Assembler. The major
difference between a compiler and an interpreter is that compiler compiles
the user’s program into machine coded by reading the whole program at a
stretch where as Interpreter translates the program by reading it line by line.
C and BASIC are an Interpreter where as FORTRAN is a
6

PROGRAMMING METHODOLOGY

A computer is used to a solve a problem.


Steps
1 Analyze the problem
2 Identify the variables involved
3 Design the solution
4 Write the program
5 Enter it into a computer
6 Compile the program and correct errors
7 Correct the logical errors if any
8 Test the program with data
9 Document the program

Algorithms
Step by step procedure for solving a problem is called
algorithm.

Example
To make a coffee
Step1: Take proper quantity of water in a cooking pan
Step2: Place the pan on a gas stow and light it
Step3: Add Coffee powder when it boils
Step4: Put out the light and add sufficient quantity of sugar and
milk
Step5: Pour into cup and have it.
To add two numbers
Step1: Input the numbers as x, y
Step2: sum=x + y
Step3: print sum

For a better understanding of an algorithm, it is represented pictorially.


The pictorial representation of an algorithm is called a Flow Chart. For
this certain pictures are used.
7

Consider a problem of multiplying two numbers

Algorithm

Step1: Input the numbers as a and b


Step2: find the product a x b
Step3: Print the result
8

Flow chart

In the above example execution is done one after another and straight forward.

But such straight forward problems occur very rarely. Some times we have to

depend on decision making at certain stage in a normal flow of execution. This

is done by testing a condition and appropriate path of flow is selected. For

example consider the following problem

To find the highest of three numbers


Algorithm
Step 1: read the numbers as x ,y and z
Step 2: compare x and y
Step 3: if x > y then compare x with z and find the greater
Step 4: Otherwise compare y with z and find the greater

Flow Chart :
9

Exercise: Write Algorithm and flow chart for the solution to the
problem

1. To find the sum of n, say 10, numbers.


2. To find the factorial of n , say 10.
3. To find the sum of the series 1+x+x2+x3+………. + xn
4. To find the sum of two matrices.
5. To find the scalar product of two vectors
6. To find the Fibonacci series up to n
7. To find gcd of two numbers
10

Chapter 2

C Fundamentals
A brief history of C
C evolved from a language called B, written by Ken Thompson at Bell Labs in
1970. Ken used B to write one of the first implementations of UNIX. B in turn was
a descendant of the language BCPL (developed at Cambridge (UK) in 1967), with
most of its instructions removed.
So many instructions were removed in going from BCPL to B, that Dennis Ritchie
of Bell Labs put some back in (in 1972), and called the language C.
The famous book The C Programming Language was written by Kernighan and
Ritchie in 1978, and was the definitive reference book on C for almost a decade.
The original C was still too limiting, and not standardized, and so in 1983 an ANSI
committee was established to formalise the language definition.
It has taken until now (ten years later) for the ANSI ( American National Standard
Institute) standard to become well accepted and almost universally supported by
compilers

Structure of a program
Every C program consists of one or more modules called functions.
One of these functions is called main. The program begins by executing main
function and access other functions, if any. Functions are written after or before
main function separately. A function has (1) heading consists of name with list of
arguments ( optional ) enclosed in parenthesis, (2) argument declaration (if any) and
(3) compound statement enclosed in two braces { } such that each statement ends
with a semicolon. Comments, which are not executable statement, of necessary can
be placed in between /* and */.

Example
/* program to find the area pf a circle */
#include<stdio.h>
#include<conio.h>
main( )
{
float r, a;
printf(“radius”);
scanf(“%f”, &r);
a=3.145*r*r;
printf(“area of circle=%f”, area);
}
11

The character set


C used the upper cases A,B,…….,Z, the lower cases a ,b,…..,z and certain
special characters like + - * / = % & # ! ? ^ “ ‘ ~ \ < > ( ) = [ ]
{ } ; : . , _ blank space @ $ . also certain combinations of these characters like
\b, \n, \t, etc…

Identities and key words


Identities are names given to various program elements like variables,
arrays and functions. The name should begin with a letter and other charact4rs can
be letters and digits and also can contain underscore character ( _ )
Exapmle: area, average, x12 , name_of_place etc………

Key words are reserved words in C language. They have predicted


meanings and are used for the intended purpose. Standard keywords are 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. (Note that these words
should not be used as identities.)

Data type
The variables and arrays are classified based on two aspects-
first is the data type it stores and the second is the type of storage. The basic data
types in C language are int, char, float and double. They are respectively concerned
with integer quantity, single character, numbers, with decimal point or exponent
number and double precision floating point numbers ( ie; of larger magnitude ).
These basic data types can be augmented by using quantities like short, long, signed
and unsigned. ( ie; long int, short int, long double etc.....).

CONSTANTS
There are 4 basic types of constants . they are int4ger constants, floating-point
constants, character constants and string constants.

(a) integer constants: It is an integer valued numbers, written in three different


number system, decimal (base 10) , octal(base8), and hexadecimal(base 16).

A decimal integer constant consists of 0,1,…..,9..

Example : 75 6,0,32, etc…..


5,784, 39,98, 2-5, 09 etc are not integer constants.

An octal integer constant consists of digits 0,1,…,7. with 1st digit 0 to


indicate that it
is an octal integer.

Example : 0, 01, 0756, 032, etc…..


32, 083, 07.6 etc….. are not valid octal integers.
12

A hexadecimal integer constant consists of 0,1, …,9,A, B, C, D, E, F. It begins with


0x.
Example: 0x7AA2, 0xAB, etc……
0x8.3, 0AF2, 0xG etc are not valid hexadecimal constants.

Usually negative integer constant begin with ( -) sign. An unsigned integer constant
is identified by appending U to the end of the constant like 673U, 098U, 0xACLFU
etc. Note that 1234560789LU is an unsigned integer constant.

( b) floating point constants : It is a decimal number (ie: base 10) with a decimal
point or an exponent or both. Ex; 32.65, 0.654, 0.2E-3, 2.65E10 etc.
These numbers have greater range than integer constants.

(c) character constants : It is a single character enclosed in single quotes like ‘a’.
‘3’, ‘?’, ‘A’ etc. each character has an ASCII to identify. For example ‘A’ has the
ASCII code 65, ‘3’ has the code 51 and so on.

(d) escape sequences: An escape sequence is used to express non printing


character like a new line, tab etc. it begin with the backslash ( \ ) followed by letter
like a, n, b, t, v, r, etc. the commonly used escape sequence are
\a : for alert \n : new line \0 : null
\b : backspace \f : form feed \? : question mark
\f : horizontal tab \r : carriage return \’ : single quote
\v : vertical tab \” : quotation mark

(e) string constants : it consists of any number of consecutive characters enclosed


in double quotes .Ex : “ C program” , “mathematics” etc……

Variables and arrays


A variable is an identifier that is used to represent some specified type of
information. Only a single data can be stored in a variable. The data stored in the
variable is accessed by its name. before using a variable in a program, the data type
it has to store is to be declared.
Example : int a, b, c,
a=3; b=4;
c=a+b

Note : A statement to declare the data types of the identifier is called declaration
statement. An array is an identifier which is used to store a collection of data of the
same type with the same name. the data stored is an array are distinguished by the
subscript. The maximum size of the array represented by the identifier must be
mentioned.
13

Example : int mark[100] .

With this declaration n, mark is an array of size 100, they are identified by nark[0],
mark[1],……….,mark[99].

Note : along with the declaration of variable, it can be initialized too. For example
int x=10;
with this the integer variable x is assigned the value 10, before it is used. Also note
that C is a case sensitive langauge. i.e. the variables d and D are different.

DECLARATIONS
This is for specifying data type. All the variables, functions etc must be declared
before they are used. 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:

Example : int a,b,c;


Float mark, x[100], average;
char name[30];
char c;
int i;
float f;
You may wonder why variables must be declared before use. There are two reasons:
1. It makes things somewhat easier on the compiler; it knows right away what
kind of storage to allocate and what code to emit to store and manipulate
each variable; it doesn't have to try to intuit the programmer's intentions.
2. It forces a bit of useful discipline on the programmer: you cannot introduce
variables willy-nilly; you must think about them enough to pick appropriate
types for them. (The compiler's error messages to you, telling you that you
apparently forgot to declare a variable, are as often helpful as they are a
nuisance: they're helpful when they tell you that you misspelled a variable,
or forgot to think about exactly how you were going to use it.)

EXPRESSION
This consists of a single entity like a constant, a variable, an array or a function
name. it also consists of some combinations of such entities interconnected by
operators.
Example : a, a+b, x=y, c=a+b, x<=y etc……..

STATEMENTS

Statements are the ``steps'' of a program. Most statements compute and assign
values or call functions, but we will eventually meet several other kinds of
statements as well. By default, statements are executed in sequence, one after
another
14

A statement causes the compiler to carry out some action. There are 3 different
types of statements – expression statements compound statements and control
statements. Every statement ends with a semicolon.

Example: (1) c=a + b;


(2) {
a=3;
b=4;
c=a+b;
}

(3) if (a<b)
{
printf(“\n a is less than b”);
}
Statement may be single or compound (a set of statements ).

Most of the statements in a C program are expression statements. An expression


statement is simply an expression followed by a semicolon. The lines
i = 0;
i = i + 1;
and printf("Hello, world!\n");
are all expression statements

SYMBOLIC CONSTANTS

A symbolic constant is a name that substitutes for a sequence of


characters, which represent a numeric, character or string constant. A symbolic
constant is defined in the beginning of a program by using #define, without: at the
end.
Example : #define pi 3.1459
#define INTEREST P*N*R/100

With this definition it is a program the values of p, n ,r are assigned the value of
INTEREST is computed.
Note : symbolic constants are not necessary in a C program.
15

Chapter 3

OPERATORS AND EXPRESSIONS


ARITHMETIC OPERATORS

The basic operators for performing arithmetic are the same in many computer
languages:
+ addition
- subtraction
* multiplication
/ division
% modulus (remainder)

For exponentiations we use the library function pow. The order of precedence of
these operators is % / * + - . it can be overruled by parenthesis.

Integer division :
Division of an integer quantity by another is referred to integer division. This
operation results in truncation. i.e.When applied to integers, the division operator /
discards any remainder, so 1 / 2 is 0 and 7 / 4 is 1. But when either operand is a
floating-point quantity (type float or double), the division operator yields a
floating-point result, with a potentially nonzero fractional part. So 1 / 2.0 is 0.5,
and 7.0 / 4.0 is 1.75.

Example : int a, b, c;
a=5;
b=2;
c=a/b;
Here the value of c will be 2

Actual value will be resulted only if a or b or a and b are declared floating type.
The value of an arithmetic expression can be converted to different data type by the
statement ( data type) expression.
Example : int a, b;
float c;a=5;b=2;
c=(float) a/b

Here c=2.5
Order of Precedence
Multiplication, division, and modulus all have higher precedence than
addition and subtraction. The term ``precedence'' refers to how ``tightly'' operators
bind to their operands (that is, to the things they operate on). In mathematics,
multiplication has higher precedence than addition, so 1 + 2 * 3 is 7, not 9. In
other words, 1 + 2 * 3 is equivalent to 1 + (2 * 3). C is the same way.
16

UNARY OPERATORS

A operator acts up on a single operand to produce a new value is called a unary


operator.
(1) the decrement and increment operators - ++ and -- are unary operators. They
increase and decrease the value by 1. if x=3 ++x produces 4 and –x produces 2.

Note : in the place of ++x , x++ can be used, but there is a slight variation. In
both csse x is incremented by 1, but in the latter case x is considered before
increment.

(2) sizeof is another unary operator


int x, y;
y=sizeof(x);
The value of y is 2 . the sizeof an integer type data is 2 that of float is 4, that of
double is 8, that of char is1.

RELATIONAL AND LOGICAL OPERATORS

< ( less than ), <= (less than or equal to ), > (greater than ), >= ( greater
than or equal to ), = = ( equal to ) and != (not equal to ) are relational operators.

A logical expression is expression connected with a relational operator.


For example ‘b*b – 4*a*c< 0 is a logical expression. Its value is either true or false.

int i, j, k ;
i=2;
j=3 ;
k=i+j ;

k>4 has the value true k<=3 has the value false.

LOGICAL OERATORS

The relational operators work with arbitrary numbers and generate true/false values.
You can also combine true/false values by using the Boolean operators, which take
true/false values as operands and compute new true/false values. The three Boolean
operators are:
&& and
|| or
! not (takes one operand; ``unary'')
The && (``and'') operator takes two true/false values and produces
a true (1) result if both operands are true (that is, if the left-
hand side is true and the right-hand side is true). The || (``or'')
operator takes two true/false values and produces a true (1) result
17

if either operand is true. The ! (``not'') operator takes a single


true/false value and negates it, turning false to true and true to
false (0 to 1 and nonzero to 0).

&& (and ) and || (or) are logical operators which are used to connect logical
expressions. Where as ! ( not) is unary operator, acts on a single logical expression.

For example, 1. (a<5) && (a>-2)


2. (a<=3) || (b>2)
In the first example if a= -3 or a=6 the logical expression returns true.

ASSIGNMENT OPERATORS

These operators are used for assigning a value of expression to another identifier.
=, + =, - = , * =, /= and %= are assignment operators.
a = b+c results in storing the value of b+c in ‘a’.
a += 5 results in increasing the value of a by 5
a /= 3 results in storing the value a/3 in a and it is equivalent a=a/3

Note : 1. if a floating point number is assigned to a integer type data variable, the
value will be
truncated.
Example : float a=5.36;
int b;
b=a
It results in storing 5 to b.
Similarly if an integer value is a assigned to a float type like float x=3 the
value of x
stored is 3.0.

CONDITIONAL OPERATOR

The operator ?: is the conditional operator. It is used as


variable 1 = expression 1 ? expression 2 : expression 3.
Here expression 1 is a logical expression and expression 2 and expression 3 are
expressions having numerical values. If expression 1 is true, value of expression 2
is assigned to variable 1 and otherwise expression3 is assigned.

Example :
int a,b,c,d,e
a=3;b=5;c=8;
d=(a<b)? a : b;
e=(b>c) ? b : c;

Then d=3 and e=8


18

LIBRARY FUNCTIONS

They are built in programs readily available with the C compiler. These function
perform certain operations or calculations. Some of these functions return values
when they are accessed and some carry out certain operations like input, output.a
library functions accessed in a used written program by referring its name with
values assigned to necessary arguments.
Some of these library functions are :
abs(i), ceil(d), cos(d), cosh(d), exp(d), fabs(d),floor(d), getchar( ), log(d),
pow(d,d’),
printf( ), putchar(c), rand( ), sin(d), sqrt(d), scanf( ), tan(d), toascii(c),
toupper(c), tolower(c).

Note : the arguments i, c, d are respectively integer, char and double type.

Example:

#include<math.h>
#include<stdio.h>
#<conio.h>
main( )
{
float x, s;
printf(“ \n input the values of x :”);
scanf(“%f ”, &x);
s=sqrt(x);
printf(“\n the square root is %f ”,s);
}
Note that C language is case sensitive, which means ‘a’ and ‘A’ are
different. Before the main program there are statements begin with # symbol. They
are called preprocessor statements. Within the main program “ float r, a;” is a
declaration statement. ‘include’ is a preprocessor statement. The syntax is
#include<file name>. it is to tell the compiler looking for library functions, which
are used in the program, included in the file, file name ( like stdio.h, conio.h,
math.h, etc…).

CHAPTER-4

DATA INPUT OUTPUT


For inputting and outputting data we use library function .the important of
these functions are getch( ), putchar( ), scanf( ), printf( ), gets( ), puts( ). For using
these functions in a C-program there should be a preprocessor statement
#include<stdio.h>.
[A preprocessor statement is a statement before the main program, which
begins with # symbol.]
19

stdio.h is a header file that contains the built in program of these standard input
output
function.

getchar function
It is used to read a single character (char type) from keyboard. The syntax is
char variable name = getchar( );
Example:
char c;
c = getchar( );
For reading an array of characters or a string we can use getchar( ) function.
Example:
#include<stdio.h>
main( )
{
char place[80];
int i;
for(i = 0;( place [i] = getchar( ))! = ‘\n’, ++i);
}
This program reads a line of text.

putchar function
It is used to display single character. The syntax is
putchar(char c);

Example:
char c;
c = ‘a’;
putchar(c);

Using these two functions, we can write a very basic program to copy the input, a
character at a time, to the output:
#include <stdio.h>

/* copy input to output */

main()
{
int c;

c = getchar();

while(c != EOF)
{
putchar(c);
c = getchar();
}

return 0;
}
20

scanf function
This function is generally used to read any data type- int, char, double, float,
string.
The syntax is

scanf (control string, list of arguments);

The control string consists of group of characters, each group beginning % sign
and a conversion character indicating the data type of the data item. The conversion
characters are c,d,e,f,o,s,u,x indicating the type resp. char decimal integer, floating
point value in exponent form, floating point value with decimal point, octal integer,
string, unsigned integer, hexadecimal integer. ie, “%s”, “%d” etc are such group of
characters.

An example of reading a data:


#include<stdio.h>
main( )
{
char name[30], line;
int x;
float y;
………
…….…
scanf(“%s%d%f”, name, &x, &y);
scanf(“%c”,line);
}

NOTE: 1) In the list of arguments, every argument is followed by & (ampersand


symbol) except
string variable.
2) s-type conversion applied to a string is terminated by a blank space character.
So string having blank space like “Govt. Victoria College” cannot be
read in this manner. For reading such a string constant we use the
conversion string as “%[^\n]” in place of “%s”.
Example:
char place[80];
…………….
scanf(“%[^\n]”, place);
……………..
with these statements a line of text (until carriage return) can be input the variable
‘place’.

printf function
This is the most commonly used function for outputting a data of any type.
The syntax is
21

printf(control string, list of arguments)

Here also control string consists of group of characters, each group having %
symbol and
conversion characters like c, d, o, f, x etc.
Example:

#include<stdio.h>
` main()
{
int x;
scanf(“%d”,&x);
x*=x;
printf(“The square of the number is %d”,x);
}
Note that in this list of arguments the variable names are without &symbol unlike in
the
case of scanf( ) function. In the conversion string one can include the message to be
displayed. In the above example “The square of the number is” is displayed and is
followed by the value of x.For writing a line of text (which include blank spaces)
the
conversion string is “%s” unlike in scanf function. (There it is “[^\n]”).

More about printf statement


There are quite a number of format specifiers for printf. Here are the basic ones :
%d print an int argument in decimal
%ld print a long int argument in decimal
%c print a character
%s print a string
%f print a float or double argument
%e same as %f, but use exponential notation
%g use %e or %f, whichever is better
%o print an int argument in octal (base 8)
%x print an int argument in hexadecimal (base 16)
%% print a single %
To illustrate with a few more examples: the call
printf("%c %d %f %e %s %d%%\n", '1', 2, 3.14, 56000000.,
"eight", 9);
would print
1 2 3.140000 5.600000e+07 eight 9%
The call
printf("%d %o %x\n", 100, 100, 100);
would print
100 144 64
Successive calls to printf just build up the output a piece at a time, so the calls
printf("Hello, ");
printf("world!\n");
would also print Hello, world! (on one line of output).
22

While inputting or outputting data field width can also


be specified.This is included in the conversion string.(if we
want to display a floating point number convert to 3 decimal
places the conversion string is “%.3f”).For assigning field
width,width is placed before the conversion character like
“%10f”,”%8d”,”%12e” and so on…Also we can display data making
correct to a fixed no of decimal places.
For example if we want to display x=30.2356 as 30.24
specification may be “%5.2f” or simply “%.2f”.

CHAPTER – 5

CONTROL STATEMENTS

When we run a program,the statements are executed in the order in which


they appear in the program.Also each statement is executed only once.But in many
cases we may need a statement or a set of statements to be executed a fixed no of
times or until a condition is satisfied.Also we may want to skip some statements
based on testing a condition.For all these we use control statements .
Control statements are of two types – branching and looping.

BRANCHING

It is to execute one of several possible options depending on the


outcome of a logical test ,which is carried at some particular point within a
program.

LOOPING

It is to execute a group of instructions repeatedly,a fixed no of times or


until a specified condition is satisfied.

BRANCHING

1. if else statement

It is used to carry out one of the two possible actions depending


on the outcome of a logical test.The else portion is optional.
The syntax is

If (expression) statement1 [if there is no else part]


Or
If (expression)
23

Statement 1
else
Statement 2

Here expression is a logical expression enclosed in parenthesis.if


expression is true ,statement 1 or statement 2 is a group of statements
,they are written as a block using the braces { }

Example: 1. if(x<0) printf(“\n x is negative”);


2. if(x<0)
printf(“\n x is negative”);
else
printf(“\n x is non negative”);

3.if(x<0)
{
x=-x;
s=sqrt(x);
}
else
s=sqrt(x);

2. nested if statement

Within an if block or else block another if – else statement can


come. Such statements are called nested if statements.

The syntax is

If (e1)
s1
if (e2)
s2
else
s3
else

3. Ladder if statement

Inorder to create a situation in which one of several courses of


action is executed we use ladder – if statements.

The syntax is

If (e1) s1
else if (e2) s2
else if (e3) s3
……………….
else sn
24

Example: if(mark>=90) printf(“\n excellent”);


else if(mark>=80) printf(“\n very good”);
else if(mark>=70) printf(“\n good”);
else if(mark>=60) printf(“\n average”);
else
printf(“\n to be improved”);

SWITCH STATEMENT

It is used to execute a particular group of statements to be chosen


from several available options. The selection is based on the current value of
an expression with the switch statement.

The syntax is:


switch(expression)
{
case value1:
s1
break;
case value 2:
s2
break;
…….
……..
default:
sn
}

All the option are embedded in the two braces { }.Within the block each
group is written after the label case followed by the value of the expression
and a colon. Each group ends with ‘break’ statement. The last may be labeled
‘default’. This is to avoid error and to execute the group of statements in
default if the value of the expression does not match value1, value2,……..

LOOPING

1. The while statement

This is to carry out a set of statements to be executed repeatedly


until some condition is satisfied.

The syntax is:


While (expression) statement

The statement is executed so long as the expression is true. Statement can


be simple or compound.
25

Example 1: #include<stdio.h>
while(n > 0)
{
printf("\n");
n = n - 1;
}

Example 2:

#include<stdio.h>
main()
{
int i=1;
while(x<=10)
{
printf(“%d”,i);
++i;
}
}

2. do while statement

This is also to carry out a set of statements to be executed


repeatedly so long as a condition is true.

The syntax is:


do statement while(expression)

Example: #include<stdio.h>
main()
{
int i=1;
do
{
printf(“%d”,i);
++i;
}while(i<=10);

THE DIFFERENCE BETWEEN while loop AND do – while loop

1) In the while loop the condition is tested in the beginning whereas


in the other case it is done at the end.
2) In while loop the statements in the loop are executed only if the
condition is true.whereas in do – while loop even if the condition is
not true the statements are executed atleast once.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy