0% found this document useful (0 votes)
4 views32 pages

Module 2

The document provides an overview of the C programming language, including its history, structure, and fundamental concepts. It covers the basic structure of a C program, character sets, identifiers, constants, variables, data types, and input/output functions. Key features of C include its robustness, speed, portability, and suitability for structured programming.

Uploaded by

bgmidaredevil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views32 pages

Module 2

The document provides an overview of the C programming language, including its history, structure, and fundamental concepts. It covers the basic structure of a C program, character sets, identifiers, constants, variables, data types, and input/output functions. Key features of C include its robustness, speed, portability, and suitability for structured programming.

Uploaded by

bgmidaredevil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basic concepts of a C program,

C language Preliminaries

Introduction: C is a programming language developed at AT & T’ s Bell laboratories of USA in


1972. It was designed and written by a system programmer Dennis Ritchie. The main intention was to
develop a language for solve all possible applications. C language became popular because of the
following reasons.

1. C is a robust language , which consists of number of built-in functions and operators


can be used to write any complex program
2. Programs written in c are executed fast compared to other languages.
3. C language is highly portable
4. C language is well suited for structured programming.
5. C is a simple language and easy to learn.

Fundamentals of Problem Solving


Executing a C program
Executing a program written in C involves a series of steps. These are
1. Creating the program.
2. Compiling the program.
3. Linking the program with functions that are needed from the C library.
4. Executing the program.

Introduction to C Language

Dept. of CSE, SJBIT Page 7


Introduction to C programming 25PLD25

Structure of a C program:
The basic structure of a C program is shown below
Documentation Section
Link Section
Definition Section
Global Declaration Section
main() Function Section
{
Declaration Part
Executable Part
}
Subprogram section
Function 1
Function 2
.
.
.
Function n
The documentation section consists of a set of comment lines giving the name of the program,
the name author and other details which the programmer would like to use later. The link section
provides instructions to the compiler to link functions from the system library. The definition
section contains all symbolic constants. There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global declaration
section. Every C program must have one main() function section. This section contains two parts
declaration part and executable part. The declaration part declares all the variables used in the
executable part. There should be at least one statement in the executable part. These two parts
must appear between the opening and the closing braces. The program execution begins at the
opening brace and ends at the closing brace. The closing brace of the main function section is
logical end of the program. All statements in the declaration and executable parts end with a

Dept. of CSE, SJBIT Page 8


C Programming for problem solving 18CPS23

semicolon. The subprogram section contains all the user-defined functions that are called in the
main function. The main function is very important compared to other sections.

Character Set

The characters that can be used to form words, numbers and expressions depend upon the
computer on which the program is run. The characters in C are grouped into the following
categories.
1. Letters
2. Digits
3. Special characters
4. White Spaces
Letters Digits
Uppercase A…Z All decimal digits 0…9
Lowercase a….z
Special characters
, comma & ampersand
. period ^ carat
; semicolon *asterisk
: colon -minus sign
? question mark + sign
‘ apostrophe < opening angle bracket
! exclamation mark (or less than sign)
| vertical bar > closing angle bracket
/ slash (or greater than sign)
\ backslash ( left parenthesis
~ tilde ) right parenthesis
_ underscore [ left bracket
$ dollar sign ] right bracket
% percent sign { left brace
# number sign } right brace

Dept. of CSE, SJBIT Page 9


C Programming for problem solving 18CPS23

White Spaces
Blank Space
Horizontal tab
Carriage return
New line
Form feed
Identifiers:
In c language every word is classified into either keyword or identifier. All keywords have
fixed meanings and these meanings cannot be changed. These serve as basic building blocks for
program statements. All keywords must be written in lowercase. The list of all ANSI C
keywords are listed below

ANSI C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers refer to the names of variables, functions and arrays. These are user defined
names and consist of a sequence of letters and digits, with a letter as a first character. Both
uppercase and lowercase letters are permitted, although lowercase letters are commonly used.
The underscore character is also permitted in identifiers. It is usually used as a link between two
word in long identifiers.

Integer Constants:

An integer constant refers to a sequence of digits. There are three types of integers,
namely decimal, octal and hexadecimal. Decimal integers consist of a set of digits 0 through 9,
preceded by an optional – or + sign. Some examples of decimal integer constants are

Dept. of CSE, SJBIT Page 10


C Programming for problem solving 15PCD13

123

-431

34567

+678

Spaces, commas, and non-digit characters are not permitted between digits. For example
15 750

20,000

Rs 1000

are illegal numbers.


An octal integer constant consists of any combination of digits from the set 0 through 7 with a
leading 0. Some examples are:
037
0
0435
0567
A sequence of digits preceded by 0x is considered as hexadecimal integer. They may also
include alphabets A through F or a through F. The letters A through F represent the numbers 10
through 15. The examples for hexadecimal integers are:
0x2
0x9F
0xbcd
0x
Floating-point constants:
Integer numbers are inadequate to represent quantities that vary continuously, such as distances
,heights ,temperatures ,prices and so on. These quantities are represented by numbers containing
fractional parts like 23.78. Such numbers are called floating-point constants or real constants.
Examples for floating-point constants are given below.
213.

Dept. of CSE, SJBIT Page 11


C Programming for problem solving 15PCD13

.95
-.71
+.5
A real number may also be expressed in exponential(or specific notation). For example the value
213.45 may be written as 2.1345e2 in exponential notation. e2 means multiply by 102. The
general form is
mantissa e exponent
Character Constants:
A character constant contains a single character enclosed within a pair of single quote
marks. Examples of character constants are:
‘5’ ‘X’ ‘;’ ‘ ‘
Note that the character constant ‘5’ is not the same as the number 5. The last constant is a blank
space. Character constants have integer values known as ASCII values. For Example, the
statement
printf (“%d”, ‘A’);
would print the number 65,the ASCII value of the letter a. Similarly, the statement
printf(“%c”, 65)
would give the output as letter ‘A’. It is also possible to perform arithmetic operations on
character constants.
Backslash Character Constants:
C supports some special backslash character constants that are used in output functions. For
example, the symbol ‘\n’ stands for new line character. The below table gives you a list of
backslash constants.

Backslash Character Constants


Constant Meaning
‘\a’ audible alert(bell)
‘\b’ back space
‘\f’ form feed
‘\n’ new line character
‘\r’ carriage return

Dept. of CSE, SJBIT Page 12


C Programming for problem solving 18CPS23

‘\t’ horizontal tab


‘\v’ vertical tab
‘\’’ single quote
‘ \” ’ double quote
‘\?’ question mark
‘\\’ backslash mark
‘\0’ null character
Note that each one of them represents one character, although they consist of two characters.
These character combinations are called escape sequences.
String constants:
A string constant is a sequence of characters enclosed in double quotes. The letters may be
numbers, special characters and blank space.
Examples are given below “THANK YOU”
“2345”
“?.....”
“7+8-9”
“X”
Remember that a character constant ‘X’ is not equivalent to the single character string constant(
“X”). A single character string constant does not have an equivalent integer value as a single
character constant. These type of constants are used in programs to build meaningful programs.
Meaning of variables:
A variable is a data name that may be used to store a data value. Unlike the constants that remain
unchanged during the execution of a program, a variable may take different values at different
times during execution. A variable name can be chosen by the programmer in a meaningful way
so as to reflect its function or nature in the program. Some examples are given below.
Average
Height
Total
Counter_1
Rules for defining variables:

Dept. of CSE, SJBIT Page 13


C Programming for problem solving 18CPS23

Variable names may consist of letters, digits, and the underscore(_) character, subject to the rules
given below:
1. The variables must always begin with a letter. Some systems permit underscore as the
first character.
2. ANSI standard recognizes a length of 31 characters. However, the length should not
be normally mare than eight characters. Since first eight characters are treated as
significant by many compilers.
3. Uppercase and lowercase are significant. That is ,the variable Rate is not the same as
rate or TOTAL.
4. The variable name should not be a keyword.
5. White space is not allowed.
Some examples are given below:
Abhi Value I_rate
Mumbai s1 ph_value
Rate sum1 distance
The examples given below are invalid:
345 (rate)
% 56 nd
Declaration of variables:
Identifiers which are used as variable names should be prefixed as integer or float
by the following declaration should appear at the beginning of a program before the variable
names are used.
type _name variable name……variable name;
The type_name is always a reserved word. The type_name available for variable names storing
numbers are int for integers and float for floating point numbers. Valid examples are given
below:
int n, height ,count ,digit;
float rate, average , y_coordinate,p1;
When a variable name is declared then a memory location is identified and given this name.
The following declarations of variables are invalid:
Float a ,b ,c ; (comma after float is not valid)

Dept. of CSE, SJBIT Page 14


C Programming for problem solving 18CPS23

Int :x; (: is not valid)


Real x, y;(real is not the correct type_name)

Fundamental data types:


C language has varieties of data types. Storage representations and machine instructions differ
from machine to machine. The variety of data types available allow the programmer to select the
appropriate to the needs of the application as well as the machine. The fundamental or primary
data types are integer(int), character(char), floating point(float), and double-precision floating
point(double). Many of them also has extended data types such as long, double, short, unsigned
and signed. The range of basic four types are given below:
Data types Range of values
char -128 to 127
int -32,768 to 32,767
float 3.4e-38 to 3.4e+38
double 1.7e-308 to 1.7e+308

Char, int, float and double are all keywords and therefore their use is reserved. They may not be
used as names of variables. Char stands for “character” and int stands for “integer”. The
keywords short int, long int and unsigned int may be and usually are, shortened to just short,
long, and unsigned, respectively. Also, double and long float are equivalent, but double is the
keyword usually used.
Integer Types:
Integers are whole numbers with a range of values supported by a particular machine. Generally
integers occupy one word of storage. If we use a 16 bit word length, the size of the integer
value is limited to the range -32768 to +32767. A signed integer uses one bit for sign and 15 bits
for the magnitude of the number. Similarly, a 32 bit word length can store an integer ranging
from -2,147,483,648 to 2,147,483,647. C has three classes of integer storage, namely short int,
int, and long int in both unsigned and signed forms. For example, short int represents fairly small
integer.
Values and requires half the amount of storage as a regular int number uses. Unlike signed
integers, unsigned integers use all the bits for the magnitude of the number and are always

Dept. of CSE, SJBIT Page 15


C Programming for problem solving 15PCD13

positive. Therefore, for a 16 bit machine, the range of unsigned integer numbers will be from 0 to
65,535. We declare long and unsigned integers to increase the range of values.

Floating point types:


Floating point (or real) numbers are stored in 32 bits (on all 16 bit and 32 bit machines), with 6
digits of precision. Floating point numbers are defined in C by the keyword float. The type
double can be used when the accuracy provided by a float number is not sufficient. A double
data type number uses 64 bits giving a precision of 14 digits. These are known as double
precision numbers. To extend the precision further, we may use long double which 80 bits..
Character types:
A single character can be defined as a character (char) type data. Characters are usually stored in
8 bits(one byte) of internal storage. The qualifier signed or unsigned may be explicitly applied to
char. While unsigned chars have values between 0 and 255, signed chars have values from -128
to 127.
Size and range of data types on a 16-bit machine
Type Size(bits) Range
Char or signed char 8 -128 to 127
Unsigned char 8 0 to 255
Int or signed int 16 -32,768 to 32,767
Unsigned int 16 0 to 65535
Short int or 8 -128 to 127
Signed short int
Unsigned short int 8 0 to 255
Long int or signed 32 -2,147,483,648 to
Long int 2,147,483,647
Unsigned long int 32 0 to 4,294,967,295
Float 32 3.4E-38 to 3.4+38
Double 64 1.7E-308 to 1.7E+308
Long double 80 3.4E-4932to 1.1E+4932
Input and Output Functions:

Dept. of CSE, SJBIT Page 16


C Programming for problem solving 18CPS23

Scanf functions:-
The function scanf() is used to read data into variables from the standard input, namely a
keyboard. The general format is:
Scanf(format-string, var1,var2,………varn)
Where format-string gives information to the computer on the type of data to be stored in the list
of variables var1,var2……varn and in how many columns they will be found
For example, in the statement:
Scanf(“%d %d”, &p, &q);
The two variables in which numbers are used to be stored are p and q. The data to be stored are
integers. The integers will be separated by a blank in the data typed on the keyboard.
A sample data line may thus be:
456 18578
Observe that the symbol &(called ampersand) should precede each variable name. Ampersand is
used to indicate that the address of the variable name should be found to store a value in it. The
manner in which data is read by a scanf statement may be explained by assuming an arrow to be
positioned above the first data value. The arrow moves to the next data value after storing the
first data value in the storage location corresponding to the first variable name in the list. A blank
character should separate the data values. The scanf statement causes data to be read from one or
more lines till numbers are stored in all the specified variable [Link] that no blanks should be
left between characters in the format-string. The symbol & is very essential in front of the
variable name. If some of the variables in the list of variables in the list of variables in scanf are
of type integer and some are float, appropriate descriptions should be used in the format-string.
For example:
Scanf(“%d %f %e”, &a , &b, &c);
Specifies that an integer is to be stored in a, float is to be stored in b and a float written using the
exponent format in c. The appropriate sample data line is:
485 498.762 6.845e-12
Printf function:
The general format of an output function is
Printf(format-string, var1,var2…..varn);

Dept. of CSE, SJBIT Page 17


C Programming for problem solving 18CPS23

Where format-string gives information on how many variables to expect, what type of
arguments they are , how many columns are to be reserved for displaying them and any
character string to be printed. The printf() function may sometimes display only a message and
not any variable value. In the following example:
printf(“Answers are given below”);
The format-string is:
Answers are given below
And there are no variables. This statement displays the format-string on the video display and
there are no variables. After displaying, the cursor on the screen will remain at the end of the
string. If we want it to move to the next line to display information on the next line, we should
have the format-string:
printf(“Answers are given below\n”);
In this string the symbol \n commands that the cursor should advance to the beginning of the
next line.
In the following example:
printf(“Answer x= %d \n”, x);
%d specifies how the value of x is to be displayed. It indicates the x is to be displayed as a
decimal integer. The variable x is of type int. %d is called the conversion specification and d the
conversion character . In the example:
printf(“a= %d, b=%f\n”, a, b);
the variable a is of type int and b of type float or double. % d specifies that a is to be displayed as
an integer and %f specifies that, b is to be displayed as a decimal fraction. In this example %d
and %f are conversion specifications and d, f are conversion characters. Example to indicate how
printf() displays answers.
/*Program illustrating printf()*/
# include<stdio.h>
main()
{
int a= 45, b= 67
float x=45.78 , y=34.90
printf(“Output:\n”);

Dept. of CSE, SJBIT Page 18


C Programming for problem solving 18CPS23

printf(“1,2,3,4,5,6,7,,8,0\n”);
printf(“\n”);
printf(“%d, %d,,%f ,%f \n” , a,b,x,y);
printf(“\n”);
}
Output:
1234567890
45,67,45.78,34.90

Example for illustrating scanf and printf statements:


/* Program for illustrating use of scanf and printf statements */
#include<stdio.h>
main()
{
int a,b,c,d;
float x,y,z,p;
scanf(“%d %o %x %u”, &a, &b ,&c ,&d);
printf(“the first four data displayed\n”);
printf((“%d %o %x %u \n”, a,b,c,d);
scanf(“%f %e %e %f”, &x, &y, &z, &p);
printf(“Display of the rest of the data read\n”);
printf(“%f %e %e %f\n”, x,y,z,p);
printf(“End of display”);
}

Input:
-768 0362 abf6 3856 -26.68 2.8e-3 1.256e22 6.856

Output:

The first four data displayed

Dept. of CSE, SJBIT Page 19


C Programming for problem solving 18CPS23

-768 362 abf6 3856


Display of the rest of the data read
-26.680000 2.800000 e-03 1.256000e+22 6.866000
End of display
Formatted input and output using format specifiers:
The function scanf is the input analog of printf, providing many of the same conversion facilities
in the opposite direction.
int scanf (char *format, …..)
scanf reads characters from the standard input, interprets them according to the specification in
format, and stores the results through the remaining arguments. The format argument is
described below; the other arguments, each of which must be a pointer, indicate where the
corresponding converted input to be stored. scanf stops when it exhausts its format string, or
when some input fails to match the control specification. It returns as its value the number of
successfully matched and assigned input items. This can be used to decide how many items were
found . On end of file EOF is returned; note that this is different from 0, which means that the
next input character does not match the first specification in the format string. The next call to
scanf resumes searching immediately after the last character already converted. A conversion
specification directs the conversion of the next input field. Normally the result is placed in the
variable pointed to by the corresponding argument. If assignment suppression is indicated by the
* character, however, the input field is skipped; no assignment is made. An input field is defined
as a string of non-white space characters; it extends either to the next white space character or
until the field width, if specified, is exhausted. This implies that scanf will read across line
boundaries to find its input, since new lines are white space. (White space characters are blank,
tab, new line, carriage return, vertical tab and form feed).
The general syntax is
int printf (char *format, arg1,arg2…………..)
printf converts, formats, and prints its arguments on the standard output under control of the
format. It returns the number of characters printed. The format string contains two types of
objects: ordinary characters, which are copied to the output stream, and conversion specifications
each of which causes conversion and printing of the next successive argument to printf. Each

Dept. of CSE, SJBIT Page 20


C Programming for problem solving 15PCD13

conversion specification begins with a % and ends with a conversion character. Between the %
and the conversion character there may be in order:
• A minus sign, which specifies left adjustment of the converted argument.
• A number that specifies the minimum field width. The converted argument will be
printed in a field at least this wide. If necessary it will be padded on the left or right, to
make up the field width.
• A period, which separates the field width from the precision.
• A number, the precision, that specifies the maximum number of characters to printed
from a string, or the number of digits after the decimal point of a floating point value, or
the minimum number of digits for an integer.
• An h if the integer is to be printed as a short, or l if as a long.

The putchar function:


Single characters can be displayed using the C library function putchar. This function is
complementary to the character input function getchar. The putchar function, like getchar, is a
part of the standard C I/O library. It transmits a single character to a standard output device. The
character being transmitted will normally be represented as a character type variable. It must be
expressed as an argument to the function, enclosed in parentheses, following the word putchar.
The general syntax is
putchar(character variable)
where character variable refers to some previously declared character variable.
A C program contains the following statements
Char c;
………
putchar(c);
C programs:
1) Program to demonstrate printf statement
#include<stdio.h>
main()
{
printf(“hello, world\y”);

Dept. of CSE, SJBIT Page 21


C Programming for problem solving 18CPS23

printf(“hello, world\7”);
printf(“hello, world\?”);
}

2) Program to convert farenheit to Celsius


#include<stdio.h>
main()
{
float fahr, Celsius;

printf(“ enter the value for farenheit\n”);


scanf(“ %f”, &fahr);
Celsius=(5.0/9.0)*fahr-32.0;
printf(“%f %f \n”, fahr,Celsius);
}
3) Program to depict interactive computing using scanf function.
#include<stdio.h>
main()
{
int number;
printf(“enter an integer number\n”);
scanf(“%d”, &number);
If (number<100)
{
printf(“Your number is smaller than 100\n\n”);
else
printf(“Your number contains more than two digits\n”);
}
Output
Enter an integer number 54
Your number is smaller than 100

Dept. of CSE, SJBIT Page 22


C Programming for problem solving 18CPS23

Enter an integer number 108


Your number contains more than digits

4) Program to depict interactive investment program


#include<stdio.h>
main()
{
int year,period;
float amount,inrate,value;
printf(“Input amount , interest rate and period \n\n”);
scanf(“%f %f %d”, &amount, &inrate,&period);
printf(“\n”);
year=1;
while(year<=period)
{
value amount + inrate*amount;
printf(“%2d Rs. %8.2f\n”, year, value);
amount=value;
year=year+1;
}
}

5) Program to calculate the average of a set of N numbers


#define N 10
main()
{
int count;
float sum, average,number;
sum=0;
count=0;
while(count<N)

Dept. of CSE, SJBIT Page 23


C Programming for problem solving 18CPS23

{
scanf(“%f”, &number);
sum=sum+number;
count=count+1;
}
average= sum/N;
printf(“N=%d Sum= %f”, N, sum);
printf(“Average=%f”, average);
}

6) Program to convert days to months and days


#include<stdio.h>
main()
{
int months,days;
printf(“enter days \n”);
scanf(“%d”, &days);
months=days/30;
days=days%30;
printf(“Months = %d Days= %d”, months,days);
}
Types of operators and expressions,
Arithmetic operators:
C provides all the basic arithmetic operators. The operators +,-,* and / all work the same way as
they do in other languages. These can operate on any built-in data type allowed in C. The unary
minus operator, in effect, multiplies its single operand by -1. Therefore, a number preceded by a
minus sign changes its sign.
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus

Dept. of CSE, SJBIT Page 24


C Programming for problem solving 18CPS23

* Multiplication
/ Division
% Modulo division
Integer division truncates any fractional part. The modulo division produces the remainder of an
integer division.

Examples are:
a-b a+b
a*b a/b
a%b -a * b
Here a and b are variables and are known as operands. The modulo divison operator % cannot be
used on floating point data.
Arithmetic expressions:
An arithmetic expression is a combination of variables, constants and operators arranged as per
the syntax of the language. Expressions are evaluated using an assignment statement of the form
Variable=expression;
The table below shows the algebraic expression and C language expression
Algebraic expression C expression
a x b-c a*b-c
(m + n) (x + y) (m + n) *(x + y)
(a b)/c a*b/c
3x2+2x+1 3*x*x+2*x+1
x/y +c x/y + c
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and the result then replaces the precious value of the variable on the left-hand
side. All variables used in the expression must be assigned values before evaluation is attempted.
x=a*b-c;
y=b/c*a;
z=a-b/c+d;

Dept. of CSE, SJBIT Page 25


C Programming for problem solving 18CPS23

The blank space around an operator is optional and adds only to improve readability. When these
statements are used in a program, the variables a ,b ,c and d must be defined before they are used
in the expressions.

Modes of expression:
There are three different modes of expression.
1. Integer Arithmetic
2. Real Arithmetic
3. Mixed-mode Arithmetic

Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operation is called integer arithmetic. This
mode of expression always yields an integer value. The largest integer value depends on the
machine, as pointed out earlier
Example:
If a and b are integers then for a=14 and b=4
We have the following results:
a - b=10
a + b = 18
a * b = 56
a / b=3
a %b=2
During integer division, if both the operands are of the same sign, the result is truncated towards
zero. If one of them is negative, the direction of truncation is implementation dependent. That
is, 6/7=0 and -6/-7=0
but -6/7 may be zero -1 (Machine dependent)
Similarly, during modulo division , the sign of the result is always the sign of the first
operand(the dividend). That is
-14 % 3 =-2
-14 % -3= -2
14 % -3=2

Dept. of CSE, SJBIT Page 26


C Programming for problem solving 18CPS23

Real Arithmetic

An arithmetic operation involving only real operands is called real arithmetic. A real
operand may assume values either in decimal or exponential notation. Since floating point
values are rounded to the number of significant digits permissible, the final value is an
approximation of the correct result. If x, y, and z are floats, then we will have:
x=6.0/7.0=0.857143
y= 1.0/3.0 =0.333333
z= -2.0/3.0= -0.666667
The operator % cannot be used with real operands.
Mixed- mode Arithmetic
When one of the operands is real and the other is integer, the expression is called a mixed-mode
arithmetic expression. If either operand is of the real type, then only the real operation is
performed and the result is always a real number.
Thus
15/10.0=1.5
where as
15/10=1
Arithmetic operators precedence:-
In a program the value of any expression is calculated by executing one arithmetic
operation at a time. The order in which the arithmetic operations are executed in an expression is
based on the rules of precedence of operators.
The precedence of operators is :
Unary (-) FIRST
Multiplication(*) SECOND
Division(/) and (%)
Addition(+) and Subtraction(-) LAST
For example, in the integer expression –a *b/c+d the unary- is done first, the result –a is
multiplied by b, the product is divided by c(integer division) and d is added to it. The answer is
thus:
-ab/c+d

Dept. of CSE, SJBIT Page 27


C Programming for problem solving 15PCD13

All the expressions are evaluated from left to right. All the unary negations are done first. After
completing this the expression is scanned from left to right; now all *, / and % operations are
executed in the order of their appearance. Finally all the additions and subtractions are done
starting from the left of the expression..
For example, in the expression:
Z=a + b* c
Initially b*c is evaluated and then the resultant is added with a. Suppose if want to add a with b
first, then it should be enclosed with parenthesis , is shown below
Z = (a + b) * c
Use of parentheses:

Parentheses are used if the order of operations governed by the precedence rules are to
[Link] the expression with a single pair of parentheses the expression inside the
parentheses is evaluated FIRST. Within the parentheses the evaluation is governed by the
precedence rules.
For example, in the expression:
a * b/(c+d * k/m+k)+a
the expression within the parentheses is evaluated first giving:
c+dk/m+k
After this the expression is evaluated from left to right using again the rules of precedence giving
ab/c+dk/m+k +a
If an expression has many pairs of parentheses then the expression in the innermost pair is
evaluated first, the next innermost and so on till all parentheses are removed. After this the
operator precedence rules are used in evaluating the rest of the expression.
((x * y)+z/(n*p+j)+x)/y+z
xy,np+j will be evaluated first.
In the next scan
Xy+z/np+j +x

Will be evaluated. In the final scan the expression evaluated would be:

(Xy+ z/np+j+x)/y +z

Dept. of CSE, SJBIT Page 28


C Programming for problem solving 18CPS23

Increment and Decrement operators:-


The increment operator ++ and decrement operator – are unary operators with the same
precedence as the unary -, and they all associate from right to left. Both ++ and – can be applied
to variables, but no to constants or expressions. They can occur in either prefix or postfix
position, with possibly different effects occurring. These are usually used with integer data type.
The general syntax is:
++variable|--variable| variable++| variable—
Some examples are
++count -kk index++ unit_one--
We use the increment and decrement statements in for and while extensively.
Consider the following example
m=5;
y=++m;
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements as
m=5;
y=m++;
then the value of y would be 5 and m would 6. A prefix operator first adds to 1 to the operand
and then the result is assigned to the variable on left. On the other hand, a postfix operator first
assigns the value to the variable on left and then increments the operand. Similar is the case,
when we use ++(or--) in the subscripted variables. That is, the statement a[i++]=10; is
equivalent to
a[i]=10;
i=i+1;
The increment and decrement operators can be used in complex statements. Example
m=n++ -j+10;
Old value of n is used in evaluating the expression. n is incremented after the evaluation.
Relational operators:
We often compare two quantities and depending on their relation, to take certain
decisions. For example, we may compare the age of two persons, or the price of two items, and

Dept. of CSE, SJBIT Page 29


C Programming for problem solving 18CPS23

so on. These comparisons can be done with the help of relational operators. C supports six
relational operators in all. These operators and their meanings are shown below
Relational Operators
Operator Meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and has the following form:
ae- 1 relational operator ae-2. ae-1 and ae-2 are arithmetic expressions, which may be simple
constants, variables or combination of them.
Given below are some examples of simple relational expressions and their values:
4.5<= 10 TRUE
4.5< 10 FALSE
-35>= 0 FALSE
10< 7+5 TRUE
a+b == c+d TRUE only if the sum of values of a and b is equal to the sum of values of c
and d.
When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results compared. That is, arithmetic operators
have a higher priority over relational operators. Relational expressions are used in decision
statements such as, if and while to decide the course of action of a running program.
Logical operators:
In addition to the relational operators . C has the following three logical operators.
&& logical AND
|| logical OR
! logical NOT
The logical operators && and || are used when we want to test more than one condition and make
decisions.

Dept. of CSE, SJBIT Page 30


C Programming for problem solving 18CPS23

Example:
a>b && x == 10
An expression of this kind which combines two or more relational expression is termed as a
logical expression or a compound relational expression. Like the simple relational expressions , a
logical expression also yields a value of one or zero, according to the truth table shown below.
The logical expression given above is true only if a>b is true and x==10 is true. If either (or
both) of them are false, the expression is false.
Truth Table
Op-1 op-2 Value of the expression
Op-1 && op-2 op-1 || op2
Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0

Some examples of the usage of logical expressions are:


If(age>55 && salary <1000)
If (number<0 || number>100)
Relational and logical expressions:
We have seen that float or integer quantities may be connected by relational operators to yield an
answer which is true of false. For example the expression,
Marks>=60
Would have an answer true if marks is greater than or equal to 60 and false if marks is less than
60. The result of the comparison (marks>=60) is called a logical quantity. C provides a facility
to combine such logical quantities by logical operators to logical expressions. These logical
expressions are useful in translating intricate problem statements.
Example :
A university has the following rules for a student to qualify for a degree with Physics as the main
subject and Mathematics as the subsidiary subject:
He should get 50 percent or more in Physics and 40 percent or more in Mathematics.

Dept. of CSE, SJBIT Page 31


C Programming for problem solving 18CPS23

If he gets less than 50 percent in Physics he should get 50 percent or more in Mathematics. He
should get atleast 40 percent in Physics.
If he gets less than 40 percent in Mathematics and 60 percent or more in Physics he is allowed to
reappear in an examination in Mathematics to qualify.
In all the other cases he is declared to have failed.

A Decision Table for Examination Results


Chemistry marks >=50 >=35 >= 60 Else
Physics Marks >=35 >=50 <35
Pass x x - -
Repeat Physics - - x -
Fail - - - x
/*This program implements above rules*/
include<stdio.h>
main()
{
unsigned int roll_no, physics_marks, chem_marks;
while(scanf(“%d %d %d”, &roll_no,&physics_marks, &chem_marks)!=EOF)
{
If(((chem_marks>=50 &&(physics_marks>=35)) || ((chem_marks>=40))
&&(physics_marks>=50)))
Printf(“%d %d %d Pass\n”, roll_no, chem_marks, physics_marks);
Else If (( chem_marks>=60)) && physics_marks<35))
Printf(“%d %d %d Repeat Physics\n”, roll_no,physics_marks,chem_marks);
Else
Printf(“%d %d %d Failed \n”, roll_no, physics _marks, chem_marks);
}
}/*End while*/
}/*End main*/
Precedence of relational operators and logical operators:
Example:

Dept. of CSE, SJBIT Page 32


C Programming for problem solving 18CPS23

(a>b *5) &&(x<y+6)


In the above example, the expressions within the parentheses are evaluated first. The arithmetic
operations are carried out before the relational operations. Thus b*5 is calculated and after that a
is compared with it. Similarly y+6 is evaluated first and then x is compared with it .
In general within parentheses:
The unary operations, namely, -,++,--,! (logical not) are performed first.
Arithmetic operations are performed next as per their precedence.
After that the relational operations in each sub expressions are performed, each sub expression
will be a zero or non _ zero. If it is zero it is taken as false else it is taken as true.
These logical values are now operated on by the logical operators.
Next the logical operation && is performed next.
Lastly the evaluated expression is assigned to a variable name as per the assignment operator.
The conditional operators:
An operator called ternary operator pair “?:” is available in C to construct conditional
expressions of the form.
exp1? exp2: exp3;
where exp1,exp2, and exp3 are expressions.
The operator ?; works as follows: exp1 is evaluated first. If it is nonzero(true), then the
expression exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is
evaluated and its value becomes the value of the expression. Note that only one of the
expressions(either exp2 or exp3) is evaluated.
For example, consider the following statements
x=3;
y=15;
z=(x>y)?x:y;
In this example, z will be assigned the value of b. This can be achieved using the if..else
statements as follows:
If (x>y)
z=x;
else
z=b;

Dept. of CSE, SJBIT Page 33


C Programming for problem solving 18CPS23

Bitwise operators:
C has a distinction of supporting special operators known as bitwise operators for manipulation
of data at bit level. These operators are used for testing the bits, or shifting them right or left.
Bitwise operators may not be applied to float or double. where the filename is the name
containing the required definitions or functions. At this point, the preprocessor inserts the entire
contents of the filename into the source code of the program. When the filename is included
within the double quotation marks, the search for the file is made first in the directory and then in
the standard directories.
Bitwise Operators
Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ One’s Complement

The Comma Operator


C has some special operators. The comma operator is one among them. This operator can be
used to link the related expressions together. A comma-linked list of expressions are evaluated
left to right and the value of right-most expression is the value of the combined expression.
For example, the statement
Value=(a=2, b=6 ,a+b);
First assigns the value 2 to a, then assigns 6 to b, and finally assigns 8(i.e 2+6) to value. The
comma operator has the lowest precedence of all operators,hence the parentheses are necessary.
Some examples are given below:
In for loops:
For(a=1, b=10;a<=b; a++, b++)
In while loops:
While(c=getchar(), C!=’10’)
Exchanging values:

Dept. of CSE, SJBIT Page 34


C Programming for problem solving 18CPS23

T=x, x=y, y=t;


The precedence of operators among themselves and across all the set of operators:
Each operator in C has a precedence associated with it. This precedence is used to determine
how an expression involving more than one operator is evaluated. The operator at the higher
level of precedence are evaluated first.
Operator Description
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
~ One’s Complement
& Address
size of(type) type cast conversion
* Multiplication
/ Division
% Modulus
+ Addition
- Subtraction
<< left shift
>> Right shift
< less than
<= less than or equal to
> Greater than
>= Greater than or equal to
== Equality
!= Inequality
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
&& Logical AND

Dept. of CSE, SJBIT Page 35


C Programming for problem solving 15PCD13

|| Logical OR
?: Conditional expression
= Assignment operators
*= /= %=
+= -= &=
^= |=
<<= >>=
, Comma operator
The associatively of operators:
The operators of the same precedence are evaluated either from left to right or from right to left
depending on the level. This is known as the associatively property of an operator.
The table below shows the associatively of the operators:
Operators Associativity
() [ ] → left to right
~ ! –(unary) left to right
++ -- size of(type)
&(address) left to right
*(pointer)
*/ %
<< >> left to right
<<= >>= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| left to right
?: right to left
=+ =- *= /= %= &= ^= |= <<= >>= right to left
,(comma operator) left to right

Dept. of CSE, SJBIT Page 36


C Programming for problem solving 15PCD13

Evaluation of expressions involving all the above type of operators:


The following expression includes operators from six different precedence groups.
Consider variables x, y , z as integer variables.
Z+=(x0>0 && x<=10) ? ++x : x/y;
The statement begins by evaluating the complex expression
(x>0 && x<=10)
If this expression is true, the expression ++x is evaluated. Other wise, the a/b is evaluated.
Finally, the assignment operation(+=) is carried out, causing the value of c to be increased by the
value of the conditional expression. If for example x, y, and z have the values 1,2,3 respectively,
then the value of the conditional expression will be 2(because the expression ++a will be
evaluated), and the value of z will increase to 5(z=3+2). On the other hand, if x,y and z have the
values 50,10,20 respectively, then the value of the conditional expression will be 5(because the
expression x/y will be evaluated) and the value of z will increase to 25(z=20+5).

Dept. of CSE, SJBIT Page 37


C Programming for problem solving 18CPS23

You might also like