0% found this document useful (0 votes)
36 views22 pages

C Programming

C is a flexible, portable, and efficient programming language with built-in functions. It can be compiled using various compilers like Turbo C, Tiny C Compiler, Portable C Compiler, and GNU Compiler Collection. A C program structure typically includes preprocessor directives, global declarations, the main function, and other functions. The program is created, compiled into machine code, linked with libraries, and executed. C supports various data types like char, int, float, and double that can be modified using qualifiers. Keywords, identifiers, and literals are basic components used to write C programs.

Uploaded by

Nil Kam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
36 views22 pages

C Programming

C is a flexible, portable, and efficient programming language with built-in functions. It can be compiled using various compilers like Turbo C, Tiny C Compiler, Portable C Compiler, and GNU Compiler Collection. A C program structure typically includes preprocessor directives, global declarations, the main function, and other functions. The program is created, compiled into machine code, linked with libraries, and executed. C supports various data types like char, int, float, and double that can be modified using qualifiers. Keywords, identifiers, and literals are basic components used to write C programs.

Uploaded by

Nil Kam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

Introduction to C

1.1 INTRODUCTION TO C:
1.1.1 Features of C:
 It is a flexible high-level structured programming language.
 It is portable
 It is much faster and efficient.
 It has an ability to extend itself.
 It has a number of built in functions, which makes the programming task simple.
1.1.2 List of C Compilers
Compiler:
Compiler is a program that converts high level language into a machine-code or
lower-level form so that they can be read and executed by a computer.
List of C compilers:
1) Turbo C:
Turbo C is one of the basic and popular compilers for the C programming
language. This was first introduced in 1987; it was popular for its small size,
compilation speed, and low price. Once Turbo C++ got released in 1990, both the
compilers are merged. In 2006, Embarcadero Technologies had re-released Turbo C
as freeware.
2) Tiny C Compiler:
The Tiny C Compiler is designed to work on slow computers with little disk
space. This is an ARM processor C compiler. This compiler started its support to
Windows from 2005. The fastness of this compiler is around nine times faster than GCC.
This compiler allows automatic execution of programs during the compile-time only
using command line arguments.
3) Portable C Compiler:
The Portable C Compiler (PCC) was a very early used compiler for the C
programming language that is almost around mid-1970. This compiler had a long-life
span. This was prevalent during a period in such a way that many of the C compilers
were based on it. PCC compiler was made such that source files were machine-
dependent, not all but only a few of them. It can detect syntax errors and can perform
perfect validity checks.
4) GNU Compiler Collection:
GNU Compiler Collection (GCC) is the compiler produced by the GNU Project.
This supports many programming languages and it is a free software foundation under
the General Public License. This compiler was first released in 1987 and it supported
only C- Programming language during the start. Slowly it expanded to C++, Java,
Android, and IOS. Here, each of the different language compilers has its own program
that reads the code written and sends the machine code as the output. All of these have
a common internal structure. When a high-level language is written, as per the language
it is written, the compiler parses the code in that language and produces an abstract
syntax tree.
5. Clang:
Clang is a compiler for C, C++, Objective-C, and objective-C++ programming
languages. This compiler uses LLVM for the back-end code related compilations. One of
the major goals for Clang is to provide library-based architecture. It is designed to keep
more information during the compilation process than GCC. The error report generated
by Clang during compilation is always in a detailed format. Clang had always aimed to
reduce the over usage of memory space and increase the compilation speed as
compared with GCC, and due to these qualities, it had become one of the fastest-growing
used compilers during a point of time.
1.1.3 Structure of C program:

Documentation Section:
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details. It consist of a set of comment lines . These
lines are not executable.
Preprocessor Section:
It is used to link system library files, for defining the macros and for defining the
conditional inclusion.
Definition section :
The definition section defines all symbolic constants.
Global Declaration Section:
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 that is
outside of all the functions. This section also declares all the user-defined functions.
main () function section :
Every C program must have one main function section. This section contains two
parts; declaration part and executable part.
a) Declaration part : The declaration part declares all the variables used in the
executable part.
b) Executable part : There is at least one statement in the executable part.

These two parts must appear between the opening and closing braces. The
program execution begins at the opening brace and ends at the closing brace.
Subprogram section :
The subprogram section contains all the user-defined functions that are called in
the main () function. User-defined functions are generally placed immediately after the
main () function, although they may appear in any order.
Example:

1.1.4 Compiling, link & run a program:


C program executes in following four steps: 1. Creating the program 2. Compiling
the Program 3. Linking the Program with system library 4. Executing the program

1. Creating a program: Type the program and edit it in standard ‘C’ editor and save the
program with .c as an extension. This is the source program .The file should be saved as
'*.c' extension only.
2. Compiling the Program:

• This is the process of converting the high level language program to Machine level
Language (Equivalent machine instruction) .
• Errors will be reported if there is any, after the compilation
• Otherwise the program will be converted into an object file (.obj file) as a result of the
compilation
• After error correction the program has to be compiled again
3. Linking a program to library: The object code of a program is linked with libraries
that are needed for execution of a program. The linker is used to link the program with
libraries. It creates a file with '*.exe' extension.
4. Execution of program: This is the process of running and testing the program with
sample data. If there are any run time errors, then they will be reported.
1.2 VARIABLES, CONSTANTS & DATA TYPES:
1.2.1 C Character Set:
Every C program contains statements. These statements are constructed using
words and these words are constructed using characters from C character set. C
language character set contains the following set of characters...
1. Alphabets 2. Digits 3. Special Symbols

Alphabets:
C language supports all the alphabets from English language. Lowercase and
uppercase letters together supports 52 alphabets.
lower case letters - a to z
upper case letters - A to Z
Digits :
C language supports 10 digits which are used to construct numerical values in C
language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols :
C language supports rich set of special symbols that include symbols to perform
mathematical operations, to check conditions, white spaces, back spaces and other
special symbols.
1.2.2 Keywords:
The meaning of these words has already been explained to the C compiler. All the
keywords have fixed meanings. These meanings cannot be changed. So these words
cannot be used for other purposes. All keywords are in lower case. The keywords are
known as Reserved words. Keywords or Reserved words are Pre-defined identifiers. 32
keywords are available in C.

Properties of Keywords
1. All the keywords in C programming language are defined in lowercase letters only.
2. Every keyword has a specific meaning; users can not change that meaning.
3. Keywords cannot be used as user defined names like variable, functions, arrays,
pointers etc...
4. Every keyword in C programming language represents some kind of action to be
performed by the compiler.

1.2.3 Identifiers:
The names of variables, functions, labels and various other user-defined objects
are called Identifiers. Identifiers are used for defining variable names, function names
etc. The general rules to be followed when constructing an identifier are:
1) Identifiers are a sequence of characters. The only characters allowed are alphabetic
characters, digits and the underscore character. Special characters are not allowed in
identifier name.
2) The first character of an identifier is a letter or an underscore character.
3) Identifiers are case sensitive. For example, the identifiers TOTAL and Total are
different.
4) Keywords are not allowed as identifier name.
VALID IDENTIFIERS:
Name area interest circum amount rate_of_interest sum
INVALID IDENTIFIERS:

1.2.4 Datatypes:
C supports several data types. Each data type may be represented differently
inside the computer’s memory. There are four data types in C language. They are,

Basic Data Types:


Basic or Fundamental data types include the data types at the lowest level. i.e.
those which are used for actual data representation in the memory. All other data types
are based on the fundamental data types.
Examples: char, int, float, double.
int type is used to store positive or negative integers. float data type is used to
store a single precision floating-point (real) number. Floating-point numbers are stored
in 32 bits with 6 digits of precision. double data type is used to hold real numbers with
higher storage range and accuracy than the type float. The data type char is used to
store one character.
The size (number of bytes) and range of numbers to be stored in each data type
is shown below.
Derived Data Types:
These are based on fundamental data types. i.e. a derived data type is
represented in the memory as a fundamental data type.
Examples: pointers, structures, arrays.
void data type :
1. void is an empty data type that has no value.
2. This can be used in functions and pointers.

1.2.5 Type Qualifiers:


 The basic data type may be modified by adding special keywords. These
special keywords are called data type modifiers (or) qualifiers. Data type
modifiers are used to produce new data types.
 The modifiers are: signed unsigned long short
 The above modifiers can be applied to integer and char types. Long can
also be applied to double type.
 signed and unsigned are called sign qualifiers these affects the sign of the
datatype.
 long and short qualifiers are called size qualifiers these affects the size of
the datatype.
Integer Type:
A signed integer constant is in the range of -32768 to +32767. Integer constant is
always stored in two bytes. In two bytes, it is impossible to store a number bigger than
+32767 and smaller than -32768. Out of the two bytes used to store an integer, the
leftmost bit is used to store the sign of the integer. So the remaining 15 bits are used to
store a number. If the leftmost bit is 1, then the number is negative. If the leftmost bit is
0, then the number is positive.
C has three classes of integer storage namely short int, int and long int. All of
these data types have signed and unsigned forms. A short int requires half the space
than normal size. Unsigned numbers are always positive and consume all the bits for
storing the magnitude of the number. The long and unsigned integers are used to declare
a longer range of values.
Floating Point Type:
Floating point number represents a real number with 6 digits precision. When
the accuracy of the floating point number is insufficient, use the double to define the
number. The double is same as float but with longer precision. To extend the precision
further , use long double, which consumes 80 bits of memory space.
Character Type:
Characters are usually stored in 8 bits of internal storage. The qualifier signed or
unsigned can be explicitly applied to char. While unsigned characters have values
between 0 and 255, signed characters have values from –-128 to 127.

1.2.6 Constants:
The data values are usually called as Constant. Constant is a quantity that does
not change during program execution. This quantity can be stored at a location in the
memory of the computer. C has four types of constants: Integer, Float, String and
Character.
Integer Constant:
An Integer Constant is an integer number. An integer constant is a sequence of
digits. There are 3 types of integers namely decimal integer, octal integer and
hexadecimal integer.
Decimal Integer consists of a set of digits 0 to 9 preceded by an optional + or -
sign. Spaces, commas and non digit characters are not permitted between digits.
Examples of decimal integer constants are : 123 -31 0 562321 + 78
Octal Integer constant consists of any combination of digits from 0 through 7
with a O at the beginning.
Examples of octal integers are : O26 O347 O676
Hexadecimal integer constant is preceded by OX or Ox. They may contain
alphabets from A to F or a to f. or a decimal digit ( 0 to 9). The alphabets A to F refers to
10 to 15 in decimal digits.
Example of valid hexadecimal integers are : OX2 OX8C OXbcd Ox123
Real Constant:
Real constants are numbers with fractional part. Real constants are often called
as Floating Point constants.
RULES:
1. A real constant must have atleast one digit.
2. It must have a decimal point.
3. It could be either positive or negative.
4. Default sign is positive (If no sign)
5. Special characters are not allowed.
6. Omitting of digit before the decimal point, or digits after the decimal point is allowed.
(Ex .655,12.)

Examples : +325.34 426.0 -32.76 -48.5792


Real Constants are represented in two forms:
i i) Fractional form
ii ii) Exponential form
EXPONENTIAL FORM or SCIENTIFIC FORM
The Exponential form is used to represent very large and very small numbers.
The exponential form representation has two parts: 1) mantissa and 2) exponent. The
part appears before the letter ‘e’ is called mantissa and the part following the letter ‘e’ is
called exponent, which represents a power of ten. The general form of exponential
representation is.
mantissa e exponent
where “mantissa” is a decimal or integer quantity and the “exponent” is an integer
quantity with an optional plus or minus sign.
The general rules regarding exponential forms are
1. The two parts should be separated by a letter “e” or “E”.
2. The mantissa and exponent part may have a positive or a negative sign.
3. Default sign of mantissa and exponent part is positive.
4. The exponent must have at least one digit.
Examples:
The value 123.4 may be written as 1.234E+2 or 12.34E+1.
The value 0.01234 may be written as 1.234E-2 or 12.34E-3.
Differences between floating point numbers and integer numbers.
• Integer includes only whole numbers, but floating point numbers can be either whole
or fractional.
• Integers are always exact, whereas floating point numbers sometimes can lead to loss
of mathematical precision.
• Floating point operations are slower in execution and often occupy more memory than
integer operations.
Character Constants:
A character constant is either a single alphabet, a single digit or a single special
character enclosed within a pair of single inverted commas.
The maximum length of a character constant can be 1 character
Examples: ‘A’ ‘1’ ‘$’ ‘‘ ‘;’
Each character constant has an integer value. This value is known as ASCII value.
For example, the statement printf (“”%d””,’A’) would print the value of 65. Because the
ASCII value of A is 65.
Similarly the statement printf (“%c”,65) would display the letter ‘A’.
String Constants:
A combination of characters enclosed within a pair of double inverted commas is
called as “String Constant”.
Examples: “Salem” “35.567” “$125” “Rose”
Each string constant ends with a special character ‘\0’. This character is not
visible when the string is displayed. Thus “salem” contains actually 6 characters. The ‘\
0’ character acts as a string terminator. This character is used to find the end of a string.
Remember that a character constant (e.g., ‘A’ ) and the corresponding single-
character string constant ("A") are not equivalent.
A character constant has an equivalent integer value, whereas a single-
character string constant does not have an equivalent integer value and, in fact,
consists of two characters - the specified character followed by the null character
( \ 0).

1.2.7 Escape Sequences:


Character combinations consisting of a backslash (\) followed by a letter or by a
combination of digits are called "escape sequences." To represent a newline character,
single quotation mark, or certain other characters in a character constant, escape
sequences are used. An escape sequence is regarded as a single character and is
therefore valid as a character constant.
• The escape sequence characters are also called as backslash character constants.
• These are used for formatting the output

For example, a line feed (LF), which is referred to as a newline in C, can be


represented as \n. Such escape sequences always represent single characters, even
though they are written in terms of two or more characters. The commonly used escape
sequences are listed below.
The following program outputs a new line and a tab and then prints the string This is a
test.
#include <stdio.h>
void main()
{
printf(''\n\tHiiiiiiiii.");
}
Characteristics
• Although it consists of two characters, it represents single character.
• Every combination starts with back slash(\)
• They are non-printing characters.
• It can also be expressed in terms of octal digits or hexadecimal sequence.
• Each escape sequence has unique ASCII value.
1.2.8 Sympolic Constants:
• Names given to values that cannot be changed. Implemented with the #define
preprocessor
directive.
#define N 3000
#define FALSE 0
• Preprocessor statements begin with a # symbol, and are NOT terminated by a
semicolon. Traditionally, preprocessor statements are listed at the beginning of the
source file.
• Preprocessor statements are handled by the compiler (or preprocessor) before the
program is actually compiled. All # statements are processed first, and the symbols (like
N) which occur in the C program are replaced by their value (like 3000). Once this
substitution has taken place by the preprocessor, the program is then compiled.
• In general, preprocessor constants are written in UPPERCASE. This acts as a form of
internal documentation to enhance program readability and reuse.
• In the program itself, values cannot be assigned to symbolic constants.
Use of Symbolic Constants
• Consider the following program which defines a constant called TAXRATE.
#include <stdio.h>
#define TAXRATE 0.10
main () {
float balance;
float tax;
balance = 72.10;
tax = balance * TAXRATE;
printf("The tax on %.2f is %.2f\n",balance, tax);
}

1.2.9 Variables:
A quantity, which may vary during program execution, is called variable. Variables
may be used to store a data value. Variables are actually memory locations , used to
store constants. The variables are identified by names. The program may modify the
values stored in a variable.
Rules for constructing variable names:
1. A variable name is the combination of characters. The length of a variable depends
upon the complier.
2. The first character must be an alphabet or underscore.
3. Special characters like comma or blank are not allowed except an underscore
character. The only characters allowed are letters, digits and underscore.
4. The variable name should not be a keyword.

Examples : area interest circumference fact date_of_birth

1.2.9.1 Declaration of Variables:


In C, all the variables used in a program are to be declared before they can be
used. All variables must be declared in the beginning of the function. Type declaration
statement is used to declare the type of various variables used in the program.
The syntax for declaration is,
data_type variable_names

where data-type is a valid data type plus any other modifiers. variable-name(s) may
contain one or more variable names separated by commas.
Examples : int a, b, c;
long int interest;
unsigned char ch;
Declaration statement is used to allocate memory space for the variable.
Declaration statement also provides a name for the location. Declaration statement
declares that the program will use that variable name to identify the value stored at the
location.

1.2.9.2 Assigning values to variables:


The process of assigning initial values to variables is called initialization of
variables. In C, an uninitialised variable can contain any garbage value. Therefore, the
programmer must make sure all the variables are initialised before using them in any of
the expressions. The value for a particular variable is initialized through declarative
statement or assignment statement. For example to initialize the value 10 to an integer
variable i, the following two methods are used.

i) int i = 10;
ii) int i;
i = 10;
The above two methods declares that i is an integer variable with an initial value of 10.
Examples : (i) float pi = 3.14; (ii) char alpha = ‘’h’’; (iii) int account = 10;
More than one variable can be initialized in a single statement. For example, the
statement
int x = 1, y = 2, z;
declares x to be an int with value 1, y to be an int with value 2 and z to be an int
of unpredictable value. Same value can be initialized to several variables with the single
assignment statement.
Examples :
int i, j, k, l, m, n;
float a, b, c, d, e, f;
i = j = k = l = m = n = 20;
a = b = c= d = e = f = 13.56;

1.2.10 Comments:
Comments are used to make a program more readable. Comments are not
instructions. Comments are remarks written in a program. These remarks are used to
give more information about the program. The compiler will ignore the comment
statements.
In C, there are two types of comments.
1. Single Line Comments: Single line comment begins with // symbol. Any number of
single line comments can be written.
2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends
with */. Any number of multiple lines comments can be included in a program.

In a C program, the comment lines are optional. All the comment lines in a C
program just provide the guidelines to understand the program and its code.
Examples:
(e.g.) /* Program to find the Factorial */
Any number of comments can be placed at any place in a program. Comments cannot be
nested. For example
/* Author Arul /* date 01/09/93 */ */ is not possible.
A comment can be split over more than one line. For example, the following is valid.
/* This statement is used to find the sum of two
numbers */
1.3 C OPERATORS:
1.3.1 Operator:
An operator is a symbol which represents some operation that can be performed
on data.
Types of Operators:
1.Arithmetic Operators
2.Relational Operators
3.Logical Operators
4.Increment and Decrement Operators
5.Conditional Operators
6.Assignment Operators
7.Special Operators
8.Bitwise Operators
1.Arithmetic Operators:
Arithmetic Operators are used to do arithmetic calculations.
Operator Operation Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Remainder a%b

Program:
#include<stdio.h>
void main()
{
int a=10,b=5;
printf(“Addition=%d”,a+b);
printf(“Subtraction=%d”,a-b);
printf(“Multiplication=%d”,a*b);
printf(“Division=%d”,a/b);
printf(“Remainder=%d”,a%b);
}

2.Relational Operators:
 Relational Operators are used to compare two values.
 Relational Operators has two results TRUE or FALSE.

Operator Operation Example


> Greater than a>b
< Less than a<b
>= Greater than or equal to a>=b
<= Less than or equal to a<=b
== Equal to Equal to a==b
!= Not equal to a!=b

program:
#include<stdio.h>
void main()
{
int a=10,b=5;
if(a>b)
printf(“a is big”);
else
printf(“b is big”);
}

3.Logical Operators:
The Logical Operators are used to combine multiple conditions into one
condition.

Operator Operation Example


&& Logical AND (a>b)&&(a>c)
|| Logical OR (a>b)||(a>c)
! Logical NOT !(a>=b)

Program:
#include<stdio.h>
void main()
{
int a=5,b=4,c=15;
if((a>b)&&(a>c))
printf(“a is big”);
else if(b>c)
printf(“b is big”);
else
printf(“c is big”);
}

4.Increment and Decrement Operators:

Operator Operation Example


++ Increment by 1 a++
--- Decrement by 1 --a
Increment Operator:
++ is the increment operator. This adds 1 to the value contained in the variable.
Syntax:
++variable Pre Increment
variable++ Post Increment
Decrement Operator:
-- is the decrement operator. This subtracts 1 to the value contained in the
variable.
Syntax:
--variable Pre Decrement
variable-- Post Decrement
Program:
#include<stdio.h>
void main()
{
int a=5;
printf(“%d”,a++);
printf(“%d”,a--);
}

5.Conditional Operators:
The Conditional Operators ? and : are used to build simple conditional
expression.
It requires three data so it is called as Ternary Operator.
Syntax:
expr1?expr2:expr3;
Example: (a>b)?a:b;
Program:
#include<stdio.h>
void main()
{
int a=5,b=2,c;
c=(a>b)?a:b;
printf(“%d is big”,c);
}

6.Assignment Operators:
Assignment operators are used to simplify the coding of certain type of
assignment statement.

Operator Example
= x=10
+= x+=10 [x=x+10]
-= x-=10 [x=x-10]
*= x*=10 [x=x*10]
/= x/=10 [x=x/10]
%= x%=10 [x=x%10]

Program:
#include<stdio.h>
void main()
{
int x=10;
printf(“%d”,x+=10);
printf(“%d”,x-=10);
printf(“%d”,x/=10);
printf(“%d”,x*=10);
}

7.Bitwise Operators:

Bitwise Operators are used to perform bit by bit calculations.

Operator Operation Example


& Bitwise AND a&b
| Bitwise OR a|b
^ Bitwise XOR a^b
>> Right Shift a>>b
<< Left Shift a<<b
~ Bitwise NOT ~a

Program:
#include<stdio.h>
void main()
{
int a=5,b=2;
printf(“%d”,a&b);
printf(“%d”,a|b);
printf(“%d”,~b);
}

8.Special Operators:
C supports some special operators like comma operator, sizeof operator, pointer
operators (& and *) and member selection operators (. And ->).
Comma Operator:
Comma operator is used in the assignment statement to assign many values to
many variables.
Example: int a=10, b= 20, c- 30;
Comma operator is also used in for loop in all the three fields.
Example: for (i=0, j=2; i<10; i=i+1;j=j+2);
sizeof Operator: Another unary operator is the sizeof operator . This operator returns
the size of its operand, in bytes. This operator always precedes its operand. The
operand may be a variable, a constant or a data type qualifier.
Consider the following program.
main()
{
int sum;
printf("%d", sizeof(float));
printf("%d", sizeof (sum));
printf("%d", sizeof (234L));
printf("%d", sizeof ('A'));
}
Here the first printf( ) would print out 4 since a float is always 4 bytes long. With
this reasoning, the next three printf( ) statements would output 2, 4 and 2. Consider an
array school[]= “National” . Then, sizeof (school) statement will give the result as 8.
Pointer Operator:
Pointer Operator ‘*’ is used to define pointer variable.
Example: int *a;
Dot Operator:
Dot operator ‘.’ is used to access the members of the structure or union.

1.3.2 Operator Precedence and Associativity:


Operator Precedence:
Operator precedence is used to determine the order of operators evaluated in an
expression. In C, every operator has precedence when there is more than one operator
in an expression the operator with higher precedence is evaluated first and the operator
with least precedence is evaluated last.
Operator Associativity:
Operator Associativity is used to determine the order of operator with equal
precedence evaluated in an expression.

Order Category Operator Operation Associativity


1 Highest () Function call L→R
precedence [] Left to Right

.
2 Unary ! Logical R→L
~ negation (NOT) Right -> Left
+ Bitwise 1’s
- omplement
++ Unary plus
-- Unary minus
& Pre or post
* increment Pre
size of or post
decrement
Address
Indirection
Size of operant
in bytes
3 Multiplication * Multiply Divide L → R
/ Modulus
%
4 Additive + Binary Plus L→R
- Binary Minus
5 Shift << Left shift Right L→R
>> shift
6 Relational < Less than Less L→R
<= than or equal
> to Greater than
>= Greater than or
equal to
7 Equality == Equal to L→R
!= Not Equal to
8 Bitwise AND & Bitwise AND L→R
9 Bitwise XOR ^ Bitwise XOR L→R
10 Bitwise OR | Bitwise OR L→R
11 Logical AND && Logical AND L→R
12 Conditional ?: Ternary R→L
Operator
13 Assignment = Assignment R→L
*= Assign product
%= Assign
/= reminder
+= Assign quotient
-= Assign sum
Assign
difference
14 Comma , Evaluate L→R

1.3.3 C expressions and its types:


C Expression:
An expression is the combination of Variables and Constants connected by any
one of the operators.
Types of C Expressions:
i)Arithmetic Expressions
ii)Relational Expressions
iii)Logical Expressions
i)Arithmetic Expressions:
Arithmetic expression is the combination of Variables and Constants connected
by any one of the arithmetic operators.
Syntax:

Constant Constant
(or) Arithmetic Operator (or)
Variable Variable

Example:
i) x-z ii)x+y*2 iii)4+2/6

ii)Relational Expressions:
Relational expression is the combination of Variables, Constants and Arithmetic
expressions connected by any one of the relational operators.
Syntax:

Constant Constant
(or) (or)
Variable Relational Operator Variable
(or) (or)
Arithmetic Expression Arithmetic Expression

Example:
i) x>z ii)(x+y)<2 iii)4<=6

iii)Logical Expressions:
Logical expression is formed by connecting relational expression by logical
operators.

Syntax:

Relational Relational
Logical Operator
Expression Expression

Example:
i) (a<b)&&(a>b) ii)(a==2)||(a>2)

1.3.4 Evaluation of Expressions:


While evaluating an expression the computer scans the expression from left to
right and in each scan, it evaluates the expression in the following order
1. It does all expressions inside the parenthesis.
2. It does all unary operations.
3. It does all multiplication, division and remainder operations in the order.
4. It does all addition and subtraction in the order.
5. It does all relational and logical operations.
6. It does all assignment operations.

Example 1: Determine the hierarchy of operations and evaluate the following


expression:
k=3/2*4+3/8+3
k=3/2*4+3/8+3
k = 1 * 4 + 3 / 8 + 3 operation: /
k = 4 + 3 / 8 + 3 operation: *
k = 4 + 0 + 3 operation: /
k = 4 + 3 operation: +
k = 7 operation +

Example 2: Determine the hierarchy of operations and evaluate the following


expression:
i=2*3/4+4/4+8-2+5/8
Stepwise evaluation of this expression is shown below:
i=2*3/4+4/4+8-2+5/8
i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: *
i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i = 1 + 1 + 8 - 2 + 0 operation: /
i = 2 + 8 - 2 + 0 operation: +
i = 10 - 2 + 0 operation: +
i = 8 + 0 operation : -
i = 8 operation: +
Note that 6 / 4 gives 1 and not 1.5. This so happens because 6 and 4 both are integers
and therefore would evaluate to only an integer constant. Similarly 5 / 8 evaluates to
zero, since 5 and 8 are integer constants and hence must return an integer value.

1.3.5 Type Conversion:


Type conversion is defined as a process of converting data in an expression from
one datatype into another datatype during execution.

Types of Type Conversion:


1) Automatic Type conversion
2) Explicit Type conversion
1) Automatic Type conversion:
If the data in an expression are of different type then the lower type data is
automatically converted into higher datatype before execution. This process of
conversion is called automatic type conversion.

Example:
int a=2,b=3;
float c;
c=a+b;
Answer: c=5.0

ii) Explicit Type conversion:


The process of converting one datatype data into another datatype data locally
without affecting it’s result is called explicit type conversion.

Syntax:
(datatype)Variable or Constant;
Example:
int x;
x=(int) 5.4;
Answer:x=5

You might also like