Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

M S Ramaiah Institute of Technology, Bangalore

(Autonomous Institute Affiliated to VTU)

Fundamentals of Computing Study Material


for 1st internal test
(Credits: 2:1:0)
I/II Semester
Department of Computer Science and Engineering
Subject Code: CS201

[Type text]
[Type text]
UNIT I
1.4 : Constants, Variables and Data Types

Character Set:
A character denotes any alphabet ,digit or symbols to represent information. The
following are the valid alphabets, numbers and special symbols permitted in C
Numerals: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Alphabets: a, b, ….z, A, B, ……...Z
Arithmetic Operations: +, -, *, /, %(Mod)
Special Characters:

[Type text]
) { } [ ] < >

! $ ? . , : ;

“ & | ^ ~ ` #

blank - _ / * % @

C tokens:
Tokens are individual words and punctuation marks in passage of text. In C, program the
smallest individual units are known as C Tokens. C has Six types of Tokens.
The Tokens are shown in figure.

By Sini Anna Alex, Dept. of Computer Science & Engineering, MSRIT Page 26

[Type text]
Key words:
"Keywords" are words that have special meaning to the C compiler. We cannot redefine
keywords. These words cannot be used as identifier names.

C Language Keyword
Standard ANSI C recognizes the following keywords:
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct

By Sini Anna Alex, Dept. of Computer Science & Engineering, MSRIT Page 27

[Type text]
switch
typedef
union
unsigned
void
volatile
while

Constants:

A "constant" is a number, character, or character string that can be used as a value in a


program. Use constants to represent floating-point, integer, enumeration, or character values that
cannot be modified.
In programming, a constant is a value that never changes. The other type of values that
programs use is variables, symbols that can represent different values throughout the course of a
program.
A constant can be
 a number, like 25 or 3.6

 a character, like a or $
 a character string, like "this is a string"

Integer Constants:
An "integer constant" is a decimal (base 10), octal (base 8), or hexadecimal (base 16)
number that represents an integral value. Use integer constants to represent integer values that
cannot be changed.
Integer constants are positive unless they are preceded by a minus sign (–). The minus
sign is interpreted as the unary arithmetic negation operator. (See Unary Arithmetic Operators
for information about this operator.)
If an integer constant begins with 0x or 0X, it is hexadecimal. If it begins with the digit 0,
it is octal. Otherwise, it is assumed to be decimal.
/* Decimal Constants */

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 28


MSRIT
[Type text]
10
132
32179

/* Octal Constants */
012
0204
076663

/* Hexadecimal Constants */
0xa or 0xA
0x84
0x7dB3 or 0X7DB3

Real Constants:
A real constant must contain a decimal point or an exponent (or both) to distinguish it
from one of integer type. The letter ``E" is used in Fortran to represent ``times 10 to the power
of". For example, the constant 1.234*10-5 is written as ``1.234E-5".

Here are a few examples of valid real constants:


.5 -10. 1E3 +123.456E4 .000001

Dangling decimal points, though permitted, are easily overlooked, and it is conventional
to standardize constants in exponential notation so that there is only one digit before the decimal
point. Using this convention, these values would look like this:
0.5 -10.0 1000.0 1.23456E6 1.0E-6

Character Constants:
Text enclosed in single quotes as in 'a' is a character constant. The type of a character
constant is int. Its value is the ASCII code for the character. Instead of a single character, an
escape sequence can appear between the quotes. Each escape sequence begins with a backslash,

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 29


MSRIT
[Type text]
followed by a character from the following table. A backslash followed by any other character
represents that character.

The special escape sequences are:

\n newline character,

\b backspace character,

\t tab character,

\r return character,

\f form feed character

String Constants:
String constants are sequences of characters enclosed in double quotes. The same
backslash sequences that are used in character constants can be used in string constants. E.g.,
"hello there", "a newline: \n", "a string\nwith multiple\nlines". If a string is long and you want to
break it up across several lines of code, you can put a backslash just before a (real) newline and
the C compiler will throw away both the backslash and the newline,
e.g., printf("A very long help message\
that is more readable if it is broken up over\n\
several lines.\n");
this string contains one real newline (the \n).

Variables:
What is a variable?
A variable is a meaningful name of data storage location in computer memory. When using a
variable you refer to memory address of computer.
Naming Variables
Each variable has a name which is called variable name. The name of variable is also refered as
identifier.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 30


MSRIT
[Type text]
Rules for constructing variable names:
1) A Variable name consists of any combination of alphabets, digits and underscores. Some
compiler allows variable names whole length could be up to 247 characters. Still it would be
safer to stick to the rule of 31 characters. Please avoid creating long variable name as it adds to
your typing effort.
2) The first character of the variable name must either be alphabet or underscore. It should not
start with the digit.
3) No commas and blanks are allowed in the variable name.
4) No special symbols other than underscore are allowed in the variable name. And it is highly
recommend that the variable name should be as meaningful to the programming context as
possible.
Examples for variable names:
Mark1,Section,Student_count

Data types:
In the C programming language, data types refers to an extensive system for declaring
variables of different types.
The C language provides many basic types. Most of them are formed from one of the
four basic arithmetic type identifiers in C (char, int, float and double), and optional specifiers
(signed, unsigned, short, long). All available basic arithmetic types are listed below:

Type Explanation Type Explanation

smallest addressable unit of the same as char,

machine that can contain basic signed char but guaranteed to

character set. It is an integer type. be signed.


Char
Actual type can be either signed or same as char,
unsigned depending on unsigned char but guaranteed to
implementation be unsigned.

short short signed integer type. At least 16 unsigned short same as short,
short int bits in size. unsigned short int but unsigned.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 31


MSRIT
[Type text]
signed short
signed short
int

int basic signed integer type. At least 16 unsigned same as int, but
signed int bits in size. unsigned int unsigned.

long
long int
long signed integer type. At least 32 unsigned long same as long,
signed long
bits in size. unsigned long int but unsigned.
signed long
int

long long same as long

long long int long, but


long long signed integer type. At least unsigned long,
signed long unsigned.
64 bits in size. Specified since the long
long Specified only in
C99 version of the standard. unsigned long long int
signed long C99 version of
long int the standard.

(single precision) floating-point type.


Actual properties unspecified,
Float however on most systems this is IEEE
754 single precision floating point
format.

double precision floating-point type.


Actual properties unspecified,
Double however on most systems this is IEEE
754 double precision floating point
format.

extended precision floating-point


long double type. Actual properties unspecified.
Unlike types float and double, it can

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 32


MSRIT
[Type text]
be either 80-bit floating point format,
the non-IEEE "double-double" or
IEEE 754 quadruple precision
floating-point format if a higher
precision format is provided,
otherwise it is the same as double. See
this page for details.

A. int - data type


int is used to define integer numbers.

{
int Count;
Count = 5;
}

B. float - data type


float is used to define floating point numbers.

{
float Miles;
Miles = 5.6;
}

C. double - data type


double is used to define BIG floating point numbers. It reserves twice the storage for the
number. On PCs this is likely to be 8 bytes.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 33


MSRIT
[Type text]
double Atoms;
Atoms = 2500000;
}

D. char - data type


char defines characters.

{
char Letter;
Letter = 'x';
}

E. Modifiers
The three data types above have the following modifiers.
 short
 long
 signed
 unsigned
The modifiers define the amount of storage allocated to the variable. The amount of storage
allocated is not cast in stone. ANSI has the following rules:

short int <= int <= long int


float <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an
'int' and the 'int' should be less or the same bytes than a 'long int'.

Declaration of variables:
The declaration of a simple variable, the simplest form of a direct declarator, specifies the
variable's name and type.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 34


MSRIT
[Type text]
In order to use a variable in C, we must first declare it specifying which data type we
want it to be. The syntax to declare a new variable is to write the specifier of the desired data
type (like int, float...) followed by a valid variable identifier.

You can use a list of identifiers separated by commas (,) to specify several variables in
the same declaration. All variables defined in the declaration have the same base type.

Syntax:
Data-type v1,v2,…vn;

For example:
int x, y; /* Declares two simple variables of type int */
int const z = 1; /* Declares a constant value of type int */

For example:

int a;
float mynumber;

These are two valid declarations of variables. The first one declares a variable of type int with
the identifier a. The second one declares a variable of type float with the identifier mynumber.
Once declared, the variables a and mynumber can be used within the rest of their scope in the
program.

If you are going to declare more than one variable of the same type, you can declare all of them
in a single statement by separating their identifiers with commas. For example:

int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exactly the same
meaning as:

int a;

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 35


MSRIT
[Type text]
int b;
int c;

The integer data types char, short, long and int can be either signed or unsigned depending on
the range of numbers needed to be represented. Signed types can represent both positive and
negative values, whereas unsigned types can only represent positive values (and zero). This can
be specified by using either the specifier signed or the specifier unsigned before the type name.
For example:

unsigned short int NumberOfSisters;


signed int MyAccountBalance;

By default, if we do not specify either signed or unsigned most compiler settings will assume the
type to be signed, therefore instead of the second declaration above we could have written:

int MyAccountBalance;

with exactly the same meaning (with or without the keyword signed).

An exception to this general rule is the char type, which exists by itself and is considered
a different fundamental data type from signed char and unsigned char, thought to store
characters. short and long can be used alone as type specifiers. In this case, they refer to their
respective integer fundamental types: short is equivalent to short int and long is equivalent
to long int. The following two variable declarations are equivalent:

short Year;
short int Year;

User defined type declarations:

Using typedef
typedef is used to define new data type names to make a program more readable to the
programmer. C provides a facility called typedef for creating new data type names.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 36


MSRIT
[Type text]
Syntax:
typedef data-type newdatatype;
newdatatype variable_list;

For example, the declaration


typedef int Length;
makes the name Length a synonym for int. The type Length can be used in declarations, casts,
etc., in exactly the same ways that the int type can be:
Length len, maxlen;

Using enum:
An enumeration consists of a set of named integer constants. An enumeration type declaration
gives the name of the (optional) enumeration tag and defines the set of named integer identifiers
(called the "enumeration set," "enumerator constants," "enumerators," or "members"). A variable
with enumeration type stores one of the values of the enumeration set defined by that type.
Syntax:
enum identifier { enumerator-list }
enum identifier variable_list;

Example:
enum DAY /* Defines an enumeration type */
{
saturday, /* Names day and declares a */
sunday = 0, /* variable named workday with */
monday, /* that type */
tuesday,
wednesday, /* wednesday is associated with 3 */
thursday,
friday
} workday;

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 37


MSRIT
[Type text]
enum DAY today = wednesday;

Assigning values to variables:

The assignment statement has the following form:


variable = expression
Its purpose is saving the result of the expression to the right of the assignment operator to the
variable on the left.
C provides an assignment operator for this purpose. The function of this operator is to assign
the values or values in variables on right hand side of an expression to variables on the left hand
side.

The syntax of the assignment expression is as follows:


Variable = constant / variable/ expression;
The data type of the variable on left hand side should match the data type of
constant/variable/expression on right hand side with a few exceptions where automatic type
conversions are possible.
Some examples of assignment statements are as follows:
b = c ; /* b is assigned the value of c */
a = 9 ; /* a is assigned the value 9*/
b = c+5; /* b is assigned the value of expr c+5 */

Defining symbolic constants:


A symbolic constant is name that substitute for a sequence of character that cannot be
changed. The character may represent a numeric constant, a character constant, or a string. When
the program is compiled, each occurrence of a symbolic constant is replaced by its corresponding
character sequence. They are usually defined at the beginning of the program. The symbolic
constants may then appear later in the program in place of the numeric constants, character
constants, etc., that the symbolic constants represent.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 38


MSRIT
[Type text]
For example
#define PI 3.141593

#define PI 3.141593 defines a symbolic constant PI whose value is 3.141593. When the program
is preprocessed, all occurrences of the symbolic constant PI are replaced with the replacement
text 3.141593.

Note that the preprocessor statements begin with a #symbol, and are not end with a
semicolon. By convention, preprocessor constants are written in UPPERCASE.
Advantages of using Symbolic Constants are:
• They can be used to assign names to values
• Replacement of value has to be done at one place and wherever the name appears in the text it
gets the value by execution of the preprocessor. This saves time. if the Symbolic Constant
appears 20 times in the program; it needs to be changed at one place only.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 39


MSRIT
[Type text]
2.1 Introduction:

There are operators for assignment, arithmetic functions, logical functions and many more.
These operators generally work on many types of variables or constants, though some are
restricted to work on certain types. Most operators are binary, meaning they take two operands.
A few are unary and only take one operand. Operators can be classified based on the type of
operations they perform. The following are the types of operators available in C,
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment/Decrement operators
6. Conditional operators
7. Special operators

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 40


MSRIT
[Type text]
Arithmetic Operators:

Arithmetic operators include the familiar addition (+), subtraction (-), multiplication (*)
and division (/) operations. In addition there is the modulus operator (%) which gives the
remainder left over from a division operation. Let us look at some examples:
/* Sample Code to show different arithmetic operators*/
#include <stdio.h>
void main()
int a = 100;
int b = 3;
int c;
c = a + b;
printf( "a + b = %dn", c );
c = a - b;
printf( "a - b = %dn", c );
printf( "a * b = %dn", a * b );
c = a / b;
printf( "a / b = %dn", c );
c = 100 % 3;
printf( "a % b = %dn", c );
}

This program gives the following output:

a + b = 103
a - b = 97
a * b = 300
a / b = 33
a%b=1

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 41


MSRIT
[Type text]
In this example we can see that it is not always necessary to assign the result of an
operation to a variable. The multiplication is performed first, then the result is passed to the
printf() function. we see an example of using an operator on constants, with the 100 and 3
replacing the variables of a and b.

If the modulus operator it is the remainder left over when one integral number is divided
by another. For example 45 % 6 is 3 since 6 * 7 is 42 and the remainder is 3. The modulus
operator works only with integral types (char, short, int, etc.). If you try to use it with other types
such as a float or double the compiler will give an error.

So far we have only used integers in our examples. When we use an operator on mixed
types they will be implicitly converted into a common type before the operation is performed.
The result of the operation will also be in the common type. The common type is derived using a
few rules, but generally, a “smaller” operand is converted to the “larger” operand's type. If the
result of the operation is assigned to another variable, the result is converted from the common
type to the type of that variable.

/*Sample Code to show the implicit conversions */

#include <stdio.h>
void main()
{
int a = 65000;
char c = 120;
int iresult;
char cresult;

iresult = a + c;
printf( "a + c = %dn", iresult );

cresult = a + c;
printf( "a + c = %dn", cresult );

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 42


MSRIT
[Type text]
}

The output is:


a + c = 65120
a + c = 96

On the system where this example was run, an int type is a signed 32 bit number, and a
char type is a signed 8 bit number. When the a + c operation is performed, c is converted to an
int and then added to a, resulting in an another int. At the end the result is assigned to a char,
which means the int result must be converted into a char. The binary representation of 65120 is
111111001100000. Truncating this to just the first 8 bits (since a char is 8 bits on this machine)
gives 01100000 which is 96 in decimal.

/* Sample Code to show the implicit conversions*/


#include <stdio.h>
void main( )
{
int a = 4;
float b = 3.14159;
int iresult;
float fresult;
fresult = a * b;
printf( "a * b = %fn", fresult );
iresult = a * b;
printf( "a * b = %dn", iresult );
}

The output is
a * b = 12.566360

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 43


MSRIT
[Type text]
Relational Operators:

Relational operators compare operands and return 1 for true or 0 for false. Following
table shows all the relational operators supported by C language with example assuming variable
A holds 10 and variable B holds 20 .

Operator Description Example

Checks if the value of two operands is equal or


== (A == B) is not true.
not, if yes then condition becomes true.

Checks if the value of two operands is equal or


!= not, if values are not equal then condition becomes (A != B) is true.
true.

Checks if the value of left operand is greater than


> the value of right operand, if yes then condition (A > B) is not true.
becomes true.

Checks if the value of left operand is less than the


< value of right operand, if yes then condition (A < B) is true.
becomes true.

Checks if the value of left operand is greater than


>= or equal to the value of right operand, if yes then (A >= B) is not true.
condition becomes true.

Checks if the value of left operand is less than or


<= equal to the value of right operand, if yes then (A <= B) is true.
condition becomes true.

/* Sample Code to show the relational operators*/


#include <stdio.h>
void main()
{
int x=10,y=20;

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 44


MSRIT
[Type text]
printf( "\n %d < %d”,x,y, x<y);
printf("\n %d == %d”,x,y, x==y);
printf("\n %d != %d”,x,y, x!=y);
printf("\n %d > %d”,x,y, x>y );
printf("\n %d <= %d”,x,y, x<y);
printf("\n %d >= %d”,x,y, x>=y );
}

Output for the above program is


10<20 =1
10= =20 = 0
10!=20 = 1
10>20 = 0
10<=20 = 1
10<=20=0

Logical operators:

A Logical operator is used to compare or evaluate logical and relational expression.


There are three logical operators in C language. They are

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Used to calculate the value of logical expressions, ie expressions thatt can take operands
are True or False. When we simply want to know if an expression is true or false (eg, x>7 ),
these operators do not consider the structure of bits, simply take the value 0 as false and any

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 45


MSRIT
[Type text]
other as true. There is also another version (the bitwise) imposed by the logical operations to the
bits used to internally represent the operands. These are the operators & , | and ~ , respectively.

Suppose that a and b are integer variables whose values are 100 and 4, respectively.
Several arithmetic expressions involving these variables are shown below, together with their
resulting values.

Expression Interpretation Value

(a>b)&&(a==100) True 1

(b>a)||(a>b) True 1

!(a>b) False 0

The following examples illustrate the logical operators:


int w, x, y, z;
if ( x < y && y < z )
printf( "x is less than z\n" );

In this example, the printf function is called to print a message if x is less than y and y is
less than z. If x is greater than y, the second operand (y < z) is not evaluated and nothing is
printed. Note that this could cause problems in cases where the second operand has side effects
that are being relied on for some other reason.

printf( "%d" , (x == w || x == y || x == z) );
In this example, if x is equal to either w, y, or z, the second argument to the printf
function evaluates to true and the value 1 is printed. Otherwise, it evaluates to false and the value
0 is printed. As soon as one of the conditions evaluates to true, evaluation ceases.
Examples for logical operators are discussed in condition statements.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 46


MSRIT
[Type text]
Assignment Operator:
C has several assignment operators available - one simple assignment operator and
several assignment operators that combine arithmetic operations with assignment. The operators
with their symbol and Meaning is given as follows

= Assignment
*= Multiply and assign
/= Divide and assign
%= Modulo and assign
+= Add and assign
-= Subtract and assign

The variable to be assigned to is the left operand. The right side is evaluated and its type
converted to the type of the variable on the left and stored in the variable. The assignment
operators return the value that was stored in the variable, making it possible to assign multiple
variables on a single line. The convenience assignment operations let you abbreviate a statement
like a = a * b to a *= b. Here are some examples.

/*Sample Code to exhibit assignment operator*/


#include <stdio.h>
void main( )
{
int a = 8.3;
float b = 1.343f;
int c;
printf( "a = %d, b = %fn", a, b );
a += 2;
b *= a;
printf( "a = %d, b = %fn", a, b );
a %= 4;
b -= 0.43;
printf( "a = %d, b = %fn", a, b );

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 47


MSRIT
[Type text]
a = c = 5;
printf( "a = %dn", a );
}

The output of this program is

a = 8, b = 1.343000
a = 10, b = 13.430000
a = 2, b = 13.000000
a=5

The double 8.3 constant is converted to an int and then stored in a. a is assigned to the remainder
left over when a is divided by 4. At the end multiple assignments on a single line is shown. The c
= 5 is done first, then the value of c (which is now 5) is assigned to a.

C Increment and Decrement Operators:

The increment (++) and decrement (--) operators simply add 1 or subtract 1 from a
variable and return the value of that variable. These are unary operators meaning they work on
only one operand, which is the variable to modify.

There are two ways to use these operators – prefix or postfix. That means you can put the
operator in front of the variable like ++a or behind the variable like b--. However, they have
slightly different behavior. In prefix notation the variable is incremented or decremented first,
then the new value is returned. In postfix notation the variable's original value is returned, and
the addition or subtraction happens later. Let us see some examples:

/* program to understand working of pre increment operator */


#include<stdio.h>
#include<conio.h>
void main()
{

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 48


MSRIT
[Type text]
int a=20;
clrscr();
++a;
printf("Value of a is %d",a); //Value of a is 21 as it is incremented by 1
getch();
}

/* program to understand working of post increment operator */


#include<stdio.h>
#include<conio.h>
void main()
{
int a=20;
clrscr();
a++;
printf("Value of a is %d",a); //Value of a is 21 as it is incremented by 1
getch();
}

/* program to understand working of post/pre increment operators*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=6,c,d;
clrscr();
printf("values of a and b are %d %d\n",a,b);
printf("result for the 1st expression %d\n",a++ * b++); /*a=5 b=6*/
c=a++ * b++; /*a=6 b=7*/

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 49


MSRIT
[Type text]
printf("result for the 2nd expression is %d\n",c);
printf("Result for the 3rd expression is %d\n",++a * ++b); /* a=8 b=9*/
d=++a * ++b; /*a=9 b=10*/
printf("result for the 4th expression is %d\n",d);
}

Output is as follows
values of a and b are 5 6
result for the 1st expression is 30
result for the 2nd expression is 42
result for the 3rd expression is 72
result for the 4th expression is 90

Condition Operators:

The conditional operator is unusual in that it takes three operands. The syntax of this
operator is like this
Condition ? Expression1 : Expression2;

You can think of the conditional operator as if it were a function that works like this:

if ( Condition )
return Expression1;
else
return Expression2;

The Condition expression must evaluate to true or false. If it is true Expression1 is


evaluated and its value is returned. If Condition is false Expression2 is evaluated and its value is
returned. Both Expression1 and Expression2 must be the same type (or convertible to the same
type).

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 50


MSRIT
[Type text]
/* Program to find whether given number is even or odd using conditional operator */

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a non zero number\n");
scanf("%d",&n);
(n%2==0)? printf("Given number is even\n"): printf("Given number is odd\n");
getch();
}
Output:
Enter a non zero number
10
Given number is even

/* Program to find whether given number is zero, positive or negative using conditional
operator */
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter the number\n");
scanf("%d",&n);
(n==0)? printf("Given number is zero\n"):(n>0)? printf("Given number is positive\n"):
printf("Given number is negative\n");
getch();

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 51


MSRIT
[Type text]
}

Output
Enter the number
-8
Given number is negative

Special operators:

C support special operators like comma(,) and sizeof( ) operators.

Sizeof( ): The sizeof operator returns the size in bytes of that its operand takes up. The operand
can be any expression that is not a function or bitfield, which means it can be an expression like
20 + 1.34 or a type name or a variable name or a constant. The size is returned as an int. Here are
some examples:

/* program to understand working of sizeof operators */


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d;
clrscr();
a=sizeof(int);
b=sizeof(float);
c=sizeof(char);
d=sizeof(double);
printf("a is %d, b is %d, c is %d, d is %d",a,b,c,d);
getch();
}

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 52


MSRIT
[Type text]
Output:
a is 2, b is 4, c is 1, d is 8

/* program to understand working of sizeof operators */


#include<stdio.h>
#include<conio.h>
void main()
{
int x;
float y;
char z;
double p;
int a,b,c,d;
clrscr();
a=sizeof(x);
b=sizeof(y);
c=sizeof(z);
d=sizeof(p);
printf("a is %d, b is %d, c is %d, d is %d",a,b,c,d);
getch();
}

Output:
a is 2, b is 4, c is 1, d is 8

Evaluation of expressions:

Expressions in C are basically operators acting on operands. Statements like a = b + 3, ++z


and 300 > (8 * k) are all expressions. Strictly speaking, even a single variable or constant can be
considered an expression.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 53


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

Precedence and Associativity of C Operators:

The following Table lists operator precedence and the associativity.

Symbol1 Type of Operation Associativity

[ ] ( ) . –> postfix ++ and


Expression Left to right
postfix --

prefix ++ and prefix -- sizeof


Unary Right to left
& * +–~!

typecasts Unary Right to left

*/% Multiplicative Left to right

+– Additive Left to right

<< >> Bitwise shift Left to right

< > <= >= Relational Left to right

== != Equality Left to right

& Bitwise-AND Left to right

^ Bitwise-exclusive-OR Left to right

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 54


MSRIT
[Type text]
| Bitwise-inclusive-OR Left to right

&& Logical-AND Left to right

|| Logical-OR Left to right

?: Conditional-expression Right to left

= *= /= %=
Simple and compound
+= –= <<= >>= &= Right to left
assignment2
^= |=

, Sequential evaluation Left to right

1. If several operators appear on the same line or in a group, they have equal precedence.
2. All simple and compound-assignment operators have equal precedence.
3. An expression can contain several operators with equal precedence. When several such
operators appear at the same level in an expression, evaluation proceeds according to the
associativity of the operator, either from right to left or from left to right.

/* Sample Code to show the evaluation of expression*/


#include <stdio.h>
void main()
{
int a = 0;
int b = !++*&a;
printf( "a = %d, b = %dn", a, b );
}

This program outputs:


a = 1, b = 0

/* Sample Code to show the evaluation of expression*/


#include<stdio.h>
#include<conio.h>

By Sini Anna Alex, Dept. of Computer Science & Engineering, MSRIT Page 55

[Type text]
void main()
{
int a=5,b=10,c=-6;
int res1,res2,res3,res4;
clrscr();
res1=a>b&&a<c;
res2=a==c||b>a;
res3=(a/2.0==0.0 && b/2.0!=0.0)||c<0.0;
res4=b>15&&c<0||a>0;
printf("res1=%d res2=%d\n res3=%d res4=%d",res1,res2,res3,res4);
}

Output
res1=0 res2=1
res3=1 res4=1

/* Sample Code to show the evaluation of expression*/


#include<stdio.h>
#include<conio.h>
void main()
{
int res1,res2,res3,a=0,b=1,c=-1;
float x=2.5,y=0.0;
clrscr();
res1=--a*(5+b)/2- c++ * b;
printf("result of first expression is %d\n",res1);
res2=x*5&&5||(b/c);
printf("result of second expression is %d\n",res2);
res3=(x>y)+ !a || (c++);
printf("result of third expression is %d\n",res3);

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 56


MSRIT
[Type text]
getch();

result of third expression is 1

Output:

result of first expression is -2

result of second expression is 1

[Type text]
UNIT II

2.2 : Managing input and output operations

Introduction:

Reading, processing, and writing of data are the three essential functions of a computer
program . Most programs take some data as input and display the processed data, often known as
information or results, on a suitable medium.

In C all input / output operations are carried out through function calls such as printf and
scanf. There exist several functions that have more or less become standard for input and output
operations in C. These functions are collectively known as the standard I/O library.

Each program that uses a standard input/output function must contain the statement
#include <stdio.h> at the beginning. However, functions printf and scanf which have been
defined as part of the C language in that header file.

The file name stdio.h is an abbreviation for standard input -output header file. The
instruction #include <stdio.h> tells the compiler to search for a file named stdio.h and place its
contents at this point in the program. The contents of the header file become part of the source
code when it is compiled.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 57


MSRIT
[Type text]
Unformatted input and output functions:

Reading a character:

The simplest of all input/output operations is reading a character from the standard input
unit (usually the keyboard) and writing it to the standard output unit (usually the screen).
Reading a single character can be done by using the function getchar. The getchar takes the
following form variable_name = getchar();
variable_name is a valid C name that has been declared as char type. When this statement
is encountered , the computer waits until a key is pressed and then assigns this character as a
value to getchar function . Since getchar is used on the right-hand side of an assignment
statement , the character value of getchar is in turn assigned to the variable name on the left.
getchar is unformatted input statement.

For example
char name;
name = getchar();
will assign the character 'H' to the variable name when we press the key H on the keyboard
.Since getchar is a function ,it requires a set of parentheses as shown.

Writing a character:

Putchar( ) is used to write a single character on the terminal

Syntax: Putchar(variable_name);

/* program to read and print a character using getchar */


#include<stdio.h>
#include<conio.h>
void main()

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 58


MSRIT
[Type text]
{
char a;
clrscr();
printf("Enter a character\n");
a=getchar();
printf("The given character is ");
putchar(a);
getch();
}

output:
Enter a character
a
The given character is a

/* program to illustrate use of character in decision making */


#include<stdio.h>
#include<conio.h>
void main()
{
char a;
clrscr();
printf("Do you want to get good marks? press y for yes \n");
a=getchar();
if(a=='y'||a=='Y')
printf("Then start studying ");
else
printf("you will get less marks");
getch();
}

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 59


MSRIT
[Type text]
Output 1:
Do you want to get good marks? press y for yes
y
Then start studying

Output 2:
Do you want to get good marks? press y for yes
n
you will get less marks

/* program to find whether given character is a vowel or a consonant */


#include<stdio.h>
#include<conio.h>
void main()
{
char x;
clrscr();
printf("Enter a character\n");
x=getchar();
if(x=='a'||x=='e'|| x=='i'||x=='o'|| x=='u'||x=='A'|| x=='E'||x=='I'|| x=='O'||x=='U')
printf("%c is a vowel ",x);
else
printf("%c is consonant ",x);
getch();
}

Output 1:
Enter a character
a
a is a vowel

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 60


MSRIT
[Type text]
Output 2:

Output 2:
Enter a character
s
s is consonant

/* program to find whether given character is alphabet or digit */


#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char a;
clrscr();
printf("Enter a character\n");
a=getchar();
if( isalpha(a))
printf("%c is an alphabet\n",a);
else if(isdigit(a))
printf("%c is a digit\n",a);
else
printf("%c is neither an alphabet nor a digit\n",a);
getch();
}

output 1:
Enter a character
t
t is an alphabet

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 61


MSRIT
[Type text]
output 2:
Enter a character
6
6 is a digit

output3:
Enter a character
!
! is neither an alphabet nor a digit

/* program to convert lowercase letter to uppercase and vice versa */


#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char a;
clrscr();
printf("Enter a character\n");
a=getchar();
if( isalpha(a))
{
if(islower(a))
putchar(toupper(a));
else
putchar(tolower(a));
}
else
printf(" Invalid input\n");
getch();

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 62


MSRIT
[Type text]
}

output 1:
Enter a character
a
A
output 2:
Enter a character
D
d

output 3:
Enter a character
!
Invalid input

Formatted input and output:

Unformatted I/O functions are used to read and print a single characters. Whenever user
wants to process on N variables of different data types then we use formatted I/O functions there
are two formatted functions are available they are
1. Scanf( ) to perform read operation
2. Printf( ) to perform write operation

1. The scanf() : functions reads data from the keyboatd, and stores the data in to the
variables that is provided in the argument list.Formatted input refers to an input data that has
been arranged in a particular format . For example, consider the following data:
15.73 123 John

This line contains three pieces of data, arranged in a particular form. Such data has to be
read conforming to the format of its appearance. For example, the first part of the data should be

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 63


MSRIT
[Type text]
read into a variable float, the second into int, and the third part into char. This is possible in C
using the scanf function as follows
scanf("control string", arg1, arg2,......argn);

The control string specifies the field format in which the data is to be entered and the
arguments arg1 ,arg2, .....argn specify the address of locations where the data is stored . Control
string and arguments are seperated by commas.
*** Field (or format ) specifications, consisting of the conversion character %, a data type
character (or type specifier ), and an optional number, specifying the field width.
*** Blanks, tabs, or new lines are ignored.

Inputting Integer Numbers:

The field specification for reading an integer number is:


%wd
The percent (%) indicates a conversion specification follows. w is an integer number that
specifies the field width of the number to be read and d, known as data type character, indicates
that the number to be read is in integer mode.

Inputting Real Numbers:

Unlike integers numbers , the field width of real numbers is not to be specified and
therefore scanf reads real numbers using the simple specification %f for both the notations,
namely, decimal point notation and exponential notation. For example, the statement
scanf("%f %f %f , &x, &y , &z);
with the input data
472.34 43.21E-1 678
will assign the value 472.34 to x, 4.321 to y, and 678.0 to z. The input field specifications may
be seperated by any arbitrary blank spaces.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 64


MSRIT
[Type text]
Inputting Character Strings:

We have already seen how a single character can be read from the terminal using the
getchar function. The same can be achieved using the scanf function also. In addition, a scanf
function can input strings containing more than one character strings:
%ws or %wc
The corresponding argument should be a pointer to a character array. However %c may
be used to read a single character when the argument is a pointer to a char variable.
scanf Format Codes:
%c reads a single character
%d read a decimal integer
%e read a floating point value
%f read a floating point value
%g read a floating point value
%h read a short integer
%i read a decimal, hexadecimal, or octal integer
% o read an octal integer
%s read a string
%u read an unsigned decimal integer
%x read a hexadecimal integer
%[..] read a string of word(s)
scanf() returns EOF on end-of-file.

1) For example consider the following data types


int a;
long int b;
unsigned int c;
float d;
double e;
long double f;
char s[100];

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 65


MSRIT
[Type text]
2) The following scanf ( ) shows how read the values for above data types.
scanf("%d", &a); // store an int
scanf(" %d", &a); // eat any whitespace, then store an int
scanf("%s", s); // store a string
scanf("%Lf", &f); // store a long double

// store an unsigned, read all whitespace, then store a long int:


scanf("%u %ld", &c, &b);

// store an int, read whitespace, read "blendo", read whitespace,


// and store a float:
scanf("%d blendo %f", &a, &d);

// read all whitespace, then store all characters up to a newline


scanf(" %[^\n]", s);

// store a float, read (and ignore) an int, then store a double:


scanf("%f %*d %lf", &d, &e);

// store 10 characters:
scanf("%10c", s);

2. printf( ): It is used to write formatted output to "stdout" i.e monitor. The result of printf( ) is
the number of characters written. If a write error occurs, "printf" returns a negative number.
Syntax printf(“format string”,arg1,arg2,...);
The output is formatted according to the "format" string. This string may contain two kinds of
objects:
 ordinary characters which are simply copied to "stdout";

 placeholders, which tell "printf" how to format arguments in the variable argument list.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 66


MSRIT
[Type text]
Each placeholder starts with the character '%' and ends with one or two letters that indicate what
"type" of formatting is necessary. Between the '%' and the "type" field may appear "modifiers",
"width", and "precision" fields. An ANSI placeholder has the form
%[modifiers][width][.precision]type
where square brackets indicate that a field is optional, because '%' has a special meaning to
"printf", you must use two of them to stand for a literal per cent character. For example, you
would use
printf("We had 100%% attendance!\n");
to print out the line
We had 100% attendance!
/*Example to show the printf( ) function */
/* width.c -- field widths */
#include <stdio.h>
#define PAGES 931
void main(void)
{ printf("*%d*\n", PAGES);
printf("*%2d*\n", PAGES);
printf("*%10d*\n", PAGES);
printf("*%-10d*\n", PAGES);
}
Output:
*931*
*931*
* 931*
*931 *

(1) /*program to print float numbers using printf( )*/

/* floats.c -- some floating-point combinations*/


#include <stdio.h>
int main(void)
{

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 67


MSRIT
[Type text]
const double RENT = 3852.99; // const-style constant
printf("*%f*\n", RENT);
printf("*%e*\n", RENT);
printf("*%4.2f*\n", RENT);
printf("*%3.1f*\n", RENT);
printf("*%10.3f*\n", RENT);
printf("*%10.3e*\n", RENT);
printf("*%+4.2f*\n", RENT);
printf("*%010.2f*\n", RENT);
}

This time, the program uses the keyword const to create a symbolic constant. The output is

*3852.990000*
*3.852990e+03*
*3852.99*
*3853.0*
* 3852.990*
* 3.853e+03*
*+3852.99*
*0003852.99*

The example begins with the default version, %f. In this case, there are two defaults—the
field width and the number of digits to the right of the decimal. The second default is six digits,
and the field width is whatever it takes to hold the number.
Next is the default for %e. It prints one digit to the left of the decimal point and six places to the
right. We're getting a lot of digits! The cure is to specify the number of decimal places to the
right of the decimal, and the next four examples in this segment do that. Notice how the fourth
and the sixth examples cause the output to be rounded off.
Finally, the + flag causes the result to be printed with its algebraic sign, which is a plus

sign in this case, and the 0 flag produces leading zeros to pad the result to the full field width.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 68


MSRIT
[Type text]
Note that in the specifier %010, the first 0 is a flag, and the remaining digits (10) specify the
field width.

Formatting Strings:

By now you have seen most of the format conversion possible, but there is one type that is a
little different and that are string format conversions. Take a look at the following
example:
#include<stdio.h>
void main( )
{ printf(":%s:\n", "Hello, world!");
printf(":%15s:\n", "Hello, world!");
printf(":%.10s:\n", "Hello, world!");
printf(":%-10s:\n", "Hello, world!");
printf(":%-15s:\n", "Hello, world!");
printf(":%.15s:\n", "Hello, world!");
printf(":%15.10s:\n", "Hello, world!");
printf(":%-15.10s:\n", "Hello, world!");
}

The output of the example above:


:Hello, world!:
: Hello, world!:
:Hello, wor:
:Hello, world!:
:Hello, world! :
:Hello, world!:
: Hello, wor:
:Hello, wor :

As you can see, the string format conversion reacts very different from number format
conversions.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 69


MSRIT
[Type text]
 The printf(“:%s:\n”, “Hello, world!”); statement prints the string (nothing special
happens.)
 The printf(“:%15s:\n”, “Hello, world!”); statement prints the string, but print 15
characters. If the string is smaller the “empty” positions will be filled with “whitespace.”
 The printf(“:%.10s:\n”, “Hello, world!”); statement prints the string, but print only 10
characters of the string.
 The printf(“:%-10s:\n”, “Hello, world!”); statement prints the string, but prints at least 10
characters. If the string is smaller “whitespace” is added at the end. (See next example.)
 The printf(“:%-15s:\n”, “Hello, world!”); statement prints the string, but prints at least 15
characters. The string in this case is shorter than the defined 15 character, thus
“whitespace” is added at the end (defined by the minus sign.)
 The printf(“:%.15s:\n”, “Hello, world!”); statement prints the string, but print only 15
characters of the string. In this case the string is shorter than 15, thus the whole string is
printed.
 The printf(“:%15.10s:\n”, “Hello, world!”); statement prints the string, but print 15
characters.
If the string is smaller the “empty” positions will be filled with “whitespace.” But it will
only print a maximum of 10 characters, thus only part of new string (old string plus the
whitespace positions) is printed.
 The printf(“:%-15.10s:\n”, “Hello, world!”); statement prints the string, but it does the
exact same thing as the previous statement, accept the “whitespace” is added at the end.

A little warning!
The printf function uses its first argument to determine how many arguments will follow and of
what types they are. If you don’t use enough arguments or if they are of the wrong type than
printf will get confuses, with as a result wrong answers.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 70


MSRIT
[Type text]
2.3 : Decision making and branching

“Decision making” is one of the most important concepts of computer programming .


Programs should be able to make logical (true/false) decisions based on the condition they are in;
every program has one or few problem/s to solve; depending on the nature of the problems,
important decisions have to be made in order to solve those particular problems.

Conditional statement is the term used by many programming languages. The importance
of conditional statements should not be ignored because every program has an example of these
statements. “IF statement” and “switch statement” are the most popular conditional statements
used in C.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 71


MSRIT
[Type text]
There are three decision making statements :-
1) if
2) if-else
3) The Conditional Operators.

If Statement:
“If statement” is the selection statement used to select course of action depending on the
conditions given. Therefore programmers can use this statement to control the flow of their
program. If the program’s condition matches “if statement” condition then the code will be
executed otherwise it will be ignored and the rest of the program will be executed.
The Keyword if tells the compiler what follows The Condition Following the Keyword if
is always enclosed within a pair or Parentheses if The Condition is True Then the Statements is
Executed if the Condition is not true then the Statement is not Executed For Checking a
condition. Relational Operators are Used Like > ,< ,==, >=,<= etc. The if statement is widely
used for checking a particular condition.
Syntax:
if ( expression )
{
Statements;
}

Flow chart of if statement

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 72


MSRIT
[Type text]
for ex:

if(a>b)

then print a is greater then here we first check the condition

that either a is greater than b if yes then execute the condition

/* Sample Code to understand the if statement*/


#include<stdio.h>
void main( )
{
int rate;
printf("Please Enter Rating? 1 for bad , 2 for average and 3 for goodn");
scanf("%d",&rate);
if(rate==1)
{ printf("nit is poor"); }
if(rate==2)
{ printf("nit is average"); }
if(rate==3)
{ printf("nit is good"); }

Output
Please enter rating 1 for bad 2 for average and 3 for good
3
It is good

/*Sample code to understand if statement*/


#include <stdio.h>
void main ()
{

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 73


MSRIT
[Type text]
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
}

Note: consider the following example


#include<stdio.h>
void main()
{
int i=0;
if(i=1)
{
i++;
}
printf(“%d”,i);
}
Output:
1
Since in the if statement i value is not compared with the 10 but 10 is assigned to i therefore the
expression inside the if results to true i value will be incremented to 1 and we get the output as 1
/*Program to show the if statement*/
#include <stdio.h>
void main()
{

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 74


MSRIT
[Type text]
int number = 0;
printf("\nenter an integer between 1 and 10: ");
scanf("%d",&number);
if (number > 7)
printf("You entered %d which is greater than 7\n", number);
if (number < 3)
printf("You entered %d which is less than 3\n", number);
}

Output
Enter an integer between 1 and 10
2
You entered 2 which is less than 3

if-else statement:

The If-else statement directs the flow of the software according to the result of the
conditional expression. The conditional expression in an if statement is a comparison between
two values. If the conditional expression is true, then the "true" block of code is executed. If the
conditional expression is evaluated as false, then the else branch or block of code is executed.
If we wish to have more than one statement following the if or the else, they should be
grouped together between curly brackets. Such a grouping is called a compound statement or a
block. Syntax of if...else
if (test expression)
statements to be executed if test expression is true;
else
statements to be executed if test expression is false;

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 75


MSRIT
[Type text]
Flowchart of if...else statement

/*Write a C program to check whether a number entered by user is even or odd*/

#include <stdio.h>
int main(){
int numb;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}

Output
Enter a number you want to check.
25
25 is odd.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 76


MSRIT
[Type text]
/*Sample code to show biggest of two numbers using if-else statement.*/
#include <stdio.h>
main( )
{
int i,j,big; //variable
scanf("%d%d",&i,&j);
big = i;
if(big < j) {
big = j;
}
printf("bigger one is %d \n",big);

else {
big = i;
}
printf("bigger one (using else) is %d \n",big);
}

Output:
10 40

Bigger one (using else) is 40

/* Write a program to find whether given number is zero even or odd */


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter the number\n");

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 77


MSRIT
[Type text]
scanf("%d",&n);
if(n==0)
printf("Given number is zero\n");
else if(n%2==0)
printf("Given number is even\n");
else
printf("Given number is odd\n");
getch();
}

Output:
0
Given number is zero

/* Write a program to find whether given number is positive or negative */


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a non zero number\n");
scanf("%d",&n);
if(n>0)
printf("Given number is positive\n");
else
printf("Given number is negative\n");
getch();
}

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 78


MSRIT
[Type text]
Output:
Enter a non zero number
25
Given number is positive

/* Write a program to find whether given triangle is equilateral, isoceles or scalene */


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter the sides of the triangle\n");
scanf("%d%d%d",&a,&b,&c);
if((a==b)&&(a==c))
printf("Given triangle is equilateral\n");
else if((a==b)||(b==c)||(c==a))
printf("Given triangle is isoceles\n");
else
printf("Given triangle is scalene\n");
getch();
}

Enter the sides of the triangle


235
Given triangle is scalene

/* Write a program to find whether given year is a leap year or not */


#include<stdio.h>
#include<conio.h>

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 79


MSRIT
[Type text]
void main()
{
int year;
clrscr();
printf("Enter the year\n");
scanf("%d",&year);
if((year%400==0)||((year%100!=0)&&(year%4==0)))
printf("%d is a leap year\n",year);
else
printf("%d is not a leap year\n",year);
getch();
}
Enter the year
2004
2004 is a leap year

Nested if...else statement:

The if in another if is known as nested if. The if...else statement can be used in nested
form when a serious decision are involved. Syntax of nested if...else statement is as follows.
if (test expression)
statements to be executed if test expression is true;

else
if(test expression 1)
statements to be executed if test expressions 1 is true;
else
if (test expression 2)
.
.
.
else

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 80


MSRIT
[Type text]
statements to be executed if all test expressions are false;

How nested if...else works?

If the test expression is true, it will execute the code before else part but, if it is false, the control
of the program jumps to the else part and check test expression 1 and the process continues. If all
the test expressions are false then, the last statement is executed. The ANSI standard specifies
that 15 levels of nesting may be continued.

Example of nested if else statement

Example 1. According to the values given, what will be the value of x after each of the
following?

if (a == b) 1. if a is given as 5, b is given as 5

if (b <= 3)

x = 4; 2. if a is given as 2, b is given as 2

else

x = 0; 3. if a is given as 5, b is given as 2

Else

if (a > b) 4. if a is given as 2, b is given as 7

x = a;

else

x = b;
}

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 81


MSRIT
[Type text]
/* Program to check the balance of an accountusing nested if*/
#include <stdio.h>
void main ()

{
int persnum,usernum,balance,num = 0;

persnum = 7462;
balance = 20000;

printf ("The Plastic Bank Corporation\n");


printf ("Please enter your personal number :");
scanf ("%d",&num);

if ((num > 9999) || (num <= 0))


{
printf ("That is not a valid number\n");
exit(0);
}

usernum = num;

if (usernum == 7462)
{
printf ("\nThe current state of your account\n");
printf ("is %d\n",balance);

if (balance < 0)

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 82


MSRIT
[Type text]
{
printf ("The account is overdrawn!\n");
}
}
else
{
printf ("This is not your account\n");
}

printf ("Have a splendid day! Thank you.\n");


}
}

Output:
The Plastic Bank Corporation
Please enter your personal number
7462
The current state of your account
20000

Output:
The Plastic Bank Corporation
Please enter your personal number
8653
This is not your account
Have a splendid day! Thank you
3)

/* C program to relate two integers entered by user using = or > or < sign.*/

#include <stdio.h>
int main(){

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 83


MSRIT
[Type text]
int numb1, numb2;
printf("Enter two integers to check".\n);
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d=%d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d>%d",numb1,numb2);
else
printf("Result: %d>%d",numb2,numb1);
return 0;
}

Output 1

Enter two integers to check.


5
3
Result: 5>3

Output 2

Enter two integers to check.


-4
-4
Result: -4=-4

Note: If programmer needs to execute more than one statements if certain condition is true or
false then, parenthesis should be used.

if {
statement1;
statement2;

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 84


MSRIT
[Type text]
......
......
statementN;
}

else if() ladder control statement:

else if() ladder is similar to if else control statement. else if() ladder is used to check for
another condition if the previously specified condition becomes false. That means when a
condition gets false then we can check for another condition by using else if ladder. so by using
else if() statement, when a condition is specified and if the condition becomes true, then the
block of statements under if() block will be executed. if the condition becomes false, then it will
check for another condition. This is also called as nested if else statement. so by using this
process we can create any number of if else statements.

syntax for else if statement :-

if(<condition>)
{
block of statements
}
else if(condition)
{
block of statements
}
else
{
block of statements
}

/*Example to use else if ladder*/


if(a<0)

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 85


MSRIT
[Type text]
{
printf("\n a is negative");
}
else if(a%2==0)
{
printf("\n a is positive");
printf("\n a is even number");
}
else
{
printf("\n a is positive");
printf("\n a is odd number");
}
printf("\n completed");
Output:

when a=-3
a is negative
completed

In the above example we are specifying a condition a<0. if the condition(a<0) is true, then the
control enters into the if() block and executes the block of statements under if() block.

If the condition(a<0) gets false, then the control checks for an another condition(a%2==0). If this
condition becomes true, then it executes the block of statements under else if block and if the
condition becomes false then the block of statements under else will be executed, and continued
to the next statement after that block.

/*Program to grade the student based on percentage*/


#include<stdio.h>
#include<conio.h>

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 86


MSRIT
[Type text]
void main()
{

int max,t=0;
float a,b,c,sum=0,per=0;
clrscr();
printf(“Enter the maximum marks for each subject: “);
scanf(“%d”,&max);
printf(“Enter the marks obtained by the student in each subject: “);
scanf(“%f%f%f”,&a,&b,&c);
if((a>max)||(b>max)||(c>max))
printf(“\n\t!!Wrong data !!\nThe obtained marks should not exceed the maximum
marks.”);
else
{
t=max*3;
sum=a+b+c;
per=(sum/t)*100;
printf(“\n\t******RESULT******\n”);
printf(“\nMaximum marks : %d\n”,t);
printf(“Obtained marks: %f\n”,sum);
printf(“Percentage : %f\n”,per);
if(per>=80)
printf(“Grade : A\n”);
else if((per>=60)&&(per<80))
printf(“Grade : B\n”);
else if((per>=40)&&(per<60))
printf(“Grade : C\n”);
else
printf(“Result : Fail\n”);

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 87


MSRIT
[Type text]
}
getch();

Output:
Enter the maximum marks for each subject:100
Enter the marks obtained by the student in each subject:90 95 92
******RESULT******
Maximum marks :100
Obtained marks: 90 95 92
Percentage :92.3
Grade :A

Important points to remember:-


-> we should be very careful while working with else if ladder as it involves multiple if else
statements.
-> As a condition has only two choices whether it is true or false, so only the block of statements
either under if block or else block are executed. the statements under both the blocks are not
executed at a single time. only one block of statements either if or else if or else are executed at a
single time depending upon the condition specified.

By Sini Anna Alex, Dept. of Computer Science & Engineering, Page 88


MSRIT
[Type text]
Study Material Prepared By:
Sini Anna Alex, A.Parkavi, Mamatha V

[Type text]

You might also like