[go: up one dir, main page]

0% found this document useful (0 votes)
2 views28 pages

2Introduction_to_C

The document provides an introduction to the C programming language, detailing its history, features, and advantages. It covers the structure of C programs, types of errors, and the process of developing C programs, including compiling and executing them. Additionally, it explains key concepts such as tokens, keywords, identifiers, constants, and the overall syntax of C programming.

Uploaded by

anshureddy0612
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)
2 views28 pages

2Introduction_to_C

The document provides an introduction to the C programming language, detailing its history, features, and advantages. It covers the structure of C programs, types of errors, and the process of developing C programs, including compiling and executing them. Additionally, it explains key concepts such as tokens, keywords, identifiers, constants, and the overall syntax of C programming.

Uploaded by

anshureddy0612
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
You are on page 1/ 28

Introduction to C 2019

Introduction to C Language
Introduction to C
 C is a general purpose programming language developed by Dennis Ritchie at A T & T Bell
laboratories in 1972.
 C is closely related to UNIX system and many of the important ideas are taken from “BCPL”
(Basic Combined Programming Language) developed by Martin Richards and “B” language.
 C provides variety of data types, derived data types like pointers, arrays, structures and unions.
 It also provides control flow constructions like conditional and looping constructs etc..,

Why C?
 Generally computer understands only binary data i.e., 0’s and 1’s.
 Writing and understanding programs in binary was very difficult and time consuming.
 To overcome this middle level language was introduced; the user feels comfortable in writing the
program.
 Many middle levels languages are available like C, C++ etc..
 Even though the program is written in middle level language, the code has to be converted to
machine language so that computer can execute it for which we make use of compiler.

Advantages/Features of C Language
There are many features which attracted programmers for the usage of C. They are
1. Simple and Portable: it gives programmer access to all functions of the machine and can
work on different kinds of computers.
2. Powerful and Flexible: most of the functionalities like UNIX is written in C. The compiler
and interpreter is also written in C language.
3. Modularity: C is a structured programming language which mainly deals with the
procedures. It is also termed as procedure oriented language.
4. Efficient: C is more efficient which increases the speed of execution and management of
memory compared to low level languages.
5. Programmer oriented: It has many data types and flexible control structure which gives
access to hardware.
6. Other features include
 Machine independent
 No need to worry about machine details.

1 Mr.Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Characteristics of C:
 C is a middle level language.
 C is a structured language.
 C is a programmer’s language.
 C is a case sensitive language.

Versions of C:
The main is ANSI C (accepted by American National Standards Institute) under which we have
 Lattice C  Turbo C  Tiny C
 Microsoft C  Borland C  Etc….
 Quick C  Small C
Developing Programs in C:
1. Creating the Program :
The source program can be written or modified using editor and can be saved with
the extension of .C
2. Compiling the program.
Where the program is checked for the Syntax and Semantics of the language and
reports the errors to the user. These errors have to be corrected by the users in the source
program.
3. Executing the Program.
Once the error free code is generated after the compilation process, the program
can be executed with valid inputs by linking to the required header files.
For the successful execution of the C Program some of the software components are
required they are:
 Operating System.  Assembler.
 Text Editors.  Loader.
 Compilers.  Linker.

On the successful execution of the C Program the following files are created:
1. Pgm.C: Contains source code of the program saved in .C extension.
2. Pgm.txt: Contains text format of the source code stored in .txt a notepad file.
3. Pgm.obj: Contains the object code of source program in terms of 0’s & 1’s.
4. Pgm.exe: An Executable file generated after successful compilation.
5. Pgm.bak: An backup file for the Pgm.C
2 Mr.Sukruth Gowda M A, Assistant Professor
Introduction to C 2019
Typical steps for Entering, Compiling and Executing C programs

C Source Code

Preprocessed Code

Assembly Code

Libraries and
other object
modules Object Code

Executable Code
Such as Hard disk as an
Executable image.

When running /execute


the program

Error and Its Type


Error is also known as bug in the world of programming, it may occur unwillingly which may
prevent the program to compile and run correctly as per the expectation of the programmer.
Programmer may come across with the following types of errors..,

 Syntax Error: errors due to the fact that the syntax of the language is not respected.
Example: int a=20 // Error: Statement missing (;)
 Semantic Error: errors due to the improper use of program statements.
Example 1.int i; // Error: Static semantic error @ compile time.
i++; // Error: Variable “i” is not initialized.

Example 2.int a[10]; // Error: Dynamic semantic error @ run time.


a[10]=40; // Error: Invalid Initialization of 11 position with
value 40.
3 Mr. Sukruth Gowda M A, Assistant Professor
Introduction to C 2019
 Logical Error: errors due to the fact that the specification is not respected.
Example: // Program for addition of two numbers.
int a=20, b=10, c;
c=a-b;
// Error: in logic subtraction is done instead of addition.

At the time of error detection it is classified in to two types:


 Compile Time Errors: Syntaxand Static Semantic errors indicated by the compiler.
 Runtime Errors: Dynamic semantic errors and logical errors that cannot be detected by the
compiler.

Note:
 Debugging: The process of identifying the errors and correcting it.
 Source Code: The text of a program that a user can read, modify and given as a input for the
C compiler.
 Object Code: Translated code generated by the compiler by taking source code as the input
and computer can executes it directly.
 Compile Time: The time during which your program is being compiled.
 Run Time: The time during which your program is executing.
 Short Cut keys:
 Menu: F10.
 Saving: Alt + F2.
 Opening the Existed program: F3.
 Compilation: F9.
 Execution: Ctrl + F9.
 To see the previously Executed screen: Alt + F5.
 Single Tab View: F5.
 To Maximize the Screen: Alt + Enter.

4 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019

Concepts of C Programming
Structure of C Program
Comments/Documentation Section
Preprocessor Directives
Global Declaration Section
void main( ) [Program Header]
{
Local Declaration part
Execution part
Statement 1
------------
------------
Statement n
}
User Defined Functions

Comments/Documentation Section
 Describes the program, which helps in understanding the program easily.
 The comments are not mandatory.
 The comment are may be of:
 Single line Comment:
 Description is written in single line with the delimiter //.
 Example: //Program to multiply two numbers.
 Multi line Comment:
 It is written in more than one line.
 Begins with /* and ends with */. The symbols /* and */ are called comment line
delimiters
 Example :
/*Program to find the roots of the Quadratic equation on checking for value of a not
equal to 0 and condition for roots are real and equal, real and distinct & Imaginary*/

Note: Comments are ignored by C compiler, i.e. everything within comment delimiters

5 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Preprocessor Directives
 Preprocessor Directives begins with a # symbol.
 It preprocesses the include files, conditional compilation instructions and macros before it
encounters the main( ) function.
 A function is a building block of a program where it performs a particular task, on execution it
should return some type of value to where it is called.
 Some examples of preprocessor statements are:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <math.h>
#define PI 3.142 Etc…
Global Declaration Section
 There will be some variable which has to be used throughout / anywhere in program i.e.., the
scope of the variable is in more than one function can bedeclared in global Declaration Section
.

The Program Header


 Every program must contain a main() function. The execution always starts from main
function.
 Every C program must have only one main function.
 void is the return type mentioned with main( ) , which represents main( ) returning nothing.

Body of the program


 Series of statements that performs specific task will be enclosed within braces { and }
 It is present immediately after program header.
It consists of two parts
1. Local Declaration part: Describes variables used in the program
Ex: int sum = 0;
int a , b:
float b;
2. Executable part: Contains input statements, processing statements (logic) & output
statements to carry out some particular task.
Note: All statements should end with semicolon(; ) a statement terminator.

User Define Function / Subroutine Section:


 All user defined functions that are called in main function should be defined.

6 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019

C Programming Concepts
 A program is a group of instructions given by the programmer to perform a specific task.
 To achieve programming there are many basic components of programming that has to be
learnt.
Character set of C language
The C language includes the characters.
 Alphabets(lowercase a-z, Uppercase A-Z)
 Digits (0-9)
 Special Symbols( ~ ‘ ! @ # % & * () - + / $ = \ { } [ ] : ; “ “ ? etc)
C- Tokens
 Tokens are the smallest individual units of C program.
 A token is collection of characters.
 Some of the C- Tokens available in C are:

Keywords
 Words which have predefined / fixed meanings are called keywords.
 These are basic building blocks of C program statements.
 The meaning of keywords will be known to computer no new name or meaning can be defined
for it.
 There are totally 32 keywords supported in C they are:
Auto double if Static
break else int Struct
case enum long Switch
char extern near Typedef
const float register Union
continue for return Unsigned
default while short Void
Do goto signed While

7 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Important points to be remembered about keywords
 Keywords should be written in lowercase letters.
 Keywords meaning cannot be changed by the users.
 It should not be used as variables, functions names and array names.

Identifiers or Variables
 Identifiers are the name given to the program element.
 The program element may be identified as variables, functions and arrays etc..,
 These are user defined names and do not have fixed meaning.
 It is name given to computer memory location.

Variables – Variables are the identifiers, the named memory location whose value changes on
program execution.
Rules for identifiers/variables
 First character must be an alphabet or an underscore(_)
 First character is followed by any number of letters or digits.
 Only first 31 characters are significant
 Keywords cannot be used as identifier / variable.
 Must not contain blank space/white space
 Must contain only alphabets, digits and one special symbol underscore ( _ )
 Two successive underscore is not permitted

Ex:-
india Valid
india06 Valid
_india Valid
india_06 Valid
india_06_king Valid
_ _india not valid as it contains successive underscore
06india not valid as it starts from digits
Int not valid since int is a keyword
india 06 not valid since there is space between india and 06
india@06 not valid since @ is not allowed

8 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Constants
Constants are the named memory location; it refers to fixed values that do not change during the
execution of a program.
We have different types of constants
1. Integer constant
2. Real constant/Floating Pointing
3. Character constant Ex: ‘a’, ‘9’, ‘\n’
4. String constant Ex: “INDIA”, “8”
Integer constant:
 It refers to sequence of digits
 Embedded spaces, commas, characters should not be included.
 Must not contain a decimal point.
 May be signed or unsigned. (default is +)

Three types of integers


 Decimal integers: Consist of digits 0 to 9
Ex: 123 -345 0 5436 +79
 Octal integers: Digits from 0 to 7 but it has to start with 0
Ex: 027 0657 0777645
 Hexadecimal integers:Digits from 0 to 9 and characters from a to f, it has to start with 0X or
0x
Ex: 0X2 0x56 0X5fd 0xbdae
Real constants/Floating point:
The numbers that are represented by fractional parts are called real constants.
Two forms
1. Fractional form:
 Digits from 0 to 9, sign (+ or -), dot(.)
 Ex: 0.0083 215. -71. +0.56 etc..
2. Exponential form:
 Syntax: mantissa e exponent
 Mantissa is either real number expressed in decimal notation or integer.
 Exponent is integer with optional + or –
 Ex: 0.65e4 3.18e-2 73e+3 12e+5

9 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Character Constant:

 Character Constant Can hold Single character at a time.


 Contains Single Character Closed within a pair of Single Quote Marks
 Single Character is smallest Character Data Type in C.
 Integer Representation : Character Constant have Integer Value known as ‘ASCII’ value
 It is Possible to Perform Arithmetic Operations on Character Constants
Examples: ‘a’ ,‘1’ , ‘#’ , ‘<‘ , ‘X’

String Constant
 A character string, a string constant consists of a sequence of characters enclosed in double
quotes.
 A string constant may consist of any combination of digits, letters, escaped sequences and
spaces.
 Note that a character constant ‫ۥ‬A’ and the corresponding single character string constant "A"
are not equivalent.
 The string constant "A" consists of character A and \0. However, a single character string
constant does not have an equivalent integer value. It occupies two bytes, one for the ASCII
code of A and another for the NULL character with a value 0, which is used to terminate all
strings.
 Valid String Constants: -
"W"
"100"
"24, Kaja Street"
 Invalid String Constants: -
"W the closing double quotes missing
Raja" the beginning double quotes missing
 Rules for Constructing String constants
 A string constant may consist of any combination of digits, letters, escaped sequences
and spaces enclosed in double quotes.
 Every string constant ends up with a NULL character which is automatically assigned
(before the closing double quotation mark) by the compiler.

10 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
 Difference between single character constant and string constant

Character Constant String Constant


A character constant is enclosed A sequence of characters enclosed in
within single inverted commas. double quotes.
The maximum length of a character A string constant can be any length.
constant can be one character.
A single character string constant has A single character string constant
an equivalent integer value. does not have an equivalent integer
value.
The character constant ‘A’ consists of The string constant "A" consists of
only character A. character A and \0.
A single character constant occupies A single string constant occupies two
one byte. bytes.
Every character constant does not end Every string constant ends up with a
up with a NULL character NULL character which is
automaticallyassigned (before the
closing double quotation mark) by
the compiler.

Data types
 The data type defines the type of data stored in memory location or the type of data the
variable can hold.
Data Types classification:

 Primary data types – are the fundamental data types which are readily available in C.
 Secondary data types – are the derived types with the help of primary data types.

11 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Character data type (char):
 Capable of holding one character from the local character set.
 The size of the character variable is 1 byte.
 The range is from -128 to +127.
 Each character stored in the memory is associated with a unique value termed as ASCII
(American Standard Code for Information Interchange).
 It is used to represent character and strings.

Integer data type (int):


 It stores an integer value or integer constant.
 Typically reflects the natural size of integers on host machine.
 General size is 2 bytes.
 The range is -32768 to +32767 ( To calculate the size 1 byte =8bits so 2bytes will be 16 bits
then range will be -215 to +215 -1).
 int can have additional data type which is long int whose size will be of 4 bytes and the size
ranging from -231 to +231 -1.

Floating data type (float):


 Single precision floating point.
 Holds a real constant.
 The size is 4 bytes.
 The range is -3.4e38 to +3.4e38.
 Float can hold the real constant accuracy up to 6 digits after the decimal point. That is
23.456789 is valid where as 45.678953231 is invalid.
Double data type (double):
 Double precision point.
 Holds real constant.
 The size is 8 bytes.
 The range is from -1.7e308 to +1.7 e308.
 Double can hold real constant accuracy up to 16 digits after the decimal point.

Void data type (void):


 It is an empty data type.
 No memory is allocated.Mainly used when there are no return values on function execution.

12 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019

Table Contains All Data Types Defined by the C Standard

Sizes in
Sl. No Data Type Range
Bits Bytes
1 char 8 1 -128 to 127
2 unsigned char 8 1 0 to 255
3 signed char 8 1 -128 to 127
4 int 16 2 -32,768 to 32,767
5 unsigned int 16 2 0 to 65,535
6 signed int 16 2 -32,768 to 32,767
7 short int 16 2 -32,768 to 32,767
8 unsigned short int 16 2 0 to 65,535
9 signed short int 16 2 -32,768 to 32,767
10 long int 32 4 -2,147,483,648 to 2,147,483,647
11 long longint 64 8 -(263 -1) to (263 -1) (Added by C99)
12 signed long int 32 4 -2,147,483,648 to 2,147,483,647
13 unsigned long int 32 4 0 to 4,294,967,295
14 unsigned long longint 64 8 264 – 1 (Added by C99)
15 float 32 4 -3.4E38 to +3.4E38 with six digits of precision
16 double 64 8 1.7e308 to +1.7 e308 with ten digits of precision

Format Specifiers
 Format specifiers are the character string with % sign followed with a character. It specifies
the type of data that is being processed. It is also called conversion specifier. When data is
being output or input it must be specified with identifier (variable) and their format specifier.
 There are many format specifiers defined in C. Take a look at the following list:

Symbols Meaning
%i or %d integer number
%f float point number
%c Character
%o octal number
%x hexadecimal integer(Lower case letter x)
%X hexadecimal integer(Upper case letter X)
%e floating point value with exponent(Lower case letter e)
%E floating point value with exponent (Upper case letter E)
%g floating point value with or without exponent
%ld long integer
%s String
%lf double

13 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Escape sequence:
 Escape sequence are special character denoted by a backslash (\) and a character after it. It is
called escape sequence because it causes an ‘escape’ from the normal way for characters are
interpreted. For example if we use ‘\ n’, then the character is not treated as n but it is treated as
a new line. Some of the common escape sequence characters are:

Escape sequence Meaning


\a Bell
\ Beep
\n new line
\t tab horizontal
\b move the character to left one space
\\ Backslash
\’ single quote
\” double quote
Variables:
 Variables are the identifiers, the named memory location whose value changes on program
execution.
Declaration of variables:
 The declaration tells the computer which storage locations or variables to use in the program.
 The variables which will be used in the program should be declared at the beginning of the
program.
 The variable declaration indicates the type of constant that the variable can hold and the
amount of memory allocated to the variable.
 The name of the variables should be declared as per the rules of declaring identifiers or
variables.
 General Syntax: datatype variable;
(or)
datatype variable1, variable2,……..variable_n;
Example: 1. int a; 2. float x,y; 3. double sum, midun_06;
 From the examples we will come to know that
 “a” is a variable of type integer and allocates 2 bytes of memory.
 “x” and “y” are two variable of type float which will be allocated 4 bytes of memory for each
variable.
 “sum” and “midun_06” are two double type variables which will be allocated with 8 bytes of
memory for each.

14 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Variable Initialization:
 Variables can be initialized at two instances -
 Compile Time ( using Assignment Statement )
 Run Time ( using Standard Input function : scanf( ))

Compile Time Initialization: Assignment statement -


 Declaration indicates only creating space for variables but doesn’t assigns any value.
 General Syntax: Var_name = expr;
Where,
Var_name is the name of the variable ,
expr is the value of the expression or the constant value.
 The “expr” on the right hand side is evaluated and stored in the variable name (Var_name) on
left hand side.
 The expression on the right hand side may be a constant, variable or a larger formula built
from simple expressions by arithmetic operators.
Examples:
1. int a=10; // assigns the value 10 to the integer variable a
2. float x;
x=20; // creates a variable y of float type and assigns value 20 to it.
3. int a=10,b;b=a; // creates two variables a and b. “a” is assigned with value 10,
the value of “a” is assigned to variable “b”. Now the value of b will be 10.
Other Assignment Statements:
 price = cost*3; //assigns the product of cost and 3 to price.
 Square = num*num; // assigns the product of num with num to square.
Run Time Initialization :scanf( ) statement -
 To enter the input through the standard input devices like keyboard we make use of scanf
statement.
 In this initialization of the variables is done at run time.
 General Syntax:scanf(“format string”,list of address of variables);
Where: Format string consists of the access specifiers.
List of addresses of variables consist of the variable name preceded with & symbol.
Example: int a;
float b;
scanf(“%d%f”,&a,&b);
15 Mr. Sukruth Gowda M A, Assistant Professor
Introduction to C 2019
Operators:
 What is an operator?
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.
 What is an operand?
A constant or a variable or a function which returns a value is an operand. An operator may have
one or two or three operands.
Example: a+b-c*d/e%f
In this example there are :
6 operands i.e.., a, b, c, d, e, f
5 operators i.e.., +,-,*,/ and %.
What are the types of operators?
 C operators can be classified into a number of categories based on type of operation
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic operators
 C provides all basic arithmetic operators. The operators are +, - ,* , / , %.
 Let a=10, b=5. Here, a and b are variables and are known as operands.
Description Symbol Example Result Priority

Addition + a+b = 10 + 5 15 2

Subtraction - a-b = 10 – 5 5 2

Multiplication * a* b = 10 * 5 50 1

Division(Quotient) / a/b = 10/5 2 1

Modulus(Reminder) % a % b = 10 % 5 0 1

16 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019

 /*Program to illustrate the use of arithmetic operators is given below*/


#include<stdio.h>
void main()
{
int a=30,b=5,c,d,e,f,g;
c=a+b;
d=a-b;
e=a*b;
f=a/b;
g=a%b;
printf(“%d, %d, %d ,%d ,%d\n”, c,d,e,f,g);
}
Output: 35,25,150,6,0
Relational Operators
 We often compare two quantities depending on their relation, take certain decisions.
 For example, we compare the age of two persons, or the price of two items, and so on. These
comparisons can be done with the help of relational operators.
An expression such as
A< B or 1<20
 Expression with a relational operator is termed as a relational expression. The value of
relational expression is either one or zero. It is one if the specified relation is true and zero if
the relation is false.
Example: 10 < 20 is true.
20 < 10 is false.
 C supports six relational operators in all. These operators are

Operator Meaning Priority


< is less than 1
<= is less than or equal to 1
> is greater than 1
>= is greater than or equal to 1
== is Equal to 2
!= is not equal to 2

 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.

17 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Example: a+b>c+d
 In the above example first it will perform addition operation on both sides and afterwards it
will compare the results.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.
Operator Meaning
&&logical AND
|| logical OR
! logical NOT

 The logical operators && and | | are used when we want to test more than one condition and
make decisions.
Example: a>b && x==10
 The above logical expression 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.
Assignment Operators
 Assignment operators are used to assign the result of an expression to a variable or the RHS
value to the LHS variable. We have seen the usual assignment operator,‟=‟.
 In addition, C has a set of “shorthand‟ assignment operators of the form. (+=,-=,/=,*=,etc..)
 Syntax: v op = exp;
Where: v is a variable,
exp is an expression
op is a C library arithmetic operator
op= is known as the shorthand assignment operator.
 The assignment statement:
v op= exp;
is equivalent to v= v op (exp).
with v evaluated only once.

 Consider an example
x + = y+1;
This is same as the statement

18 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
x = x+ (y+1);
Increment and Decrement Operators
 C allows two very useful operators not generally found in other languages. These are the
increment and decrement operators:
++ and --
 The operator ++ adds 1 to the operand value, while -- subtracts 1. Both are unary operators
takes the following.
 ++m; or m++;
 --m; or m--;
 ++m is equivalent to m=m+1;
 --m is equivalent to m=m-1;
 We use increment and decrement statements in for and while loops extensively. While ++m
and m++ mean the same thing when they form the statements independently, they behave
differently when they are used in expressions on the right hand side of an assignment
statement.
 Consider the following
1. m=5;
y=++m; // In this case, the value of y and m would be 6.
Suppose, if we rewrite the above statements as
2. m=5;
y=m++; // Here the value of y would be 5 and m would be 6.
 A prefix operand first adds 1 to the operand value and then 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 value.
Note:
 This operator has four types of representation:
 Pre- Increment operator (++a): Value of Operand is incremented by 1 first then expression is
evaluated.
 Post-Increment Operator (a++): Value of Operand is incremented by 1 after then expression
is evaluated.
 Pre-Decrement Operator (--a): Value of Operand is decremented by 1 first then expression is
evaluated.

19 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
 Post-Decrement Operator (a--): Value of Operand is decremented by 1 after then expression
is evaluated.
Conditional Operator (OR) Ternary Operator
 A ternary operator pairs“? :” is available in C to construct conditional expressions of the form
 Syntax: 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 is evaluated.
Example:
Consider the following statements.
a=10;
b=15;
x = (a>b)? a:b;
In this example, x will be assigned the value of b.
This can also be achieved using if… else statements as follows:
if (a>b)
x=a;
else
x=b;
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.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ Bitwise Negate

20 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019

Example:
The following table lists the Bitwise operators supported by C. Assume variable 'A' holds 60
and variable 'B' holds 13, then:
Operator Description Example
& Operator copies a bit to the result if it exists in both (A&B) = 12
operands i.e., 0000 1100
| Operator copies a bit if it exists in either operand (A | B) = 61
i.e., 0011 1101
^ Operator copies the bit if it is set in one operand but (A ^ B) = 49
not both i.e., 0011 0001
~ Operator is unary and has the effect of 'flipping' bits (~A ) = 61
i.e., 1100 0011
in 2's complement form
<< The left operands value is moved left by the A << 2 = 240
number of bits i.e., 1111 0000
specified by the right operand.
>> The left operands value is moved right by the A >> 2 = 15
number of bits specified by the right operand i.e., 0000 1111

Special Operators
 C supports some special operators of interest such as comma operator, sizeof operator.
 The Comma Operator
 The comma operator can be used to link the related expressions together. A comma-
linked list of expressions are evaluated from left to right and the value of right-most
expression is the value of the combined expression.
Example, the statement: value = (x=10,y=5,x+y)
 First assigns the value 10 to x, then assigns 5 to y , and finally assigns 15
to value. Since comma operator has the lowest precedence of all operators,
the parentheses are necessary.
 The sizeof() Operator
 The sizeof() is a compile time operator and, when used with an operand, it returns the
number of bytes the operand occupies. The operand may be a variable, or a constant or
a data type qualifier.
Examples: m=sizeof(sum);
n= sizeof(5);

21 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
It can also be used in printf statement:
printf(“size of integer data type is %d”, sizeof(int));
Classification Based on number of Operands
The Operators are classified into four major categories based on the number of operands as shown
below:
(i) Unary Operators
(ii) Binary Operators
(iii) Ternary Operators
(iv) Special Operators
 Unary Operators: An operator which acts on only one operand to produce the result is called
unary operator.
Examples: --b, a++, c--
 Binary Operators: An operator which acts on two operands to produce the result is called a
binary operator. In an expression involving a binary operator, the operator is in between two
operands.
Examples: a + b, a*b
 Ternary Operator: An operator which acts on three operands to produce a result is called a
ternary operator. Ternary operator is also called conditional operator.
Example:a ?b : c;
Expressions
 An expression is a sequence of operands and operators that reduces to a single value.
Expressions can be simpler or complex.
 An operator is a syntactical token that requires an action to be taken.
 An operand is an object on which an operation is performed.
 We can divide simple expressions into six categories based on the number of operands,
relative positions of the operand and operator

1. Primary Expressions
2. Unary Expressions
3. Binary Expressions
4. Ternary Expressions
5. Assignment Expressions
6. Comma Expressions

22 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019

1. Primary Expressions
 An expression with only one operand but without any operator is called primary expression.
The various types of primary expressions are:
(i) Names Ex: int a
(ii) Constants Ex: 5, 10.5
(iii) Parenthesized expressions Ex: (2+3*(4-2))
2. Unary Expressions
 An expression with only one operand and one operator is called unary expression. The unary
expression act on a single operand to produce a value. The various types of unary expressions
are:
(i) Unary minus expression Ex: -5
(ii) Unary plus expression Ex: +5
(iii) Prefix expression Ex: ++i
(iv) Postfix expression Ex: i++
3. Binary Expressions
 An expression containing two operands and an operator is called binary expression. A binary
operator acts on two operands to produce a value. The various types of binary expressions are:
(i) Multiplicative expressions Ex: 2*3 , 6/2
(ii) Additive expressions Ex: a-b, a + b etc
(iii) Relational expressions Ex: a>b, a<b etc
(iv) Logical expressions Ex: a && b, a || b
(v) Bitwise expressions Ex: a &b , a | b
4. Ternary Expressions
 An expression containing three operands and two operators is called ternary expression. Here,
the two operators act on three operands.
Example:a ?b:c // a,b and c are operands and ? and:are operators
5. Assignment Expressions
 A statement with assignment operator is called assignment statement. The assignment
statements are often referred to as assignment expressions
Example1: a=10 Example 2:a = b + c
6. Comma Expressions

23 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
 A set of statements separated by commas are evaluated from left to right one after the other.
Such statements are called statements with comma operator.
Example: a=10, b=20, c=30;
Type Conversion
 The process of converting the data from one data type to another data type is called Type
conversion.
 Type conversion is of two types
(i) Implicit type conversion
(ii) Explicit type conversion
1. Implicit Conversion
 C permits mixing of constants and variables of different types in an expression. C
automatically converts any intermediate values to the proper type so that the expression can be
evaluated without losing any significance. The automatic conversion is known as implicit
conversion.
 If the Operands are of different types, the lower data type is automatically converted to higher
type before the operation proceeds.
For example,
 If one operand type is same as other operand type, no conversion takes place and type of
result remains same as the operands i.eint + int = int, float + float = float etc.
 If one operand type is int and other operand type is float, the operand with type int is
promoted to float.
Examples:
int + int = int int + float = float
5+3=8 5 + 3.5 = 8.5

2. Explicit type conversion


 Implicit type conversion is possible only if the data types of two operands are different. In
some situation where the data types of two operands are same, still conversion is required, and
then we have to go for explicit type conversion.
Example,
We want to find the ratio of girls to boys in the college. The ratio is given by
Ratio = no_of_girls / no_of_boys.

24 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
 Here, number of girls and number of boys will be of type integer. So, the compiler will not do
any implicit type conversion because, both operands are of the same data type and hence the
result will be of type integer. But, to get the ratio which is a floating point number, we are
forced to convert one of the operands to float so that the result is also float. This is the place
where we require explicit type conversion.
 Definition: If the Operands are of the same data type, no conversion takes place by the
compiler. Sometimes, the type conversion is required to get the desired results. In such case,
the programmer can instruct the compiler to change the type of the operand from one data type
to another data type. This forcible conversion from one data type to another data type is called
explicit type conversion.
The syntax is: (type) expression
Example:
(int) 9.43: The data conversion from higher data type to lower data type is possible using
explicit type conversion. The following example gives the explicit type conversion.

1 x=(int) 7.5 7.5 is converted to integer by truncation


2 a=(int)21.3 / (int) 4.5 Evaluated as 21/4 and the result would be 5.
3 b=(double) sum/n Division is done in floating point mode
4 y=(int)(a+b) The result a + b is converted to integer
5 z=(int)a +b a is converted to integer and then added to b

Now let us see “What is type casting? Explain with example?”


Definition: C allows programmers to perform typecasting by placing the type name in
parentheses and placing this in front of the value.
For instance
main()
{
float a;
a = (float)5 / 3;
}
Gives result as 1.666666 . This is because the integer 5 is converted to floating point value
before division and the operation between float and integer results in float.

25 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019

Important points to be remembered:


 Precedence[Priority]
It is the rule that specifies the order in which certain operations need to be performed in an
expression. For a given expression containing more than two operators, it determines which
operations should be calculated first.
 Associativity
If all the operators in an expression have equal priority then the direction or order chosen left to
right or right to left to evaluate an expression is called associativity.
BODMAS Rule can be used to solve the expressions,
Where- B: Brackets O: Operators D: Division M: Multiplication A: Addition S: Subtraction
 The Precedence (Hierarchy) of Operator
Operators in Order of
Operator Category Precedence Associativity
(Highest to Lowest)
Innermost brackets/Array (), [], {} Left to Right(L->R)
elements reference
Unary Operators ++, --, sizeof(), ~, +, - Right to Left(R->L)
Member Access -> or * L->R
Arithmetic Operators *, /, % L->R
Arithmetic Operators -, + L->R
Shift Operators <<, >> L->R
Relational Operators <, <=, >, >= L->R
Equality Operators ==, != L->R
Bitwise AND & L->R
Bitwise XOR ^ L->R
Bitwise OR | L->R
Logical AND && L->R
Logical OR || L->R
Conditional Operator ?: R->L

26 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
Assignment Operator =, +=, -=,*=, /=, %= R->L
Comma Operator , L->R

 Evaluation of Expressions involving all the operators


The rules to be followed while evaluating any expressions are shown below.
 Replace the variables if any by their values.
 Evaluate the expressions inside the parentheses
 Rewrite the expressions with increment or decrement operator as shown below:
a) Place the pre-increment or pre-decrement expressions before the expression being
evaluated and replace each of them with corresponding variable.
b) Place the post-increment or post- decrement expressions after the expression being
evaluated and replace each of them with corresponding values.
 Evaluate each of the expression based on precedence and associativity.

Program Statement
 Statement is a syntactic construction that performs an action when a program is executed. All
C program statements are terminated with a semi-colon ( ; )

 Declaration is a program statement that communicates with the compiler about the name and
types of the data needed for program execution.
Example:inta, b;

27 Mr. Sukruth Gowda M A, Assistant Professor


Introduction to C 2019
 Expression statement contains no more that expression i.e.., only the sequence of operands
with operators.
Example: C = A+B*D;

 Compound statements are the sequence of statements that may be treated as a single
statement in the constructions larger statements. Always compound statements will be
enclosed with in { and }.
 Labeled statements can be used to mark any statement so that control may be transferred to
that statement.
 Control statement is a statement whose execution results is a choice being made on condition
or path of execution. It can also be defined as the statement determines the flow of control of
the program.
 Selection statements allow the programmer to select a particular execution path from a set of
one or more alternatives.
 Iteration statements are used to execute a group of one or more statements repeatedly.
 Jump statements cause an unconditional jump to some other place in the program.

28 Mr. Sukruth Gowda M A, Assistant Professor

You might also like