Module 3
Module 3
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.
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.
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.
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. 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.
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.
Example: The three identifiers SUM, sum, and Sum have different meanings.
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 “arevalue”).
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)
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
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.
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.
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).
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.
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.
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.
+= 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
Example: 1010
& 0110
0010
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,
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.
Example: 1010
^ 0110
1100
Example : If the variable num contains the bit pattern 110011110, then
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.
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
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.
TYPE CASTING
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.
( 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.
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
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.
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);
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.
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.
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.
#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:
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
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
% 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:
% 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
%wc
Example:
i) printf("%c", "A"); A
ii) printf("%4c", "A"); A
iii) printf("%-4c", "A"); A
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 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
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.
scanf("%d",&n);
Example: The following scanf() function
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);
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
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).
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.
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.
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.
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: 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: 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");
}
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 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
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);
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().
#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
#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.
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);
}
}