0% found this document useful (0 votes)
2 views31 pages

C language Unit-2 Notes

The document outlines the syllabus for the II Semester of I B.Sc. at St. Joseph’s Degree College, focusing on the C programming language. It covers the structure of a C program, decision control and looping statements, data types, variables, constants, and input/output statements. Additionally, it provides instructions on writing, compiling, and executing C programs, along with examples and explanations of key concepts.

Uploaded by

sainaagin123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views31 pages

C language Unit-2 Notes

The document outlines the syllabus for the II Semester of I B.Sc. at St. Joseph’s Degree College, focusing on the C programming language. It covers the structure of a C program, decision control and looping statements, data types, variables, constants, and input/output statements. Additionally, it provides instructions on writing, compiling, and executing C programs, along with examples and explanations of key concepts.

Uploaded by

sainaagin123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc.

, II Semester

Unit – II
Syllabus
Introduction to C: Introduction – Structure of C Program – Writing the first C
Program –File used in C Program – Compiling and Executing C Programs – Using
Comments –Keywords – Identifiers – Basic Data Types in C – Variables – Constants –
I/O Statements in C- Operators in C- Programming Examples.
Decision Control and Looping Statements: Introduction to Decision Control
Statements– Conditional Branching Statements – Iterative Statements – Nested Loops
– Break and Continue Statement – Go to Statement
Introduction to C:

C is a general-purpose programming language that is extremely popular, simple and flexible. It is machine-
independent, structured programming language which is used extensively in various applications.

C was the basic language to write everything from operating systems (Windows and many others) to
complex programs like the Oracle database, Python interpreter and more.

C was developed in the year 1972 in AT-T bell laboratory in Cambridge University in USA It was invented
by “Dennis Ritchie”. It is an out growing of two early language called BCPL (basic combined programming
language) and B which were developed at bell laboratory. C is a general-purpose structured programming
language that is powerful, efficient and compact.

Department of Computer Science Page 1


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Structure of 'C' Program:


The Structure of C Program is having following Sections
Documentation Section
Link Section
Definition Section
Global Declaration Section
main Section ()
{
declaration part;
executable part;
}
Sub-program Section
{
statements;
}
1) Documentation section: The documentation section consists of a set of comment lines giving the name of
the programme like the author name and other details which the programmer would like to use later.
2) Link section: The link section provides instructions to link functions from the system library.
3) Definition section: The definition section defines all symbolic constants.
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
the all functions.
5) main() section: Every 'C' program must have one main function section. This section contains two parts,
declaration part and executable part. The declaration part declares all the variables used in the executable
part. There is at least one statement in executable part. Then two parts must appear between the opening and
the closing phrases [ { } ]. The sub-program section contains all the user-defined functions that are called in
the main function.
Example:
/* programme for adding two numbers */ (Documentation section).
# include < stdio.h > (Link Section).
# define N 100 (pf printf) (Definition Section).
main ( )
{
int a, b, sum; [Declaration part]
printf ("enter two numbers"); [Executable part]
scanf ("%d%d", &a, &b);
sum = a + b;
printf ("%d", sum);
printf ("%d", N);
}

Department of Computer Science Page 2


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Writing the first C-program


#include<stdio.h>
main()
{
printf(“Hello World\n”);
}
Explanation: This program will execute the block of statements in the main section. It prints the message as

O/P (output): Hello World.

#include<stdio.h>: With this line of code we include a file called stdio.h. (Standard Input/Output header
file). commands for input or output which we can use in our program. it has commands for input like
reading from the keyboard and output commands like printing things on the screen.
main():Every program must have a main(). It is the starting point of every program.
{}: The two curly brackets (one in the beginning and one at the end) are used to group all commands
together. In this case all the commands between the two curly brackets belong to main(). The curly brackets
are often used in the C language to group commands together.
printf(“Hello World\n”); : The printf is used for printing things on the screen, The words Hello World are
inside inverted cotations, because they are what is called a string. (A single letter is called a character and a
series of characters is called a string). Strings must always be put between inverted commas. The \n is called
an escape sequence represents a newline character. If there is no \n then a next printf command will print
the string on the same line.
File Used in C Program

Department of Computer Science Page 3


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Source code file: This file includes the source code of the program. The extension for these kinds of files
are .c. It defines the main and many more functions written in C.

Header files: They have the extension .h. they contain the C function declarations and macro definitions
that are shared between various source files.

Common standard header files are:

1) String.h: used to handle string functions


2) Stdlib.h: used for some miscellaneous functions
3) Stdio.h: used for giving standardized input and out put.
4) Math.h: used for mathematical functions
5) Alloc.h: used for dynamic memory allocation
6) Conio.h: used for cleaning the screen.
The header files are added at the start of the source code so that they can be used by more than one function
of the same file.
Object file:
They are the files that are generated by the compiler as the source code file is processed. These files
generally contain the binary code of the function definitions. The object file is used by linker for producing
an executable file for combining the object files together. It has a .o extension.

Executable file: This file is generated by the linker. Various object files are linked by the linker for
producing a binary file which will be executed directly. They have an .exe extension.

[The high-level language is first translated into the target computer’s machine language by the compiler.
The input to the compiler is the source file containing the text of a high-level language.

If the program is syntactically correct, the compiler saves in an object file, the machine language
instructions that carry out the program’s purpose. The object file format is binary. If the source file has
errors, the compiler lists these errors but does not create an object file. The user must correct the errors and
recompile the program

Linker program combines the chunks of code called functions that resides in other object files with the
current object file creating a complete machine language program that is ready to run. We call this as
executable file. The file .exe is just stored on disk.

To run this .exe file LOADER must copy all its instructions into memory and direct the CPU to begin
execution with first instruction.]

Compiling and execution of C program:


How to write C program:
In order to write C program, you must enter into C editor i.e.
1. Double click on “Dosbox”.
2. Defaultly, it shows the last drive, we have to fetch it to C editor drive
Z:\> mount c c:\turboc2 (enter)
3. To go to C drive type as Z:\> C:(enter)

Department of Computer Science Page 4


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

4. To enter into C editor type as ‘.C’ i.e. ‘filename.c’


5. Now you enter into the C editor where we write the C program.

Compilation of C program:

Choose compile menu → Compile (or) shortcut for compilation is ‘Alt+C’ → compile (or) ‘Alt+F9’ for line
by line compilation. After compilation, the C file will exist of ‘filename.obj’.
Execution of C program:

1) After compilation we get the object file which consists of machine code of the program.
2) Choose ‘Run’ menu → execute, for execution of our program (or) shortcut key for execution of our
program is ‘Ctrl+F9’.
To see the output:
After the execution of our program we will see the output by pressing shortcut key ‘Alt+F5’.

Using Comments:
• In C program, we wish not to execute some of the statements of the program can be called as
comments.
• In C programming, comments can be written in 2 ways:
Single line comment: This way of commenting is only for single line source code of the program. The
symbol “//” before the line in the program.
Group of line comment: This way of commenting is used for group of line source code of the program.
The symbol is “/*” and it should be opening and closing.
/* ……………………………
……………………………
………………….............*/

C Tokens:

In C Programming punctuation, individual words, characters etc are called tokens.


Tokens are basic building blocks of C Programming.

Department of Computer Science Page 5


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Keywords:
Keywords are reserved words which cannot be used as variables. There are almost 32
keywords seen in c language as follows,

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 refers to the names of variables,functions,arrays.these are userdefined names and
consists of a sequence of letters & digits.Both uppercase & lowercase letters are permitted although
lowercase letters are commonly used.

Basic Data Types in C:


All 'C' compilers supports four fundamental data types. They are:
1. Character data type.
2. Integer data type.
3. Floating Point data type.
4. Double Floating Point data type.

1. Character Data Type:


A single character can be defined as a character type data. Keyword for character data type is
‘char’.Characters data type 1 byte of storage in the memory.The qualifier signed or unsigned may be

Department of Computer Science Page 6


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

explicitly applied to character data type.The range of character data type is -128 to +127,while unsigned
character is 0 to 255.
Example: char ch;

2. Integer Data Type:


An Integer data type reads only integer type of data. That is whole numbers. Key word for the integer data
type is’int’.Integer data type ocuupy 2bytes of storage in the memory.The range of the integer data type is -
32768 to 32767.The ‘c’ compiler provides three clauses of Integer storage namely short int,int,long int in
both signed and unsigned forms.The unsigned range is 0 to 65535.

3. Floating Point Data Type


In this data type we read real numbers. Keyword for floating point data type is 'float'. It occupies 4 bytes as
storage in the memory. The range of the floating point data type is 3.4E –38 to 3.4E +38.
Example: Float a, b;

4. Double Floating Point Data Type


Keyword for double floating point data type is 'double'. It occupies 0 bytes of storage in memory.The range
of double is 1.7E-308 to +1.7E+308.To extend the precision further,we may use long double which occupies
10 bytes of storage in the memory.The range of long double is 1.7E-4932 to 1.7E+4932.
Example: double x;
long double z;

Variables:

A variable is a data name that may be used to store a data value. A variable may take different values at
different times during execution of the program. A variable name can be chosen by the programmer in a
meaningful way so as to reflect its function and nature in the program. Ex: sum, avg, total, value, x.
Department of Computer Science Page 7
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Some Rules for declaring Variables


1) They must begin with an alphabet.
2) Length should not be more than 8 characters.
3) Upper case and lower case are significant.
4) The variable name should not be a key word or a reserve word.
5) Wide space is not allowed.

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.

“C” constants can be classified as:

1. Numeric Constants
2. Character Constants
3. String Constants

Numeric Constants:

A numeric constant is made of a sequence of numeric digits (0-9).


Integer Constants:-
An integer constant refers to a sequence of digits. There are three types of integers, namely, decimal integer,
octal integer and hexadecimal integer.
Decimal integers consist of a set of digits 0 to 9, preceded by an optional – (or) + sign.
Eg:- 123, -321, 0, 652347, +78
An octal integer constant consists of any combination of digits from the set 0 to 7, with a leading 0(zero).
Eg:- 037, 0 0435, 0551
A sequence of digits preceded by 0X (or) 0x is considered as hexadecimal integer constant. They may also
include alphabets A to F (or) a to f. The letter A to F represent the numbers 10 to 15.
Eg:- 0X2, 0x9F, 0xbcd, 0x

Department of Computer Science Page 8


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Real Constants:-
Integer numbers are inadequate to represent quantities that vary continuously such as distance, heights,
temperatures etc. These quantities are represented by the numbers containing fractional parts like 17.548.
Such numbers are called real (or) floating point constants.
Eg:- 0.0083, -0.75, +247.6

A real number may also be expressed in exponential notation. For example, the value 215.65 may be written
as 2.1565e2 in exponential notation. Here ‘e2’ means multiply by 102.

The general form is mantissa e exponent Ex: 30.0, 30.45, etc

Character Constants:
Any single character enclosed within single quotation marks is termed as a character constant.
Ex: 'A', 'x', 'y'.
String Constants:
A sequence of 0 or more characters surrounded by double quotation marks is termed as string
Constant. Ex: "Computer", "Sudha", "666".

Input/Output Statements In C:

'C' supports the following Input/output Statements:


1. getchar( ) [Input Statement.]
2. putchar( ) [Output Statement.]
3. scanf( ) [Input Statement.]
4. printf( ) [Output Statement.]
❖ getchar():
The getchar() is used to read a single character from the standard input device, that is, keyboard.
Syntax: variable name = getchar();
Example:
char ch;
ch = getchar();
❖ putchar():
The putchar() is used to write or display single character onto the screen.
Syntax: putchar(variable name);
Example:
char ch = 'a';
putchar(ch);
It will display the character 'a' on to the screen.
# include < stdio.h >
main()
{
char ch;
printf("enter a char");

Department of Computer Science Page 9


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

ch = getchar();
printf("typed char is =");
putchar(ch);
}

❖ scanf():
The scanf() is used to read the formatted data items from the keyboard. The format is a userdefined
data item.

Syntax: scanf("control string", argument list);


The control string is a specified format data to be read from the keyboard and the argument list is a
us dataer-defined variables list. The argument list of the user-defined variables must include the address
operator (&) as a prefix to the variable.
Example
1. scanf("%d", &value);
2. char ch; int x; float y;
scanf("%c%d%f", &ch, &x, &y);
❖ printf():
The printf() is used to display the formatted output data items on the standard output device.
Syntax: printf("control string", argument list)
where, control strings are the user-defined format data and the argument list is a set of data itemsto
be displayed in a proper format as defined by the control string. The arguments should match in number,
order and type with format specification.
Example:
1. int x;
printf("%d", x);
2. int x; char y; float z;
printf("%c%d%f", y, x, z);
3. printf("Hello");
4. printf("\n\t");
[\n = new line, \t = tab space]

Operators in c:

'C' operators can be classified as:


1. Arithmetical Operators
2. Relational Operators
3. Logical Operators
4. Increment and Decrement Operators
5. Assignment Operators
6. Conditional Operators
7. Special Operators

Department of Computer Science Page 10


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

✓ Arithmetic Operators:
'C' provides all the basic arithmetic operators. The operators +, -, /, *, % can operate on any built
in data type allowed in 'C'.
Operator Meaning
+ Addition
- Subtraction
/ Division
* Multiplication
% Module Division
The module division (%) operator will take the remainder value and (/) division operator will take
the quotient value.
Example
a + b 10 % 3 = 1
a – b 10 / 3 = 3
✓ Relational Operators:
Relational operators are used to compare the values to see if they are equal or if one of them is greater than
the other and so on. Relational operators in 'C' produce only a one or a zero result. These are often specified
as true or false respectively. 'C' supports six relational operators. They are: <. <=, >, >=, ==, !=
Operator Meaning
> greater than
< less than
>= greaterthan equal
<= lessthan equal
== equalto
!= not equalto
Example:
3 > 4 = false
10 >= 15 = false
10 > 5 = true
✓ Logical Operators:
'C' supports three logical operators. They are:
1. Logical AND (&&)
2. Logical OR (||)
3. Logical NOT (!)
The logical operators && and !! are sued when we want to test more than one condition and make
decision.
OP1 OP2 && ||
T T T T
T F F T
F T F T
F R R F
T = True; F = False
Example
Department of Computer Science Page 11
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

1. a = 4, b = 5, c = 6
(a < b) && (b > c)
(4 < 5) && (5 > 6)
T && T
T
2. (a < b) !! (b > c)
(4 < 5) !! (b > c)
(4 < 5) !! (5 > 6)
T !! F
T
✓ Increment and Decrement Operators:
'C' has two very useful operators not generally found in other languages. These are increment and decrement
operators, ++ and --. These operators are used to control the loops in an effective method.
The ++ operator adds one value to the operators while – operator subtracts one value. These operators are
also called unary operatory.
✓ Increment Operator-The ++ symbol is used for increment by 1 (one).
Example
++i equal to i = i + 1
i++ equal to i = i + 1
There are two types of increment operators.
(a) prefix(++i)
(b) postfix(i++)
In prefix increment operator, first increment the value and do the operation. On the other hand,
the postfix, first do the operation and then increment the value.
Example
i =7; x = ++i; x = i++; x = ?
x = ++7; x = 7++
x = i++ = i + 1 = 7 + 1 = 8
After execution the value of x = 8.
✓ Decrement Operators: The decrement operator is also similar to the increment operators. The –
symbol is used for decrementing by 1.
Example
--i equal to i = i – 1
i—equal to i = i – 1
Here also there are two types of decrements, prefix and postfix decrements.
i = 7; x = --i; x = i--
x = i-- = i = i – 1 = 7 – 1 = 6
After execution the value of x will be 6.

✓ Assignment Operators:
An assignment operator is used to assign a value to a variable. "=" is called an Assignment operator.
Example: a = 10

Department of Computer Science Page 12


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Here, the value 10 will be assigned to a variable known as 'a'.


✓ Conditional Operators:
'C' includes a very special operator called conditional terminating operator. The pair ?: is called the
conditional operator.The general format (Syntax)of the conditional opearator is
Exp1? Exp2: Exp3.
Here, Exp1 is evaluated first. If it is true then the Exp2 is evaluated and it becomes the value of the
expression If Exp1 is false; the Exp3 is evaluated and it becomes the value of the expression.
Example:
a = 10, b = 5
x = (a > b) ! a : b
= 10 > 5
x = 10
After execution the value of x = 10.
✓ Special Operators:
'C' supports some special operators such as comma operator (,), size of operators, pointer opearators(& and
*)and number opearators(. and ).
➢ Operator precedence and association
Each operator in 'C' has a precedence associated with it. This precedence is used to determine how an
expression involving more than one opearator is evaluated.There are distinct levels of precedence and an
operator may belong to one of the levels. . The operators at the higher level of precedence evaluated first.
The operators of the same precedence are evaluated either from left to right or from right to left, depending
on the level. This is known as the association property of an operator.

Operator Precedence
Operator Association Rank
( ), [ ] Left to right 1
++, -- size of Left to right 2
*, /, % Left to right 3
+, - Left to right 4
<, <=, >, >= Left to right 5
==, != Left to right 6
&& Left to right 7
|| Left to right 8
?: Right to left 9
= Right to left 10
, Left to right 11

I. A = 5; b = 6; c = 8
1. a + b * a – c
2. (a + b) * (a – c)
II. 10 + 5/2 * 3
III. i = j = k = 1; m = 2; n = 5; b = 3
(i + j) / k * n % m – 5 * b
Department of Computer Science Page 13
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

I. 1. a + b * a – c
5+6*5–8
5 + 30 – 8 = 35 – 8 = 27
2. (a + b) * (a – c)
(5 + 6) * (5 – 8)
11 * (-3) = -33
II. 10 + 5/2 * 3
10 + 2 * 3 = 10 + 6 = 16
III. i = j = k = 1; m = 2; n = 5; b = 3
(i + j) / k * n % m – 5 * b
2/1 * 5 % 2 – 5 * 3
2*5%2–5*3
10 % 2 – 5 * 3
0 – 15
-15.
✓ Bit-wise Operators:
Bit-wise Operators is used for manipulation of data at bit level. These operators are used for testing the bit
or shifting them right or left. Bit-wise Operators may not be applied to float or double datatype. 'C' supports
the following Bit-wise Operators.
1. Bit-wise AND (&)
2. Bit-wise OR (!)
3. Bit-wise Exclusive (^)
4. Bit-wise Complement (~)
5. Bit-wise Shift
(a) Left Shift (<<)
(b) Right Shift (>>)
❖ Bit-wise AND (&)
The Bit-wise AND Operator is represented by a single ampersand (&) and is surrounded on bothsides by
integer expression. The result of AND operation is one (1) if both bits have a value of one.Otherwise it is 0
(zero).
Example:
x = 5; y = 2
101010
x&y = 000
❖ Bit-wise OR (!):
The bit-wise OR is represented by the Exclamation symbol (!) and is surrounded by two integer operands.
The result of OR operation is 1 if at least one of the bits have a value of 1. Otherwise it is 0(zero).
Example
x = 5; y = 2
101010
x!y = 7 111
❖ Bit-wise Exclusive OR (^):
The bit-wise exclusive OR is represented by the Caret (^) symbol. The result of exclusive OR is

Department of Computer Science Page 14


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

1, if only one of the bits is one otherwise 0 (zero).


Example-1
x = 5; y = 2
101010
x^y 7 111
Example-2
x = 1101 y = 1001
x^y 0100
❖ Bit-wise Complement (~):
The complement operator is also called one's complement operator. It is an unary operator and involves all
the bits represented by its opearand.That is 0's become 1's and 1's become 0's.

Example
x=1010 10 (Decimal value)
~x=0101 5 (Decimal value)
OP1 OP2 & ! ^ ~ OP1 ~ OP2
1 1 1 1 0 0 0
1 0 0 1 1 0 1
0 1 0 1 1 1 0
0 0 0 0 0 1 1
❖ Bit-wise Shift:
The shift operation take binary patterns and shift the bits to the left or right keeping the same number of
by dropping shifted bits on the end and fielding in with 0's from the other and 'C' provides two types of shift
operations. They are:
1. Left Shift (<<) 2. Right Shift (>>)
*Left Shift (<<):Syntax:
op << n;
where, 'op' is the expression and 'n' is the number of bits position to be shifted.
x = y << 1;
This statement shifts one bit to the left in 'y' and then the result is accessing to the 'x'.
Example
x = 10 << 2
1010 = 10
10 << 1 1010 * = 10 * 2
10 << 2 1010 **= 20 * 2 40
252423222120 = 8 + 0 + 32 = 40
*Right Shift (>>):
Syntax
op >> n;
where, 'op' is the integer expression. That is to be shifted and 'n' is the number of bit position to
beshifted.
x = y >> 1;
This statement shift 'y' value one bit to the right and assigns the result to 'x'.

Department of Computer Science Page 15


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Example:
x 10 >> 2
1010
10 >> 1 *1010 = 10/2 = 5
10 >> 2 **1010 = 5/1 = 2.

C programming examples:
We can add lab programs here
❖ INTRODUCTION TO DECISION CONTROL STATEMENTS:

A ‘C’ program is a set of statements which are normally executed sequentially in the order in which they
appear. This happens when no options or no repetitions of certain calculations are necessary. If we have
a number of situations where we may have to change the order of execution of statements based on
certain conditions until certain specified condition is satisfied. This involves a kind of decision making
to see whether a particular condition has occurred or not and then direct the computer to execute certain
statements accordingly.
‘C’ language possesses such decision-making by supporting the following statements:

1. if statement
2. switch statement
3. conditional operator statement
4. goto statement.
The above statements are known as decision-making statements. Since these statement control the
flow of execution, they are also known as control statements.

1. if statement:-
The if statement is a powerful decision-making statement and is used to control the flow of execution
of statements. It is basically a two-way decision statement and is used with an expression. It allows
the computer to evaluate the expression first and then depending on whether the value of expression
is true or false, it transfers the control to a particular statement.
The if statement is divided into four types. They are:

i. simple if statement
ii. if -------- else statement
iii. Nested if ------ else statement
iv. else if ladder
i. Simple if statement:-
The general form of a simple if statement is

if(test condition)

Department of Computer Science Page 16


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Statement-block;

Statement-x;

The “statement-block” may be single statement or a group of statements. If the test condition is true, the
“statement-block” will be executed. Otherwise, the “statement-block” will be skipped and the execution
will jump to the “statement-x”. When the condition is true, then the “statement-block” and “statement-x”
both are executed.

Eg:-

#include<stdio.h>
main()
{
int num;
printf(“enter a number”);
scanf(“%d”,&num);
if(num>=0)
printf(“%d is a positive number\n”,number);
}
Output:
enter a number 6
6 is a positive number

if -else statement: -

The if -else statement is an extension of the simple if statement. The general form is:

if(test expression)
{
True-block statements;
}
else
{
False-block statements;
}
Statement-x;
If the test expression is true, then the true, then the true-block statements are executed and the control is
transferred to the statement-x. If the test expression is false, then the false-block statements are executed
and the control is transferred to the statement-x;

Eg: -

1. WAP to find biggest number among the two numbers.

Department of Computer Science Page 17


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b;
clrscr( );
printf(“\nenter any two numbers”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“\na=%d is biggest number”,a);
else
printf(“\nb=%d is biggest number”,b);
getch();
}
2. WAP to check a given number is even or odd
#include<stdio.h>
#include<conio.h>
void main( )
{
int num;
clrscr( );
printf(“\nenter any number”);
scanf(“%d”,&num);
if((num%2)==0)
printf(“\nThe given number %d is even”,num);
else
printf(“\nThe given number %d is odd”,num);
getch( );
}
ii. Nested if -else statement:-
When a series of decisions are involved, we may have to use more than one if -else statements in nested
form. The general form is:

if(test condition-1)
{
if(test condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-x;

Department of Computer Science Page 18


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

If the condition-1 is false, then the statement-3 will be executed and the control transferred to the statement-
x. If the condition-1 is true, then it continues to perform the second test. If the condition-2 is true, then the
statement-1 will be evaluated and the control transferred to the statement-x. If the condition-2 is false, then
the statement-2 will be evaluated and the control is transferred to the statement-x.

Eg:-

1.WAP to find largest number among the three numbers.

#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c;
printf(“\nenter any three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“\na=%d is largest number”,a);
}
else
{
printf(“\nc=%d is largest number”,c);
}
}
else
{
if(c>b)
{
printf(“\nc=%d is largest number”,c);
}
else
{
printf(“\nb=%d is largest number”,b);
}
}
getch( );
}
2.WAP to calculate average of 3 subject marks and calculate the division as per the following conditions

avg division
>=60 first
>=50 second
>=35 third

Department of Computer Science Page 19


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

<35 fail
#include<stdio.h>
#include<conio.h>
void main( )
{
int m1,m2,m3,avg;
clrscr( );
printf(“\nenter 3 subjects marks”);
scanf(“%d%d%d”,&m1,&m2,&m3);
avg=(m1+m2+m3)/3;
if(avg>=60)
printf(“\nFirst Division”);
else
{
if(avg>=50)
printf(“\nSecond Division”);

else
{
if(avg>=35)
printf(“\nThird Division”);
else
{
printf(“\nFail”);
}
}
getch( );
}
iii. The else if ladder:-
The way of putting ifs together when multipath decisions are involved. A multipath decision is
a chain of ifs in which the statement associated with each else is an if. The general form is:

if(condition-1)

statement-1;

else if(condition-2)

statement-2;

else if(condition-3)

statement-3;

: : : :

: : :

else if(condition-n)

Department of Computer Science Page 20


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

statement-n;

else

default-statement;

statement-x;

The above construct is known as “else if ladder”.The conditions are evaluated from the top to
downwards.As soon as a true condition is found,the statement associated with it is executedand the control
is transfereed to the statement-x,skipping the rest of the ladder. When all the ‘n’ conditions become false,
then the final else containing the default-statement will be executed and the control is transferred to the
statement-x.

Eg:-

1.WAP to check whether the given number is positive,negative or zero?

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a > 0)
{
printf("Given Number is Positive");
}
else if(a == 0)
{
printf("Given Number is Zero");
}
else if(a < 0)
{
printf("Given Number is Negative");
}
getch();
}
2.WAP to accept student number, marks in 3 subjects. Calculate average and display result as per the
following conditions:
Average Result
>=75 Distinction
>=60 First
>=50 Second
>=35 Third
Otherwise Fail
#include<stdio.h>
#include<conio.h>
Department of Computer Science Page 21
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

void main( )
{
int sno,m1,m2,m3,tot,avg;
clrscr( );
printf(“\nenter student number, name and marks in three subjects”);
scanf(“%d%d%d%d”,&sno,&m1,&m2,&m3);
tot=m1+m2+m3;
avg=tot/3;
clrscr( );
printf(“\nNumber :%d”,sno);
printf(“\nM1:%d\tM2 :%d\t M3 :%d”,m1,m2,m3);
printf(“\nTotal : %d”,tot);
printf(“\nAverage :%d”,avg);
printf(“\nResult :”);
if(avg>=75)
printf(“Distinction”);
else if(avg>=60)
printf(“First class”);
else if(avg>=50)
printf(“Second class”);
else if(avg>=35)
printf(“Third class”);
else
printf(“Fail”);
getch( );
}
2.The Switch statement:-

When one of the many alternatives is to be selected, then we can use if statement to control the
selection. When the number of alternatives increases then the program will become difficult to read and
follow.

‘C’ has a built-in multiway decision statement known as a switch. The general form is as
follows:

switch(expression)
{
case value-1 : block-1;
break;
case value-2 : block-2;
break;
case value-3 : block-3;
break;
: : :
: : :
default : default-statements;
}
Statement-x;

Department of Computer Science Page 22


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

The expression is an integer expression or characters. Value-1,value-2,------- are constants or constant


expressions. And are known as “case labels”, block-1,block-2,---- are statement lists and may contain zero or more
statements.

When the switch is executed, the value of the expression is successfully compared against the values

value-1, value-2, ------- If a case is found whose value matches with the value of the expression, then the
block of statements that follow are executed.

The “break” statement at the end of each block signals the end of a particular case and causes an exit
from the switch statement, transferring the control to the statement-x.

The “default” is an optional case. It will be executed if the value of the expression does not match
with any of the case values and the control goes to the statement-x.

Eg:-

1. WAP to display the name of the day depending upon the number which is entered by the user using
switch statement.

#include<stdio.h>
#include<conio.h>
void main( )
{
int no;
clrscr( );
printf(“\n enter any number between 1 to 7”);
scanf(“%d”,&no);
switch(no)
{
case 1 : printf(“\nMonday”);
break;
case 2 : printf(“\nTuesday”);
break;
case 3 : printf(“\nWednesday”);
break;
case 4 : printf(“\nThursday”);
break;

case 5 : printf(“\nFriday”);
break;
case 6 : printf(“\nSaturday”);
break;
case 7 : printf(“\nSunday”);
break;
default: printf(“\n enter a correct number”);
}
getch( );
}
Department of Computer Science Page 23
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

2.WAP to check whether the given character is a vowel or not.

#include,stdio.h>
#include<conio.h>
void main( )
{
char ch;
clrscr( );
printf(“\n enter any charcter”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘A’:
case ‘a’: printf(“\n%c is a vowel”,ch);
break;
case ‘E’:
case ‘e’: printf(“\n%c is a vowel”,ch);
break;
case ‘I’:
case ‘i’: printf(“\n%c is a vowel”,ch);
break;
case ‘O’:
case ‘o’: printf(“\n%c is a vowel”,ch);
break;
case ‘U’:
case ‘u’: printf(“\n%c is a vowel”,ch);
break;
default : printf(“\n%c is not a vowel”,ch);
}
getch( );
}
3.Conditional Operator(?:) statement:-

The ‘C’ language has an unusual operator, useful for making two-way decisions. This operator is a
combination of “?” and “:” , and takes three operands. This operator is popularly known as the conditional
operator. The general form of the conditional operator is as follows:

Conditional expression ? expression1 : expression2

The conditional expression is evaluated first. If the result is true, expression1 is evaluated and is returned
the value of the conditional expression. Otherwise, expression2 is evaluated and its value is returned. For
example,

if(x<0)

flag=0;

else

Department of Computer Science Page 24


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

falg=1;

can be written as

flag=(x<0)?0:1;

Eg:-

1.WAP to find square of a given number.

#include<stdio.h>
void main( )
{
int isqrd,i;
printf(“\n enter a number”);
scanf(“%d”,&i);
isqrd=(i>0) ? i*i : -(i*i);
printf(“%d squared is %d,i,isqrd);
getch( );
}
4.The goto Statement:-

The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program unconditionally. The general form is as follows:

goto label;

where the label is an identifier that is used to label the target statement to which the control is transferred.

Control may be transferred to anywhere within the current function. The target statement must be labelled,
and a colon must follow the label.

label:

statement;

Each labelled statement within the function must have a unique label i.e., no two statements can have the
same label.

Eg:-

#include<stdio.h>
void main( )
{
int number;
printf(“\nwww.”);
goto x;
y:
printf(“expert”);
goto z;
Department of Computer Science Page 25
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

x:
printf(“C programming”);
goto y;
z:
printf(“.com”);
getch( );
}
❖ Iterative Statements
In looping, a sequence of statements is executed until some conditions for termination of
the loop are satisfied. A program loop consists of two segments, one known as the body of the loop and
the other known as the control statement. The control statement tests certain conditions and then directs
the repeated execution of the statements contained in the body of the loop.

A looping process includes the following four steps:

1. Setting and initialization of a condition variable.


2. Execution of the statements in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.
The ‘C’ language provides three constructs for performing loop operations. They are:

1. The while statement.


2. The do – while statement.
3. The for statement.
1. The while statement:-
The simplest of all the looping structures in ‘C’ is the while statement. The general form is:

while(test condition)

body of the loop

Statements-X;

The test condition is evaluated and if the condition is true, then the body of the loop is executed.
After execution of the body, the test condition is once again evaluated and if it true, then again the body
is executed once again. This process of repeated execution of the body continues until the test condition
becomes false and the control is transferred out of the loop.

Eg:-

#include<stdio.h>
main()
{
int count=1;
Department of Computer Science Page 26
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

while(count<=4)
{
printf(“%d”,count);
count++;
}
}
Output: 1 2 3 4

2. The do – while statement:-


The do – while statement is another repetitive loop used in ‘C’ program. The general form
is as follows:

do

body of the loop

}while(test condition);

Statement-X;

The program proceeds to evaluate the body of the loop first. At the end of the loop, the test
condition in the while statement is evaluated. If the condition is true, then the program continues to
evaluate the body of the loop once again. This process continues as long as the condition is true. When
the condition becomes false, then the loop will be terminated and the control goes to the statement-X.

Eg:

#include<stdio.h>
#include<conio.h>
#include<stdio.h>
main()
{
int j=0;
do
{
printf(“value of a variable j is:%d \n”,j);
j++;
}while(j<=3);
}
Output: value of a variable j is 0
value of a variable j is 1
value of a variable j is 2
value of a variable j is 3
3. The for statement:-
The for loop is most commonly used looping statement in ‘C’. This loop consists of three
expressions. The first expression is used to initialize the index value, the second expression is used to

Department of Computer Science Page 27


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

check whether or not the loop is to be continued again and the third expression is used to change the
index value for further iteration. The general form is as follows:

for(initialization;test condition;re-initialization)

body of the loop

Eg:-
#include<stdio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
printf(“%d”,i);
}
}
Output: 1 2 3 4 5 6 7 8 9 10

Nested Loops:

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements
inside another loop. Let's observe an example of nesting loops in C.

Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number
of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop;
for example, you can define 'while' loop inside a 'for' loop.

Syntax:

1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while'
loop.

Nested for loop

Syntax:
Department of Computer Science Page 28
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

The nested for loop means any type of loop which is defined inside the 'for' loop.

for (initialization; condition; update)


{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}

Example:
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
❖ Break and Continue Statement: -
The break statement in C programming has the following two usages −

• When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.

• It can be used to terminate a case in the switch statement (covered in the next chapter).

If you are using nested loops, the break statement will stop the execution of the innermost loop and start
executing the next line of code after the block.

Syntax
The syntax for a break statement in C is as follows:

break;

Department of Computer Science Page 29


St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

Eg:

#include<stdio.h>
main()
{
int num=0;
while(num<=100)
{
printf(“value of variable num is %d\n”,num);
if(num==2)
{
break;
}
num++;
}
printf(“out of while loop”);
}
Continue statement: -

The continue statement in C programming works somewhat like the break statement. Instead of
forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.

For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control to pass to the
conditional tests.

Syntax

The syntax for a continue statement in C is as follows

continue;

#include <stdio.h>
void main( )
{
int a = 10;
do
{
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );
}
Department of Computer Science Page 30
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester

❖ Goto statement

A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement in the same function

Syntax

The syntax for a goto statement in C is as follows –

goto label;

..

label: statement;

Here label can be any plain text except C keyword and it can be set anywhere in the C program above or
below to goto statement.

Eg:

#include<stdio.h>
main()
{
int n,i=1;
printf(“Enter the number whose table you want to print?”);
scanf(“%d”,&n);
table:
printf(“%d x %d = %d \n”,n,i,num*i);
i++;
if(i<=10)
goto table;
}
Output:
Enter the number whose table you want to print? 10
10x1=10
10x2=20
10x3=30
10x4=40
10x5=50
10x6=60
10x7=70
10x8=80
10x9=90
10x10=100

Department of Computer Science Page 31

You might also like