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

Module 3

This document provides an introduction to C programming, covering fundamental concepts such as programming definitions, structured programming, and desirable program characteristics. It details the history of the C language, its features, advantages, and the character set, including tokens, keywords, identifiers, variables, and constants. Additionally, it discusses operators in C, classifying them into various types and explaining their functions.
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)
2 views58 pages

Module 3

This document provides an introduction to C programming, covering fundamental concepts such as programming definitions, structured programming, and desirable program characteristics. It details the history of the C language, its features, advantages, and the character set, including tokens, keywords, identifiers, variables, and constants. Additionally, it discusses operators in C, classifying them into various types and explaining their functions.
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

Module 3

Introduction To C Programming and Control Structures

3.1 INTRODUCTION TO PROGRAMMING

Programming is the process of converting the representation of a solution either as an


algorithm or a flowchart into set of instructions in a programming language so that
we get the desired results or output. A programming language is a set of written
commands that instruct the computer hardware to perform specified tasks. Use of these
commands is governed by a set of rules called syntax. A computer program is set of
precise instructions in a particular language that tell the computer what to do.

Design and implementation of a program is characterized by the imposition of a sense


of orderliness, a systematic way of doing things, which we understood in the previous
chapter. This consists of a set of guidelines, rules concepts and practices which, taken
together are given the name structured programming. The basic purpose of structured
programming is to simplify the programming process.

DESIRABLE PROGRAM CHARACTERISTICS

The characteristics described apply to all programming languages and not only to C.
They can be used as useful guidelines to create good and efficient programs.

Simplicity: This aspect makes the program more understanding. Sometimes it


becomes necessary to sacrifice computational efficiency in order to make the
program more understandable.

Clarity: It refers to the overall readability of the program. The more readable a
program the more easily the logic of program can be understood. Clarity can be usually
achieved through a disciplined approach to programming.

Verification and Validation: They form the two important parts of integrity of a
program. Verification relates to finding out whether the program is working according
to our requirements and Validation relates to the accuracy of the calculations and the
accuracy of the answers generated by the program.
Efficiency: This aspect involves the method of using as less system resources as
possible so that the program works as fast as possible.

Modularity: Is an approach to the method of solving a problem. Instead of


approaching the problem as a single task, we break up the problem into sub-tasks
and approach each task individually. The use of this approach enhances many
aspects such as clarity.

THE HISTORY OF C
C is a general-purpose computer programming language developed between 1969 and
1973 by Dennis Ritchie supported by Ken Thompson at the Bell Telephone
Laboratories. The initial development of C occurred at AT&T Bell Labs between 1969
and 1973; according to Ritchie, the most creative period occurred in 1972. It was named
"C" because its features were derived from an earlier language called "B", which
according to Ken Thompson was a stripped-down version of the BCPL (Basic
Combined Programming Language) programming language.
C was not very popular and was mostly confined to Bell Labs. In 1978 Dennis
Ritchie and Brian Kernighan together published a detailed description of the C
language. This provided a proper exposure for the language. With the growing of the
language in early 80s, numerous C compilers were written for computers for all sizes
and environments including Personal Computers. There is no single compiler for C.
Many different organizations have written and implemented C compilers, which
differ from one another to some extent. However, since no standard existed, there
were discrepancies and minor incompatibilities among different versions of the
language. Hence ANSI (American National Standards Institute) established a
committee in 1983 to create a standard for C language. Since then there is a set of
proper guidelines for the language.

FEATURES OF ‘C’ AS A PROGRAMMING LANGUAGE

Modularity: Ability to breakdown a large module or program into smaller


manageable sub modules or parts is called as modularity; this is an important feature
of structured programming languages. Structured programming helps us to organize
and develop a solution in a more efficient manner.

Portability: This feature allows us to install the software in different platforms.


Thus the source code developed on one platform requires a minimum change when
the software is to be loaded in another platform.

Extend ability: Ability to extend the existing software by adding new features such as
types of data, implementing all types of data structures is called as extend ability.

Speed: ‘C’ is also called as middle level language because programs written in ‘c’
language run at the speeds matching to that of the same programs written in
assembly language so ‘c’ language has both the merits of high level and middle
level language and because if this feature it is mainly used in developing system
software.

Flexibility: ‘C’ language has right number of reverse words which allows the
programmers to have complete control on the language. ‘C’ is also called as
programmer’s language since it allows programmers to induce creativeness into the
programmers. It is the standard language for program development on small
machines and microcomputers.

Middle level language: ‘C’ combines the elements of a high language such as easy
debugging, compactness and so on, with the functionalism of the assembly
language. Because of this special feature of the language, it is called as a middle
level language. As a middle level language it allows manipulation of bits, bytes
and addresses. At the same time, it can be used for writing application programs like
any other high level language.

ADVANTAGES OF ‘C’

1. It is a general purpose programming language which can be used to solve a


wide variety of problems.
2. There are a small, fixed number of keywords, including a full set of flow of
control primitives: for, if, while, switch, and do..while.
3. There are a large number of arithmetical and logical operators, such as +,
+=, ++, &, ~, etc.
4. More than one assignment may be performed in a single statement.
5. User-defined data types and compound types are possible.
6. Enumerated types are possible.
7. Strings are not a separate data type, but are conventionally implemented as
arrays of characters.
8. Low-level access to computer memory is possible.
9. A preprocessor performs macro definition, source code file inclusion, and
conditional compilation.
10. There is a basic form of modularity.
11. Complex functionality such as I/O, string manipulation, and mathematical
functions are consistently delegated to library routines.
12. A wide variety of data structures can be implemented.

The ‘C’ Character Set

A character denotes any alphabet, digit or symbols to represent information. The


character set of C identifies the valid alphabets, numbers and special symbols
permitted in C, this includes:

1. Numerals: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
2. Alphabets: a, b, ….z, A, B,. Z
3. Arithmetic Operations: +, -, *, /, %(Mod)
4. Keywords: if, else, while, do, switch, …..

‘C’ Tokens

The basic element that can be recognized by the compiler is called the "token." A token
is source program text that the compiler does not break down into component elements.
The token included in C are:

1. keyword
2. identifier
3. Variables
4. constant
5. operators

Keywords

Keywords are predefined word with special meanings and these meanings cannot be
changed. Keywords should be used only for the purpose for which they have been
defined. Keywords serve as basic building blocks for program statements.
C language supports the use of 32 keywords. The list of all keywords used in C is
listed below. All keywords must be written in lowercase only.

auto double int struct


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

Identifiers

Every person in this world is identified with a name. Similarly every element used in a
program should also be identified. Identifiers are names given to various programming
elements such as variables, arrays, structures, functions and so on.
An identifier in C can be made up of letters, digits and underscore. An identifier
may start with either alphabets or underscore. The underscore is used to make the
identifier easy to read and to mark functions or library members.

Rules to be followed while creating identifiers:

1. The first character of an identifier should always start with an alphabet or an


underscore, which can be followed by either alphabets or digits or certain
symbols.
2. An identifier may be of any length up to 31 characters. Some compilers limit the
length to eight characters.
3. Identifiers can contain both uppercase and lowercase letters. C is case
sensitive, that is, lowercase letters are not converted to uppercase letters
when used in identifiers.

Example: The three identifiers SUM, sum, and Sum have different meanings.

4. Special characters except underscore should not be used in identifiers.


Successive underscores are also not allowed.
5. Identifiers should be single words i.e., blank spaces cannot be included in
identifiers.
6. Reserved words should not be used as identifiers.

Sum Varun’s_addr
Emp_name while _help
Student_address @total sum
Number do-it
age $counter sum0_1
3by2

Variable
A variable is an object or element that may take on any value of a specified type.
Variables are nothing but identifiers, which are used to identify various
programming elements. Each variable in reality represents the name of a memory
location in which a value can be stored. They are used to denote constants, arrays,
functions, structures, unions, files and may other such element used in a program.
Variables represent named storage locations, whose value can be manipulated during program
run. There are two values associated with a variable name:

1. Its data value, stored at some location in memory. This is sometimes referred
to as a variable’s rvalue (pronounced “are­value”).

2. Its location value; that is, the address in memory at which its data value is
stored. This is sometimes referred to as a variable’s lvalue (pronounced “el­
value”).

Following data illustrates the concept of rvalue and lvalue. (The variables X and Y
have been stored at location 65222 and 65224respectively)

Memory address 65222 65223 65224 65225


Data value of variable 128 890
Variable’s name X Y

Figure The rvalue and lvalue of a variable

Example:
Here are some examples of valid variable names.
Name sum total salary
years stud_name num acc_no

Here are some invalid variable names. The reason why each is invalid is written
beside the name.

int keyword
2005exam begins with a numeric character
$total must begin with an
alphabetic character or
underscore
emp name contains a space
Constants

Constants in C refer to fixed values that do not change during the execution of a
program. C supports several types of constants.

1 Numeric Constants
i. Integer Constants
a. Decimal integer constant
b. Octal integer constant
c. Hexadecimal integer constant
ii. Float Constants (Real)
a. Using dot notation
b. Using E (exponent) notation
2 Character Constants
i. Single character constants
ii. String constants
i. Integer Constants

An integer constant refers to a sequence of digits without a decimal point. Thus an


integer is usually referred to as a whole number. Integer constants can be represented in
three different number systems:

Decimal constant : Decimal integers consist of digits from 0 through 9.


Some valid decimal constants are:
134, 9000, 32567, -987
Octal constant : Octal integer consists of digits from 0 through 7. In C the first
digit of an octal number must be a 0 so as to differentiate it from a decimal number.
Some valid octal constants are:
06, 0677, -07564

Hexadecimal constant: Hexadecimal integer consists of digits 0 through 9 and


alphabets from “a” through “f” or “A” through “F”. In C, a hexadecimal constant
must begin with 0x or 0X so as to differentiate it from a decimal number. Some
valid hexadecimal integer constants are:
0x20, 0XA, 0x1AB

ii. Float Constants


Real or floating-point numbers can both an integer part and a fractional part in the
number. They are stored differently from integers. Floating point numbers may be
represented in two forms, either in the decimal form or in the exponent form.

We normally write real numbers with a decimal point, as in 342.34 or 123.78. Both
positive and negative numbers may be represented in this form. Symbols are normally
included only before the integer part and not after the decimal point. It is also
possible for us to omit digits either before or after the decimal point. Some valid
decimal constants are:
18.5, .18, 5.
Very large and very small numbers are represented using the exponent notation. The
exponent notation use the “E” or “e” symbol in the representation of the number. The
number before the “E” is called as the mantissa and the number after forms the
exponent. Some valid exponent constants are:
5.3E-5, -6.79E3, 78e05, 34e-8

The value of the constant 5.3E-5 is equal to 5.3 * 10 –5. The mantissa and the
exponent in this representation can be prefixed with + or – symbols. The mantissa can
be either an integer or a fractional number, but the exponent should always be an
integer.
There are three types of real values used in C float, double and long double. A float provides at
least 6 significant digits after the decimal and usually requires 32 bits of storage. A double
provides at least 10
significant digits after the decimal and usually requires 64 bits of storage. And a long double
provides more significant digits after the decimal and a larger range of values.

iii. Single character constant


A character constant is a literal or any symbol enclosed by apostrophes or single quotes.
Usually, the literal is a single character. For example the first letter of a alphabet is
‘a’ or ‘A’. Character constant can be used in assignment statements or in symbolic
constant definitions.

Example: ch = ’A’;
#define PERIOD ’.’
A character constant is usually a single character. However, C contains a few
special characters that look like two characters but are treated as one character.
They may be used in expressions with single apostrophes around them.

Example: ch = ’\n’; /* A newline character */


They may appear even in symbolic constant definitions.
#define CR ‘\r’ /* A carriage return character */

iv. String Constants


A sequence of characters enclosed between double quotes is called a string
constant. Character constants are enclosed by single apostrophes. String constants
are enclosed by double quotation marks.
Example: “The best way to learn is through practice”
The above given example is a string constant. The double quotation marks are not
a part of the string.
The term #define is used to define symbolic constants. The statements that follow
show the form of the term. Notice that there is no semicolon after a define
statement.
#define TRUE 1
#define PI 3.14159
The #define statements are placed outside the body of the main( ) function.

OPERATORS
Operators are symbols which represent a particular operation or computation and
give a definite value as output. They are mainly applied to variables and constants in
an expression. C++ includes a rich set of operators. An operator is a
language-specific syntactical token that requires an action to be taken. Operators in
C++ can be divided into the following classes:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Unary operators
5. Conditional operators [ Ternary ]
6. Shorthand operators
7. Bitwise operators
8. Assignment operators
9. Other operators

Operators operate on constants and variables which are called operands. Operators
may also be classified based on the number of operands they act on as either:
1. Unary Operators (single operand)
2. Binary Operators (two operands)
3. Ternary Operators (three operands)

Arithmetic Operators
The C++ programming language supports various arithmetic operators for all
floating-point and integer numbers. These operators are + (addition), - (subtraction), *
(multiplication), / (division), and % (modulos).

Operator Syntax Description

+ a+b Adds a and b


- a–b Subtracts b from a
* a*b Multiplies a by b
/ a/b Divides a by b
% a%b Compute the remainder of dividing a
by b

Relational Operators
A relational operator compares two values and determines the relationship between
them. A relational operation generates an output of either true or false.

Operator Syntax Description


> a>b Returns true if a is greater than b
>= a >= b Returns true if a is greater than or equal
to b
< a<b Returns true if a is less than b
<= a <= b Returns true if a is less than or equal to b
== a == b Returns true if a and b are equal
!= a != b Returns true if a and b are not equal

Relational operators often are used with logical or conditional operators to construct
more complex decision making expressions. The Java programming language supports
six logical or conditional operators, five binary and one unary.

Logical Operators
Logical operators are normally used when our action depends on the ouput of
multiple conditions. They can combine the outputs of multiple conditions into a
single output based on certain conditions.

Operator Use Description


&& C1 && C2 Returns true if C1 and C2 are both true
otherwise returns false
|| C1 || C2 Returns true if either C1 or C2 is true
otherwise returns false
! !C Returns true if C is false i.e., negates the output
of the condition.

Unary operators
Unary operators are those operators that act on one data element. The following are
some unary operators:
Operator Syntax Description
++ ++a or a++ Increment operator
-- --a or a-- Decrement operator

The placement of the operator before or after the variable name decides the timing of
the increment and decrement process. For example, in the statement
a = 5;
num = ++a;
This sequence is called pre-increment. Here the value of the variable a is
incremented first and then it is assigned to the variable num.
a = 5;
num = a++;
This sequence is called post-increment. Here the value of the variable a is first
assigned to the variable num then the value of the variable a is incremented.

Ternary operators
Ternary operators are those operators that act on three data elements. The
conditional operator ?: is a ternary operator.
Syntax: (condition) ? expression1 :expression2
Example:largest = (num1>num2) ? num1 :num2;

Here the value after the "?" is assigned to the variable "largest" if the condition "num1 >
num2) is true otherwise the value after the ":" is assigned to the variable.
largest = ( 7>5) ? 7: 5; thus largest will be assigned the value 7
largest = ( 17>55) ? 17: 55; thus largest will be assigned the value 55

Shorthand Operators
These operators are used to reduce the length of an expression and represent it in a
shorter form in a program. They are used also as assignment operators.

Operator Syntax Description

+= a += b Is equivalent to a = a + b
-= a –= b Is equivalent to a = a - b
*= a *=b Is equivalent to a = a * b
/= a /=b Is equivalent to a = a / b
%= a %=b Is equivalent to a = a % b

Bitwise Operators
These operators allow us to perform various operation on the individual bits of a
memory location. A powerful set of bitwise operators makes C++ different from
other high level languages. The inclusion of bitwise operators gives C++ features of
low level languages such as assembly language. They are useful for controlling and
interacting with hardware, other devices, and in performing some mathematical
tasks. Bitwise operators allow you to perform AND, OR and to shift left and shift
right. The bitwise operators are:

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Ones Complement
<< Bit shift left
>> Bit shift right

Bitwise AND(&) operator


The bitwise, or binary, operator AND (&) yields a 1 if the corresponding bits in both
values are 1, otherwise, it yields 0.

Example: 1010
& 0110
0010

The use of AND operator is to check whether a particular bit of an operand is


ON/OFF.

Example: Suppose, from the bit pattern 10111011 of an operand, we want to check
whether bit number 5 is ON(1) or OFF(0). Since we want to check the bit number 5,

the second operand for the AND operation we choose 1*25 which is equal to 32. This
operand can be represented bitwise as 0010 0000.
Then the AND operation would be,

1010 1011 Original bit pattern


& 0010 0000 AND mask
0010 0000 Resulting bit pattern.

The resulting value we get 32, i.e., the value of the second operand. The result
turned out to be 32, since the fifth bit of the first operand was ON.

Bitwise OR ( | ) operator
The inclusive OR is used to make sure a value is 1, which is represented as | . That
is, OR turns bits on. The result of an inclusive OR is a 1 if either (or both) of the
corresponding bits is a 1.

Example : 1010
| 0110
1110

The only bit not set to 0 is the last because neither of the two operands contained a 1
in that position.

Bitwise XOR(^) operator


The bitwise XOR operator (^) also called the exclusive OR operator yields a 1 if the
corresponding bits in one of the values are 1, otherwise, it yields 0.

Example: 1010
^ 0110
1100

Example: 1010 1011


^ 0010 0000
1000 1011

ONE’s complement operator


It reverse the values of all the bits, i.e., all 1’s present in the number are changed
to 0’s and all 0’s are changed to 1’s. For example, one’s complement of 1010 is
0101. Similarly, one’s complement of 1111 is 0000.

Binary equivalent of 65 is 0000 0000 0100 0001


One’s complement of 65 is 1111 1111 1011 1110
One’s complement operator is represented by the symbol ~. Following program
segment shows one’s complement operator in action

Example: Consider the following program


segment num= 16;
num_comp=~num;
The value of num_comp will be 15, because complement of 10000 is 01111.

Right shift operator


Like one’s complement operator ‘right shift operator’ too operates on a single variable. It is
represented by >> and it shifts each bit in the operand to the right. The number of places the bits
are shifted depends on the number following the operand.
Thus, num>>3 would shift all bits three places to the right. Similarly, num >> 5
would shift all bits 5 places to the right.

Example : If the variable num contains the bit pattern 110011110, then

num >> 1 gives 011001111


num >> 3 gives 000110011
num >> 5 gives 000001100

Left shift operator

This is similar to the right shift operator, the only difference being that the bits are
shifted to the left, and for each bit shifted, a 0 added to the right of the number.

Example: If the variable ch contains the bit pattern 11010111, then

ch <<1 gives 10101110


ch <<3 gives 10111000
ch <<5 gives 11100000

Assignment operator
Assignment operator is used to assign the value of either a constant or an
expression to another variable. The format of the assignment statement is as follows:
Syntax : variable = Value or expression;
Example
num=20;
assigns or stores the value 20 in the variable num.

OPERATORS PRECEDENCE IN

Operator precedence determines the grouping of terms in an expression. This affects


how an expression is evaluated. Certain operators have higher precedence than
others, for example, the multiplication operator has higher precedence than the
addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

TYPE CASTING

Converting an expression of a given type into another type is known as type-casting.


They are of two types:
1. Implicit typecasting
2. Explicit typecasting

Implicit typecasting
Implicit conversions do not require any operator. They are automatically performed
when a value is copied to another compatible type.
Example:
short
a=2000; int
b;
b=a;

Here, the value of a has been converted from short to int and we have not had to
specify any type-casting operator. This is known as a standard conversion. Standard
conversions affect fundamental data types, and allow conversions such as the
conversions between
numerical types such as short to int, int to float, double to int and so on and some
pointer conversions. Some of these conversions may imply a loss of precision,

Explicit Typecasting

Explicit conversion happens when the user forces the conversion from one type to
another. C is a strong-typed language. Many conversions, especially those that imply a
different interpretation of the value, require us to do explicit conversion.

In C the term applies to data conversions specified by the programmer, as opposed


to the automatic data conversions we just described. Sometimes a programmer
needs to convert a value from one type to another in a situation where the compiler
will not do automatically. To cast data from one type to another you specify the
new type in parenthesis before the value you want to be converted. For example, to
convert an integer count to float, the cast expression will be;

( float ) count

Suppose you want to cast the product of two integers to a float, you would
code
( float ) (num1 * num2)
Suppose an intermediate result won't fit the unsigned type either. In such a case we
might be able to solve the problem by using cast.

3.2 INPUT AND OUTPUT OPERATION:

INTRODUCTION
Any programming language must have some facility for transfer of data between the
computer and the input-output devices. The C language does not have any built-in input-
output statements. All input and output operations are carried out through function calls such
as printf, putchar, scanf and getchar. This is done to preserve the portability of the
programs from one computer to another. All data transfer operations in C are carried out
using functions available in the standard library. These functions are known as the standard
I/O library. These operations can be classified into two types.
i. Buffered Input/Output
ii. Unbuffered Input/Output

Buffered Input/Output : A buffer is a temporary storage in the memory. The characters


entered at the keyboard(or any other input device) are stored in the buffer until the Enter key
is pressed and then made available to the program as a block of characters. Since a block of
characters are trnaferred at a time, input-output operations take less time on a buffered
system. If any mistakes have been made while entering the data and if the enter key is not
pressed, they can be corrected.

Unbuffered Input/Output : In unbuffered Input/Output, the character which the user enters at the
keybord is made available to the program immediately. Though unbuffered input-output is
not recommended for most programming applications, it proves quite useful in some
interactive programs. Unbuffered input- output is also used to read and write binary data.

The C language is relatively small. The language itself excludes many of the features and
keywords. C makes use of a collection of libraries (i.e., functions and commands available
to the C programmer, but not part of the language). Library functions are included in the
program if actually needed. The result is fast, compact code. The standard input/output
library requires the use of a header file called stdio.h.
Almost every C program begins with the statement

#include <stdio.h>

The include command is a directive that tells the compiler to use the information in the header
file called stdio.h. The initials stdio stands for standard input output, and stdio.h file contains
all the instructions the compiler needs to work with disk files and send information to the
output device.

SINGLE CHARACTER INPUT


getchar( ) : The getchar( ) function is used to get a single character from the keyboard. C
allows you to treat characters as integers and to accept a character as a value for a variable of
type int. The general format of this function is
variable = getchar( ) ;

Example: The code to read a character using getchar( )


function.
To input a character, use either of these formats:

Format I : int ch; Format II : char ch;


ch=getchar(); ch=getchar()
;

The getchar( ) function returns the ASCII value of the key that was pressed. Hence if a lowercase z was
pressed, ch would have the value 122. The ASCII value is an integer data, the appropriate data type is int.
Declare to be of type char and then understandthat is an integer. It is legal to declare ch to be type char but
there are other reasons for declaring ch to be an int.
SINGLE CHARACTER OUTPUT
putchar( ) : The inverse of getchar( ) is putchar(ch) for which ch is the character to output.
The function putchar(x) displays the value of x on the standard output device at the current
cursor position. It accepts a character constant or a character variable whose contnent is to be
displayed as an argument. The general format of this function is

putchar(argument);

Example: The statements


ans= ‘Y’;
putchar(ans
);
will display the charcter ‘Y’ on the screen.

Example: The statement


putchar(‘\n’);
would cause the cursor on the screen to move to beginning of the next line.

Program: A program to read a character from the keyboard and display on the console.

#include <stdio.h>
main()
{
char ch; / * Declare ch as character variable
*/ ch=getchar();
putchar(ch);
}

FORMATTED I/O
C standard library provides two powerful functions for performing formatted input-output.
They are,
printf( ) - for formatted output
scanf( ) - for formatted input
These two functions can read and write data in various formats as specified by the user. Format
specifiers give the format in which the values of the variables are to be input and displayed
according to the type specifiers like int, float etc.

The printf( ) function


Most simple output requires constants. These are readily available via the printf( ) [Link]
allows you to display the contents of several variables in formatted output and to provide text
labels. The simplest is a prompt such as:

printf(“Welcome to the world of C programming“);

This prompt causes the message enclosed inside quotation marks to be printed. The quotation
marks are delimiters and are not printed. This message would leave the cursor at the end of the
line.

A program to illustrate the use of printf( ) function.


#include
<stdio.h> main()
{
printf(“Hello !”);
printf(“Welcome to the world of C programming”);
}

OUTPUT
Hello !Welcome to the world of C programming

If you wish to print second message (i.e., Welcome to the world of C programming ) to the
beginning of the next line, a newline character must be placed inside the quotation marks. For
example,
printf(“Hello !
\n”); or
printf(“\nWelcome to the world of C programming”);

The \n character looks like two characters but is, in fact, a single character. It is the newline character and it
forces the execution of a typewriter like carriagereturn whenever it is found.

A program to use printf( ) and getchar( ) function to pause a program.

#include
<stdio.h> main()
{
printf(“Press any key to
continue “); getchar();
}

The getchar( ) instruction, used here to pause the program until any key is
pressed. The ‘\n’ character is one of several “escape” or ESC characters
used in C.
Conversion strings and specifiers
The printf( ) function is quite flexible. It allows a variable number of arguments, labels and
sophisticated formatting of output. The general form of the printf( ) function is:

Syntax : printf(“conversion string”, argument list);

The conversion string includes all the text labels, escape character and conversion specifiers
required for the desired output. The argument list includes all of the variables to be printed in the
order they are to be printed. There must be a conversion specifier for each variable. The
conversion specifiers are listed in Table 5.2.

Specifier Meaning
%c print a character
%d print a signed decimal integer
%I print a signed integer( same as %d )
%e print float value in exponential form
%f print signed float value
%g print using %e or %f, whichever is smaller
%o print unsigned octal value
%s print a string
%x print hexadecimal integer (unsigned) using lowercase a-f
%X print hexadecimal integer (unsigned) using uppercase A-F
%u print an unsigned integer
%p print a pointer value
%hx hex short
%lo octal long
%ld print a signed long decimal integer

Table Different string specifiers


Format specifiers

In order to print the output in a required manner, C provides various format specifiers begin
with a % sign followed by a number and a conversion specifier. The number can be a
positive or negative integer or a floating point number. The syntax of the format specifier is as
follows :

% - w. p

Where - (minus)left justify the argument


w field width (optional)
. separates field width from precision
p number of places after decimal (precision)

Format specifiers for integers

The format spcifier for integers are

% wd %-wd
right justified left justified

where w is an integer specifying the total width of the output. The defualt output is always
right justified. But the output can be left justified by a negative sign preceding the width
specifier.
Example:

Format specifiers for floating point numbers


The format spcifier for floating point numbers is

% w.p f % - w.p f
right justified left justified
where w represent the total width including the decimal point and p represents the number of
significant digits after the decimal point.
Example: Consider the following declaration
float num = 1234.678 ;
i) printf("%f", num) 1 2 3 4 . 6 7 8 0 0 0
ii) printf("%10.2f", num ) 1 2 3 4 . 6 8
iii) printf("%010.2f", num ) 0 0 0 1 2 3 4 . 6 8
iv) printf("%-10.2f", num ) 1 2 3 4 . 6 8
v) printf("%4.2f", num ) 1 2 3 4 . 6 8
vi) printf("%e", num) 1 . 2 3 4 6 8 e + 0 3
vi) printf("%10.2e", num ) 1 . 2 3 e + 0 3
vi) printf("%-10.2e", num ) 1 . 2 3 e + 0 3

Format specifiers for characters

The format specifier for character is as follows :

%wc
Example:

i) printf("%c", "A"); A
ii) printf("%4c", "A"); A
iii) printf("%-4c", "A"); A

Program: A program to illustrate the use of conversion specifier.


OUTPUT
Number is = 1267
Number is = 1267
Number is = 1267
Number is = 1267
Address of num =
65524
Long integer value = 145687956
Sum value by default =
127.549000
Sum value with two decimal places =
127.55
Sum value in exponential form =
1.275490e+02
Value of ch = A
ASCII value of A is 65

Type conversion can be interesting. These implicit type conversions can be useful, but be
very careful in their use. Full and complete testing of a program is always appropriate.
Consider the following program.
Program: A program to convert decimal to octal and hexadecimal using conversion specifier.
OUTPUT
Number is = 126
Octal equivalent of 126 = 176
Hexadecimal equivalent of 126
= 7e
Hexadecimal equivalent of 126
= 7E

THE scanf( ) FUNCTION

The scanf( ) function is the input function. This function is used to accept data. It can be used to
enter any combination of numerical values, single character and strings. The general format is

Syntax : scanf ("conversion specifiers", argument list );

Where
conversion specifiers : Contains the conversion specifiers and the modifiers in much the
same way that printf() does. All the conversion specifiers are used except the %g. Another
specifier, %h, is available for reading short integers.

argument list : Variable list is actually a list of variable address.


The conversion specifiers and argument list discussed for printf( ) function holds good for scanf( )
function also. However, printf( ) uses variables, constants and expressions in the argument list, whereas scanf(
) uses pointers to variables. A pointer to a variable is the address where the particular data item is to be stored.
This is discussed in detail in the next volume. The name of the variable preceded by the ampersand (&)
symbol gives the address or the pointer to the variable. Therefore, whenever we read in the value of a
variable of the fundamental datatype (int, char, float or double) using scanf( ) function, the variable
name is preceded byan & symbol

Example: To read an integer into the variable n, you might use

scanf("%d",&n);
Example: The following scanf() function

scanf("%7.f, %3d", &average, &count);


This result is a float value of field width 7 being read into average and an integer of field
width 3 being read into the variable count.

BUFFERED INPUT
Usually, input from the standard input device is buffered. That is, the keyboard characters
are stored in a buffer until the return key is pressed. Then the program process the buffer as
the data stream. This makes the difference in how your program treated the input data
stream. Look at the following program segment:
char ch;
ch=getchar();
putchar(ch);

If you have buffered input and type


Hello < return>
the result is
H

because the H is handled to your program as soon as it is typed.

In many instances, programmers prefer buffered input because the backspace key or
delete key can back up and fix typing error.
3.3 CONTROL STRUCTURES

INTRODUCTION
The C programs presented up to this point have a common structure which is reflected in the
order of the execution of the statements. More specifically, the statements in the programs are
executed sequentially, starting with the first statement of the main program and then continuing
with the next statements in order until the last statement is executed.

Structured high-level languages, such as C contain statements that can also alter the flow of a
sequence of instructions. These statements are called as control statements. In this chapter we
will consider a fundamental control structure known as selection. Using selection, statements can
be executed conditionally. That is, if a certain condition is true, then one sequence of statements
will be executed. These types of statements help us to jump from one part of the program to
another. This transfer of control may be based on certain conditions or may be unconditional.

SELECTION STATEMENTS
The selection statements allow to choose the set-of-instructions for execution depending upon an
expression's truth value. C provides two types of selection statements : if and switch. In addition,
in certain circumstances ? operator can be used as an alternative to if statement. The selection
statements are also called conditional statements or decision statements.

THE if STATEMENT
The if statement is the simplest form of selection statement. It is very frequently used in decision
making and altering the flow of program execution. The if structure has four different forms
(Simple if, if-else, Nested if-else and else if ladder). The simpler form of an if statement is

Format I : if ( expression ) statement;


Where expression is any valid C expression (Arithmetic, Relational or Logical). The expression
must be enclosed in parentheses. If the expression evaluates to true i.e. a nonzero value, the
statement is executed, otherwise ignored. Where a statement may consists of simple statement
or a compound statement.
The command says “if this condition is true” then perform the following instructions. If the
condition is false, the computer skips the instruction that is part of the if command, and moves
on to the next instruction in the program.
Example: Consider the following if statement :
if (a >b ) a=a + 2;
b=a+2;
This if statement specifies that when the expression a > b is true, then execute the statement
a=a+2, otherwise, the control of program should goto the statement immediately following it,
that is b=a+2;
Example: if (weight > 1000)
printf("Allowable weight exceeded");
This statement causes the message to be printed only when the variable weight has a value
greater than 1000. C does allow you to take advantage of the fact that the expression is evaluated
as a number. If the expression evaluates to 0, it is false, and if non-zero, the expression is
evaluated as true.
Example: The expression that follows is a common statement in C but is not usually found in
other languages.
if((ch = getchar()) =='\n')
printf("End of line");
First, the expression calls the function getchar(), then the result is assigned to ch. Finally,
the value of ch is examined to see if it is equal to a newline character. The parentheses are
required because
== has a higher precedence than = and you want the assignment operator to take effect before the
relational operator.

Example: Consider the following if statement

if (( average >= 60 ) || (grade =='A') )


printf ("FIRST CLASS");

The message “FIRST CLASS” is written out if average greater thanor equal to 60 or if the grade represents the
character ‘A’ ( or if both conditions are true).

THE if-else STATEMENT


All the examples of if we have seen so far allow you to execute a set of statements if a condition
or expression evaluates to true. What if there is another course of action to be followed if the
expression evaluates to false. There is another form of if that allows for this kind of either or
condition by providing an else clause. The general form of the if-else is

if (expression)
Format II : Statement-1;
else
Statement-2;

If the expression is evaluated as true, i.e., a nonzero value, the Statement-1 is executed, otherwise
Statement-2 is executed. Notice that one statement or the other is always executed, not both.
Both the statements Statement-1 and Statement-2 can be simple or compound.

Example Suppose you want to find the largest of two numbers


NESTED if STATEMENT
The if statement may itself contain another if statement is known as nested if statement. One of
the nested if statement is given below:

if(expression 1)
if(expression 2)
Format III: Statement_1; nested if
else
Statement_2;
else
{
Statement_3;
}

If the expression 1 is false, the Statement 3 will be executed; otherwise it continues to perform
the expression 2. If the expression 2 is true, the Statement-1 will be executed; otherwise the
Statement-2 is evaluated. The if statement may be nested as deeply as you need to nest it. One
block of code will only be executed if two conditions are true. Expression 1is tested first and
then expression 2 is tested.
Example 6.7 :
if (a >b)
if(a>c)
big=a;
The second if statement is nested in the first. The second if condition is tested only when the first
condition is true, so the variable big is assigned only when both conditions are true.

THE else-if LADDER


This construct is an extension of if-else structure. A general else-if ladder selection construct is of
the form:
if(expression-1)
Statement -1;
else if(expression-2)
Format IV : Statement_2;
else if(expression-3)
Statement-3;
...................
...................
else
Statement-n+1;
If expression-1 is true only Statement-1 is executed. The control is transferred to the statement
following Statement-n+1. If expression-1 is false then one of the statements, Statement-2,
Statement-3,..,Statement-n+1, is executed depending upon which expression is true. If expression-
2 is true, then Statement-2 is executed, If expression-3 is true, then Statement-3 is executed and so
on ... . If none of the condition is true, then Statement-n+1 is executed. In each case after statement
execution, control is transferred to the statement following the Statement-n+1.

MULTIWAY DECISIONS - THE switch STATEMENT


Unlike the if, which allows a selection of two alternatives, the switch statement allows a program
to select one statement for execution out of a set of alternatives. During the execution of the
switch statement, only one of the possible statements will be executed; the remaining statements
will be skipped. The format of this statement is:
switch(control expression)
{
case case-label-1 : statement-list-1;
break;
case case-label-2 : statement-list-2;
break;
case case-label-3 : statement-list-3;
break;
case case-label-4 : statement-list-4;
break;
......
default : default block;
}

When the switch statement is executed, the control expression (integer expression or a character
variable) is evaluated first, and the value is compared with the case label (constant) values in the
given order. If a label matches with the value of the control expression, then the control is
transferred directly to the group of statements following that label. If none of the label values with
the value of the control expression, the statement against default is executed. The default is
optional in a switch statement. When it is not present, and the value of the control expression does
not match with the value of any of the case labels, then no action will take place, in this case
control is transferred to the statement that follows the switch construct.
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 that follows the switch
construct.

Example: Consider the following switch statement :


switch ( j )
{
case 1: printf("ONE");
break;
case 2: printf("TWO");
break;
case 3: printf("THREE");
break;
case 4: printf("FOUR");
}

Statements labelled 1 is executed when j = 1 and statement 2 is executed for j = 2. When j = 3 and
4, statements labelled 3 and 4 respectively, are executed.

Example: Consider the following program segment :


a=2;
switch( a )
{
case 1 : printf("Value is one\n ");
break;
case 2 : printf("Value is two\n");
case 3 : printf("Value is three\n");
}

In this example the output is


Value is two
Value is three
because there is no break after case label 2. Consequently, control flows on to the next printf,
regardless of the match. Once a match has been found, each executable statement in the switch
construct is executed in order until either a break statement is encountered or the end of the
switch is reached. The break statement transfers control to the first executable statement after the
switch construct. Example: In the following program segment, the message is displayed when
num is an even number less than 10.

Example: In the following program segment, the message is displayed when num is an even
number less than 10.
switch(num)
{
case 2 :
case 4 :
case 6 :
case 8 : printf("Number is even less than 10");
break;
}

Example: The switch can be used as a keyboard-character filter.


ch=getchar();
switch(ch)
{
case ‘a’ :
case ‘e’ :
case ‘i’ :
case ‘o’ :
case ‘u’ :
printf("Vowel");
break;
default : printf("Error - not a vowel ");
}

Example: Consider the situation where a student's grade is based on the value of a test score using
nested if statements. The preceding code could be rewritten using a switch as :
int n;
n=marks/10; /* divide marks by 10 */
switch(n)
{
case 10 :
case 9 :
case 8 :
case 7 : printf("Distinction");
break;
case 6 : printf("First Class");
break;
case 5 : printf("Second Class");
break;
case 4 : printf("Pass Class");
break;
default : printf("Fails");
}

THE TERNARY OPERATOR ?:


C has an operator that can be used as an alternative to if statement. We have discussed this
operator, the conditional operator ?: in chapter 4. This operator can be used to replace if-else
statement. The general form
if ( expression-1 )
Statements-1;
else
Statements-2;
The above form of if can be alternatively written using ?: as follows:
expression-1 ? Statements-1 : Statements-2 ;
First, expression-1 is evaluated, if it is true, Statements-1 gets executed, otherwise Statements-2
gets executed.

Example: Consider the following statement


if( number % 2==0)
even=1; /* TRUE */
else
even=0; /* FALSE */
1 is assigned to even if number is divisible by 2, and 0 otherwise. This can also be written using
ternary operator(?) in any one of the following form
1. even=(number % 2==0)?1:0;
2. even=(number%2) ?0:1 /* non-zero is true */
in case(2) if number is not divisible by 2, then the expression immediately following the question
mark is used. If number is divisible by 2, then the expression following the colon is used.

The difference between switch and if statements


1. switch can only test for equality whereas if can evaluate a relational or logical expression i.e.,
multiple conditions.
2. The if-else can handle ranges whereas switch cannot. Each switch case label must be a single
value.
3. The if-else statements can handle floating point tests apart from handling integer and character
tests whereas a switch cannot handle floating point tests. The case labels of switch must be an
integer (which includes char also)
4. The switch statement selects its branches by testing the value of same variable (against a set of
constants) whereas the if-else statement use a series of expressions that may involve variables and
complex expressions.

THE goto STATEMENT


Structured programming advocates avoiding the arbitrary transfer of control provided by the goto
statement. The goto statement is a simple statement, used to transfer control from one point in a
program to any other point in that program. This action is called branching. If misused, the goto
can make a program impossible to understand. Its form is

Syntax : goto label;


......
......
label : statement;
Where label is a user defined identifier and can appear either before or after goto. This statement
provides an unconditional jump to the statement indicated by the label. No declaration is required
for the label. The syntax of the label requires a colon (:) after the label.

Example:
LOOP : printf("Mangalore "); .
..............
goto LOOP;
Here LOOP is the label of statement printf("Mangalore"). During running of a program, the flow
of control will jump to the statement immediately following the label LOOP :. This happens
unconditionally.
The goto statement is discouraged in C, because it alters the sequential flow of logic that is the
characteristic of the language.

LOOPS
One of the methods with which it is possible for us to achieve high performance using a computer
is by repeating the execution of identical tasks on different data. For example we may write a
program to add two numbers. The program would be more useful if it was able to perform the
operation more than once. For performing an operation just once it would be better to use a
calculator or even pencil and paper. However when we will have to perform the operation again
and again many times, the effort of using a calculator or pencil and paper would be tedious. A
program would save us many tedious calculations.
A loop is a program construct that causes a statement to be executed again and again. The process
of repeating the execution of a certain set of statements again and again is termed as looping. C
has several such statements that can be used to form loops they are
i. while statement
ii. do-while statement
iii. for statement
The first two types of loops i.e., the while and do-while loops, are used in situations when the
programmer does not know exactly the number of executions. Thus the execution will be repeated
until some condition is satisfied. for loop is normally used when the number of repetitions is
known in advance.

THE while STATEMENT


This structure is also called as the “pre-tested” looping statement. For this statement two different
things must be specified, the statements to be repeated and the condition. In this structure the
checking of a condition is done at the beginning. The condition must be satisfied before the
execution of the statements i.e., the set of statements in the structure(block) is executed again and
again until the test condition is true. If the test condition becomes false control is transferred out of
the structure(block).
The general form of the while statement in C programming language is as follows :
while (test condition)
{
Statement 1;
Statement 2;
……..
}
Statement n+1;

The execution of this statement structure works as follows:


1. The test condition is first evaluated.
2. If the value of the test condition is false then the while statement is terminated and the control
goes out of the structure.
3. If the value of the test condition is true then the statements in the structure is executed and the
control returns to the test condition.
Example:
sum = 0;
count = 1;
while (count < = 100)
{
sum = sum + count;
count ++;
}
printf ("Total sum = %d ", sum);

The program first initializes the value of the variable sum to zero and the value of the variable
count to one. The statements inside the structure find the sum of all numbers from 1 to 100. The
calculated sum is stored in a variable, which is finally displayed. T

THE do-while STATEMENT


This structure is also called as the “post-tested” looping statement. For this statement two different
things must be specified, the statements to be repeated and the condition. In this structure the
checking of a condition is done at the end. The condition must be satisfied for the execution of the
statements after the first instance i.e., the set of statements in the structure is executed again and
again until the test condition is true. If the test condition becomes false control is transferred out of
the structure.
The general form of the do-while statement in C programming language is as follows
do
{
Statements 1;
Statements 2;
……..
} while (test condition);
Statements n+1;
The execution of this statement structure works as follows :
1. The set of statements in the structure (block) is first executed once.
2. The test condition is then evaluated.
3. If the value of the test condition is false then the do-while statement is terminated and the
control goes out of the structure.
4. If the value of the test condition is true then control goes back to the beginning of the structure
and the statements in the structure is executed again.
Example: prod = 1;
count = 1;
do
{
prod = prod * count; count ++;
} while (count < = 100)
printf ("Total product = %d \n", prod);
The program first initializes the value of the variable prod to one and the value of the variable
count to one. The statements inside the structure find the product of all numbers from 1 to 100.
The calculated product is stored in a variable, which is finally displayed.

THE for STATEMENT


for statement is also called as the “fixed execution” looping structure. This structure is normally
used when we know exactly how many times a particular set of statements is to be repeated again
and again. The for statement is a looping control structure which will execute a set of statements a
specified number of times and automatically keep track of the number of ‘passes’ through the set
of statements. for statement can be either used as the increment looping statement or the
decrement looping statement. The general form of the for statement in a programming language is
as follows :
for ( Expression 1; Expression 2; Expression 3 )
{
Statements 1;
Statements 2;
……..
}
statements n+1;
Where
1. Expression 1 represents the initialization expression.
2. Expression 2 represents the expression for the final condition.
3. Expression 3 represents the increment or decrement expression.
The execution of this statement structure works as follows :
1. Expression 1 is first evaluated i.e., the counter variable of the expression is assigned the initial
value.
2. Expression 2 is then executed i.e., the value of the counter variable is checked to see whether it
has exceeded the final value, if not the statements in the structure(block) are executed once.
3. Control is sent back to the beginning of the structure and Expression 3 isevaluated i.e., the value
of the counter variable is either increased or decreased depending on the statement used.
4. Step 2 is repeated again and again until the counter variable exceeds the final value.

Example: The statement uses a for loop to print the numbers 1 through 10 down the screen
for(repeat=1; repeat<=10; repeat++)
printf(“%d\n”,repeat);
When the program first encounters the loop, it sets the value of repeat to 1. It then checks the
condition to see if the value of repeat is less than or equal to 10. Since the condition is true, it will
perform the instruction that is associated with the loop, displaying the value of the variable.
After performing the instruction, it increments the value of repeat by 1, and again checks the
condition. Since the condition is still true, it performs the instruction a second time, displaying the
current value of the variable. The process is repeated until the value of repeat is incremented to
11. The condition repeat <= 10 is then false, so the instruction is not performed and the loop stops.
Example: You can use a for loop without any instructions to place a timed pause in a program:
for( delay=1; delay<=1000; delay++);
Even though there is no instruction, the loop is repeated 1000 times, as the variable named delayis
incremented and then checked against the condition. This repetition pauses the program before
executing the next instruction.
Example: You can use for loop without any start value.
s=0;
for( ; s<=10 ; s++)
printf(“%d\n”,s);

COMPARISON OF THE THREE LOOPING STATEMENTS


C has three types of looping structures(while, do-while and for). These loops can be used in
almost all situations. There are some situations where one loop fits better than the other.
The for loop is appropriate when you know in advance how many times the loop will be executed.
The other two loops while and do-while loops are more suitable in the situations where it is not
known before-hand when the loop will terminate. The while should be preferred when you may
not want to execute the loop body even once, and the do-while loop should be preferred when you
are sure to execute the loop body at least once.
while statement do-while statement for statement
i = 1; i = 1;
while ( i < = 10 ) do for (i = 1; i < = 10; i++)
{ { printf (“%d \n “, i);
printf (“%d \n “, i); printf (“%d \n “, i);
i++; i++;
} } while ( i < = 10 );

JUMP STATEMENTS
The jump statements unconditionally transfer program control within a function . C has four
statements that perform an unconditional branching : goto, return, break, and continue. We can
use goto and return statements any where in the program whereas break and continue are used
inside the loops. In addition to the above four, C provides a standard library function exit( ) that
helps you break out of a program.
The return statement is used to return from a function. This statement will be discussed in II PUC
under chapter 'Functions'. In this section we deal break and continue alongwith the function exit().

THE break STATEMENT


The break statement is used to terminate loops. It can be used within a while, do-while or for
statement. When break is encountered inside any loop, control automatically passes to the first
statement after the loop. This provides a convenient way to terminate the loop if an error or other
irregular condition is encountered. The break statement is simply written as :
break;
Example: To test whether a number is prime or not.
#include<stdio.h>
void main()
{
int num, i, flag;
printf("Enter a number ");
scanf("%d", &num);
flag=1; /* Assume that num is prime */
for (i= 2 ; i <=num / 2 ; i++)
{
if(num % i = = 0)
{
flag=0; /* number is not a prime */
printf("\n Number is not a Prime "); break;
}
}
if (flag == 1)
printf("\n %d is a Prime Number");
}

THE continue STATEMENT


In some programming situations we want to take the control back to the beginning of the loop,
bypassing the statements inside the loop, which have not yet been executed. When the keyword
continue is encountered inside any loop, control automatically passes to the beginning of the loop.
The continue statement is simply written as :
continue;
Program: Program to display all numbers from 1 to n, which are not divisible by 5.

#include<stdio.h>
void main()
{
int i=0, num;
prinf(“ Enter the limit \n “);
scanf(“%d”,&num);
while( i++<= num )
{
if ( i % 5 == 0) /* condition for display */
continue;
else
printf(“%6d”,i);
}
}

OUTPUT
Enter the limit 10
12346789

THE exit() FUNCTION


exit() is a standard library function that comes ready-made with the C compiler. Its purpose is to
terminate the execution of the program. break statement terminates the execution of loop in which
it is written, where as exit() terminates the execution of the program itself. Let us consider the
following program:
Program: To test whether a number is prime or not.

#include<stdio.h>
#include< stdlib.h > /* For exit() function */
void main()
{
int num, i;
printf(“Enter a number “);
scanf(“%d”, &num);
for (i= 2 ; i <=num / 2 ; i++)
{
if(num % i = = 0)
{
printf(“\n Number is not a Prime “);
exit(0);
}
}
printf(“\n %d is a Prime Number”);
}
OUTPUT
Enter a number 14
Number is not a Prime

The above program accepts a number and tests whether it is prime or not. If the number is
divisible by any number from 2 to half of the number, the program displays a message that the
number is not a prime and exits from the program by exit() function. The exit() has been defined
under the header file stdlib.h which must be included in a program that uses exit() function.

THE for LOOP VARIATIONS


NESTED LOOPS
If one looping statement is enclosed in another looping statement then such a sequence of
statements is called as nested loops. If one for statement is performed within another, the
sequence is called as nested-for.
Whenever nested loops are used the inner loop should be completely enclosed by the outer loop
i.e., overlapping of loops is not possible. Also the inside loop is completely repeated for each
repetition of the outside loop.
Program: To generate the following output.
*
**
***
****
#include<stdio.h>
void main()
{
int row, col;
for(row = 1; row <=10; row++) /* outer loop */
{
for(col = 1; col <=row; col++) /* inner loop */
printf(“*”);
printf(“\n”);
}
}

COMMA OPERATOR
By using the comma operator in an expression of a loop, we will be able to combine two
statements that are in the body of the loop into a single expression, which then becomes the action
of the loop. This leaves the body of the loop empty, allowing us to use null statement as its body.
Program: To find the factorial of a non negative number.
#include<stdio.h>
void main()
{
int fact, i, n;
printf(“\n Input a number “);
scanf(“%d”,&n);
if(n<=0)
printf(“ Invalid input ! (Input only non-negative number) \n”);
else
{
for( fact =1, i =1 ; i<=n ; fact *= i , i++ ) ;
printf(“\n Factorial of %d = %d”, n, fact);
}
}

You might also like