Professional Documents
Culture Documents
Overview & Problem Solving With C
Overview & Problem Solving With C
[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 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 */
/* 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".
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,
\n newline character,
\b backspace character,
\t tab character,
\r return 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.
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:
short short signed integer type. At least 16 unsigned short same as short,
short int bits in size. unsigned short int but unsigned.
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
{
int Count;
Count = 5;
}
{
float Miles;
Miles = 5.6;
}
{
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:
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.
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;
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:
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;
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.
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;
#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.
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
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 );
}
a + b = 103
a - b = 97
a * b = 300
a / b = 33
a%b=1
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.
#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 );
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.
The output is
a * b = 12.566360
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 .
Logical operators:
Operator Meaning
|| 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
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.
(a>b)&&(a==100) True 1
(b>a)||(a>b) True 1
!(a>b) False 0
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.
= 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.
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.
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:
#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*/
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;
#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();
Output
Enter the number
-8
Given number is negative
Special 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:
Output:
a is 2, b is 4, c is 1, d is 8
Evaluation of expressions:
= *= /= %=
Simple and compound
+= –= <<= >>= &= Right to left
assignment2
^= |=
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.
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
Output:
[Type text]
UNIT II
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.
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:
Syntax: Putchar(variable_name);
output:
Enter a character
a
The given character is a
Output 2:
Do you want to get good marks? press y for yes
n
you will get less marks
Output 1:
Enter a character
a
a is a vowel
Output 2:
Enter a character
s
s is consonant
output 1:
Enter a character
t
t is an alphabet
output3:
Enter a character
!
! is neither an alphabet nor a digit
output 1:
Enter a character
a
A
output 2:
Enter a character
D
d
output 3:
Enter a character
!
Invalid input
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
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.
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.
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.
// 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.
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.
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!");
}
As you can see, the string format conversion reacts very different from number format
conversions.
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.
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.
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;
}
if(a>b)
Output
Please enter rating 1 for bad 2 for average and 3 for good
3
It is good
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;
#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.
else {
big = i;
}
printf("bigger one (using else) is %d \n",big);
}
Output:
10 40
Output:
0
Given number is zero
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
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 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
x = a;
else
x = b;
}
{
int persnum,usernum,balance,num = 0;
persnum = 7462;
balance = 20000;
usernum = num;
if (usernum == 7462)
{
printf ("\nThe current state of your account\n");
printf ("is %d\n",balance);
if (balance < 0)
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(){
Output 1
Output 2
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;
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.
if(<condition>)
{
block of statements
}
else if(condition)
{
block of statements
}
else
{
block of statements
}
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.
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”);
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
[Type text]