0% found this document useful (0 votes)
18 views91 pages

Unit-2 22ES14A

Uploaded by

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

Unit-2 22ES14A

Uploaded by

DEVANSH SHAH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

Go, change the

RV College world
of
Engineering

Unit -2
Introduction to C

1
RV College of Engineering
Go, change the world

2
RV College of
Engineering Go, change the world

Contents

1. Introduction, structure of a C program, Writing the first


program, Files used in a C program. Compiling and
executing C Programs using comments, C Tokens,
Character set in C, Keywords, Identifiers, Basic Data Types
in C, Variables, Constants, I/O statements in C.

2. Operators in C, Type conversion and type casting, scope of


variables.

3
RV College of
Engineering Go, change the world

Introduction to C
• Created in 1972 to write operating systems (Unix in
particular)
By Dennis Ritchie at Bell Labs
• Evolved from B
• It can be portable to other hardware (with careful
design – use Plauger’s The Standard C Library book)
• Built for performance and memory management
• operating systems
• embedded systems
• real-time systems
• communication systems
4
RV College of Engineering
Go, change the world

• C is a High level, general – purpose structured


programming language.
• Instructions of C consists of terms that similar to
algebraic expressions, consisting of certain English
keywords such as if, else, for, do and while
• C contains certain additional features that allows it to
be used at a lower level, acting as bridge between
machine language and the high level languages.
(Middle Level Language)
• This allows C to be used for system programming as
well as for applications programming

5
RV College of Engineering
Go, change the world

After C
• 1979 C++ by Bjarn Stroustrup
also at Bell
• Object orientation
• 1991 Java by Sun
• Partial compile to java
bytecode: virtual machine
code
• Write once, run anywhere
• Memory manager – garbage
collection
• Many JVMs written in C / C++

6
RV College of Engineering
Go, change the world

Why C
C is a core language :
 In computing, C is a general-purpose, cross-platform, block
structured procedural, imperative computer programming
language.
 There are a number of common and popular computer languages
are based on C.
 Having learnt C, it will be much easier to learn languages that are
largely or in part based upon C.
 Such languages include C++, Java, and Perl.

7
RV College of Engineering
Go, change the world

Features of C
Simple
• C is a simple language in the sense that it provides a structured
approach (to break the problem into parts), the rich set of library
functions, data types, etc.
Machine Independent or Portable
• Unlike assembly language, c programs can be executed on different
machines with some machine specific changes.
Therefore, C is a machine independent language.
Mid-level programming language
• Although, C is intended to do low-level programming.
• It is used to develop system applications such as kernel, driver, etc.
It also supports the features of a high-level language.
• That is why it is known as mid-level language.
8
RV College of Engineering
Go, change the world

Features of C
Structured Programming Language
• C is a structured programming language ie we can break the
program into parts using functions.
• Easy to understand and modify.
• Functions also provide code reusability.

Rich Library - Inbuilt functions that make the development fast.

Memory Management - Dynamic Memory Management

9
RV College of Engineering
Go, change the world

Features of C
Statically Type
• C programming language is a statically typed language.
• Meaning the type of variable is checked at the time of compilation
but not at run time.
• This means each time a programmer type a program they have to
mention the type of variables used.
Easy to Extend
Programs written in C language can be extended means when a
program is already written in it, then some more features and
operations can be added to it.

10
RV College of Engineering
Go, change the world
main()
Structure of a C program {
• A C program contains one or more functions, where Statement 1;
Statement 2;
a function is defined as a group of statements that ............
perform a well-defined task. Statement N;
• The statements in a function are written in a logical }
sequence to perform a specific task. Function1()
• The main() function is the most important function {
Statement 1;
and is a part of every C program. Statement 2;
• A C program can have any number of functions Statement N;
depending on the tasks that have to be performed, }
and each function can have any number of Function2()
{
statements arranged according to specific
Statement 1;
meaningful sequence. Statement 2;
Statement N;
} 11
RV College of Engineering
Go, change the world

Structure of a C program

12
RV College
of Go, change the world
Engineerin
g

First Program
#include <stdio.h>
int main() Output :
{
/* My first program */ Hello World!
printf("Hello World! \n");

return 0;
}

• C is case sensitive.
• End of each statement must be marked with a
semicolon (;).
• Multiple statements can be on the same line.
• White space (e.g. space, tab, enter, …) is ignored. 13
RV College
of Go, change the world
Engineerin
g

First Program
#include <stdio.h>
int main() Output :
{
/* My first program */ Hello World!
printf("Hello World! \n");

return 0;
}

• The C program starting point : main().


• main() {} indicates where the program actually starts and ends.
• In general, braces {} are used throughout C to enclose a block of
statements to be treated as a unit.
• COMMON ERROR: unbalanced number of open and close curly brackets!
14
RV College
of Go, change the world
Engineerin
g

First Program
#include <stdio.h>
int main() Output :
{
/* My first program */ Hello World!
printf("Hello World! \n");

return 0;
}

 #include <stdio.h>
 Including a header file stdio.h
 Allows the use of printf function
 For each function built into the language, an associated header file must be included.

 printf() is actually a function (procedure) in C that is used for printing variables and text
15
RV College
of Go, change the world
Engineerin
g

First Program
#include <stdio.h>
int main() Output :
{
/* My first program */ Hello World!
printf("Hello World! \n");

return 0;
}

• Comments
• /* My first program */
• Comments are inserted between “/*” and “*/”
• Or, you can use “//”
• Primarily they serve as internal documentation for program
structure and function. 16
RV College
of Go, change the world
Engineerin
g

First Program
• first.c. If you are a Windows user, then open the command prompt by
clicking Start->Run and typing “command” and clicking Ok. Using the
command prompt, change to the directory in which you saved your file
and then type:
C:\>tc first.c
• In case you are working on UNIX/Linux operating system, then exit the
text editor and type
$cc first.c –ofirst
• If everything is right, then no error(s) will be reported and the compiler
will create an .exe file for your program. This .exe file can be directly
run by typing
"first.exe" for Windows and "./first" for UNIX/Linux operating system
• When you run the .exe file, the output of the program will be displayed
17
on screen. That is,
RV College
of Go, change the world
Engineerin
g

First Program
Using Comments
Comments are a way of explaining what a program does. C supports two
types of comments.
• // is used to comment a single statement.
• /* is used to comment multiple statements. A /* is ended with */ and all
statements that lie between these characters are commented.
Note that comment statements are not executed by the compiler.
Rather, they are ignored by the compiler as they are simply added in
programs to make the code understandable by programmers as well as
other users.

18
RV College
of Go, change the world
Engineerin
g

First Program
Standard Header Files
Standard header files include:
• string.h : for string handling functions
• stdlib.h : for some miscellaneous functions
• stdio.h : for standardized input and output functions
• math.h : for mathematical functions
• alloc.h : for dynamic memory allocation
• conio.h : for clearing the screen
All the header files are referenced at the start of the source code file that
uses one or more functions from these files.

19
RV College
of Go, change the world
Engineerin
g

Files used in a C program


• Editor - code by programmer
• Compiling using gcc:
• Preprocess – expand the programmer’s code
• Compiler – create machine code for each file
• Linker – links with libraries and all compiled objects to
make executable
• Running the executable:
• Loader – puts the program in memory to run it
• CPU – runs the program instructions

20
RV College
of Go, change the world
Engineerin
g

Compiling and executing C Programs

Typical C development environment 21


RV College
of Go, change the world
Engineerin
g

Typical C development environment


22
RV College
of Go, change the world
Engineerin
g

Compiling and Running C Program


The Three main Steps are
1. Writing the C program
2. Compile the program and
3. Executing it.
• For these steps, there requires some software components, namely
an operating system, a text editor, and the C compiler
• The editor is used to create and modify the program code while the
compiler transforms the source program to object code.
• There are several editors which provide a complete environment for
writing managing, developing, and testing your programs.
• This is sometimes called an integrated development environment, or
IDE. 23
RV College
of Go, change the world
Engineerin
g

Compiling and Running C Program


Writing or Editing the source program using an text editor
or an IDE and saving it with .c extension.
Programming Environment
• Most programming language compilers come with a
specific editor that can provide facilities for managing the
programs.
• Such an editor offers a complete environment for writing,
developing, modifying, deploying, testing, and debugging
the programs.
• Such software is referred to as an integrated development
• environment or IDE.
24
RV College
of Go, change the world
Engineerin
g

Compiling and Running C Program


Preprocessing is the first phase of the C compilation.
• It processes include-files, conditional compilation
instructions
• and macros.
• The C preprocessor is used to modify your program
according to the preprocessor directives in your source
code.
• A preprocessor directive is a statement (such as #define)
that gives the preprocessor specific instructions on how to
modify your source code.
• The preprocessor is invoked as the first part of your
compiler program’s compilation step. 25
RV College
of Go, change the world
Engineerin
g

Compiling and Running C Program


• Compilation is the second pass.
• The compiler examines each program statement contained
in the source program and checks it to ensure that it
conforms to the syntax and semantics of the language.
• If any mistakes are discovered by the compiler during this
phase, they are reported to the user.
• The errors then have to be corrected in the source program
(with the use of an editor), and the program has to be
recompiled

26
RV College
of Go, change the world
Engineerin
g

Compiling and Running C Program


Linking is the final stage of compilation.
After the program has been translated into object code, it is
ready to be linked.
The purpose of the linking phase is to get the program into
a final form for execution on the computer.
The functions are the part of the standard C library, provided
by every C compiler.
The program may use other source programs that were
previously processed by the compiler.
These functions are stored as separate object files which
must be
linked to our object file. Linker handles this linking. 27
RV College
of Go, change the world
Engineerin
g

Compiling and Running C Program


• The process of compiling and linking a program is often called
building.
• The final linked file, which is in an executable object code
format, is stored in another file on the system, ready to be run
or executed.
• Under UNIX, this file is called a.out by default.
• Under Windows, the executable file usually has the same name
as the source file, with the .c extension replaced by an exe
extension.
• When the program is executed, each of the statements of the
program is sequentially executed in turn
• If the program requests any data from the user, known as input,
the program temporarily suspends its execution so that the
input can be entered. 28
RV College
of Go, change the world
Engineerin
g

Compiling and Running C Program


Results that are displayed by the program, known as output,
appear in a window, sometimes called the console.
Or, the output might be directly written to a file on the system.
If all goes well the program performs its intended task.
If the program does not produce the desired results, it is
necessary to go back and reanalyze the program.
There are three types of errors that may occur:
Compile errors : These are given by the compiler and prevent
the program from not running.
Linking errors : These are given by the linker or at runtime and
ends the program.
The linker can also detect and report errors, for example, if part
of the program is missing or a non-existent library component is
referenced. 29
RV College
of Go, change the world
Engineerin
g

Compiling and Running C Program


Runtime errors :These are given by the operating system.
• Removing errors from a program is called debugging.
• Any type of error in your program is known as bug.
• During debugging an attempt is made to remove all the
• known problems or bugs from the program.
• By tracing the program step-by-step, keeping track of each
variable, you monitor the program state.
• The program state is simply the set of values of all the
variables at a given point in program execution.
• It is a snapshot of the current state of computation.
.

30
RV College
of Go, change the world
Engineerin
g

Character Set in C
• Just like we use a set of various words, numbers, statements,
etc., in any language for communication, the C programming
language also consists of a set of various different types of
characters.
• Characters include digits, alphabets, special symbols etc.
• The C language provides support for about 256 characters.
• Characters are used for constructing statements .

31
RV College
of Go, change the world
Engineerin
g

32
RV College
of Go, change the world
Engineerin
g

C Tokens
• The words formed from the character set are building blocks of C
•Cand are sometimes known as tokens.
Tokens
•The
These tokens
words represent
formed thecharacter
from the individual entity
set of language.
are building blocks of C
and are sometimes known as tokens. These tokens represent the
individual entity of language. The following different types of token
are used in C

1) Character set in C
2) Keywords
3) Identifiers
4) Basic Data Types
5) Variables
6) Constants
7) I/O statements
33
RV College
of Go, change the world
Engineerin
g

Keywords
• C has a set of reserved words often known as keywords that
cannot be used as an identifier.
• All keywords are basically a sequence of characters that have a
fixed meaning. By convention, all keywords must be written in
lower case letters.
• There are 32 keywords in C program
Keywords in C language

34
RV College
of Go, change the world
Engineerin
g

Identifiers
• Identifiers are names given to program elements such as variables, arrays and
functions.
• They are formed by using a sequence of letters (both uppercase and lowercase),
numerals, and underscores
• Identifiers cannot include any special characters or punctuation marks (like #, $,
^, ?, ., etc.) except the underscore “_”.
• There cannot be two successive underscores.
• Keywords cannot be used as identifiers.
• The case of alphabetic characters that form the identifier name is significant. For
example, ‘FIRST’ is different from ‘first’ and ‘First’.
• Identifiers must begin with a letter or an underscore. use of underscore as the first
character must be avoided because several complier-defined identifiers in the
standard C library have underscore as their first character. So, inadvertently
duplicated names may cause definition conflicts.
• Identifiers can be of any reasonable length. They should not contain more than 31
characters. (They can actually be longer than 31, but the compiler looks at 35 only
RV College
of Go, change the world
Engineerin
g

Rules to Define Identifiers


•They must begin with a letter or underscore(_).
•They must consist of only letters, digits, or underscore. No other special
character is allowed.
•It should not be a keyword.
•It must not contain white space.
•It should be up to 31 characters long as only the first 31 characters are
significant.

36
RV College
of Go, change the world
Engineerin
g

37
RV College
of Go, change the world
Engineerin
g

BASIC DATA TYPES


Data type determines the set of values that a data item can take
and the operations that can be performed on the item. C language
provides four basic data types. Table 1.2 lists the data types, their
size, range, and usage for a C programmer.
Table Basic data types in C
Data Size in
Range Use
Type Bytes
char 1 –128 to 127 To store characters
int 2 –32768 to 32767 To store integer numbers
3.4E–38 to To store floating point
float 4
3.4E+38 numbers
1.7E–308 to To store big floating
double 8
1.7E+308 point numbers 38
RV College
of Go, change the world
Engineerin
g

BASIC DATA TYPES Table Basic data types and their


• In addition, C also Sizevariants
in
Data Type Range
Bytes
supports four modifiers—
char 1 –128 to 127
two sign specifiers unsigned char 1 0 to 255
(signed and unsigned) signed char 1 –128 to 127
and two size specifiers int 2 –32768 to 32767
(short and long). Table unsigned int 2 0 to 65535
1.3 shows the variants of signed int 2 –32768 to 32767
basic data types. short int 2 –32768 to 32767
• Using modifirs we can unsigned short int 2 0 to 65535

extend or limit the range signed short int 2 –32768 to 32767


long int 4 –2147483648 to 2147483647
of data type
unsigned long int 4 0 to 4294967295
signed long int 4 –2147483648 to 2147483647
float 4 3.4E–38 to 3.4E+38
double 8 1.7E–308 to 1.7E+308
39
long double 10 3.4E–4932 to 1.1E+4932
40
RV College
of Go, change the world
Engineerin
g

Variables
• A variable is nothing but a name given to a storage area that our
programs can manipulate. Each variable in C has a specific type, which
determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of operations
that can be applied to the variable.
• The name of a variable can be composed of letters, digits, and the
underscore character. It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because C is case-sensitive.
There are following basic variable types −
Type Description
Char Typically a single octet (one byte). This is an
integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
Double A double-precision floating point value. 41
RV College
of Go, change the world
Engineerin
g

Variables

Numeric Variables
Numeric variables can be used to store either integer values or
floating point values. Modifiers like short, long, signed, and unsigned
can also be used with numeric variables.

Character Variables
Character variables are just single characters enclosed within single
quotes. These characters could be any character from the ASCII
character set—letters (‘a’, ‘A’), numerals (‘2’), or special characters
(‘&’).

42
RV College
of Go, change the world
Engineerin
g

Variables
Declaring Variables
To declare a variable, specify the data type of the variable followed by its
name. The data type indicates the kind of values that the variable can store.
In C, variable declaration always ends with a semi-colon. For example,
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;

Initializing Variables
While declaring the variables, we can also initialize them with some value. For
example,
int emp_num = 7;
float salary = 9800.99
char grade = ‘A’; 43
RV College
of Go, change the world
Engineerin
g

Constants
• A constant is a value or an identifier whose value cannot be altered in a
program. For example: 1, 2.5,
• As mentioned, an identifier also can be defined as a constant. eg. const double
PI = 3.14
• Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for
this program.
Integer constants
• A integer constant is a numeric constant (associated with number) without any
fractional or exponential part. There are three types of integer constants in C
programming:
• decimal constant (base 10) ex: 10,525, 22000
• octal constant (base 8) Ex: 023,045,07
• hexadecimal constant (base 16) Ex: 0x24. oxA5, 0x72b
Declaring Constants
To declare a constant, precede the normal variable declaration with const
keyword and assign it a value. 44
RV College
of Go, change the world
Engineerin
g

Constants

Floating-point constants
A floating point constant is a numeric constant that has either a
fractional form or an exponent form. For example: 2.0,0.0000234,-
0.22E-5

Character constants
A character constant is a constant which uses single quotation
around characters. For example: 'a', 'l', 'm', 'F'

String constants
String constants are the constants which are enclosed in a pair of
double-quote marks. For example: "good" ,"x", "Earth is round\n"
45
RV College
of Go, change the world
Engineerin
g

Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special
meaning in C programming. For example: newline(enter), tab, question mark etc. In
order to use these characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the
normal way the characters are interpreted by the compiler.escape
Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character 46
RV College
of Go, change the world
Engineerin
g

Operators in C
C language supports different types of operators, which can be
used with variables and constants to form expressions. These
operators can be categorized into the following major groups:
• Arithmetic • Relational operators
operators • Logical operators
• Equality operators • Conditional operator
• Unary operators • Assignment
• Bitwise operators operators
• Comma operator • Size of operator

47
RV College
of Go, change the world
Engineerin
g

Arithmetic Operators
Consider three variables declared as,
int a=9, b=3, result;
Table shows the arithmetic operators, their syntax, and usage in C
language.
Table Arithmetic operators

a and b (on which the operator is applied) are called operands.

48
RV College
of Go, change the world
Engineerin
g

Relational Operators
A relational operator, also known as a comparison operator, is an
operator that compares two values or expressions. Relational
operators return true or false value, depending on whether the
conditional relationship between the two operands holds or not.
Table Relational operators

49
RV College
of Go, change the world
Engineerin
g

Equality Operators
C language also supports two equality operators to compare
operands for strict equality or inequality. They are equal to (==)
and not equal to (!=) operators. The equality operators have lower
precedence than the relational operators.

Table Equality operators

50
RV College
of Go, change the world
Engineerin
g

Logical Operators
C language supports three logical operators. They are logical AND
(&&), logical OR (||), and logical NOT (!). Logical AND and LogicaL
OR combines two relational quantities(Ex A>B && B<C). Logical
operators in C are used to combine multiple conditions/constraints. Logical
Operators returns either 0 or 1,. As in case of arithmetic expressions,
logical expressions are evaluated from left to right.
Truth table of logical AND Truth table of logical OR Truth table of
logical NOT

51
RV College
of Go, change the world
Engineerin
g

Explanation of logical operator program


a= 5, b=5, c=10
(a == b) && (c > 5) evaluates to 1
because both operands (a == b) and (c > b) is 1 (true).
(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b)
are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false).
Hence, !(a != b) is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true).
Hence, !(a == b) is 0 (false).

52
Explanation of logical operator program
a= 5, b=5, c=10
•(a == b) && (c > 5) evaluates to 1
•because both operands (a == b) and (c > b) is 1 (true).
•(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0
(false).
•(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
•(a != b) || (c < b) evaluates to 0 because both operand (a !=
b) and (c < b)
are 0 (false).
•!(a != b) evaluates to 1 because operand (a != b) is 0 (false).
• Hence, !(a != b) is 1 (true).
•!(a == b) evaluates to 0 because (a == b) is 1 (true).
•Hence, !(a == b) is 0 (false).
53
RV College
of Go, change the world
Engineerin
g

Unary Operators
Unary operators act on single operands. C language supports three
unary operators. They are unary minus, increment, and decrement
operators.
Unary Minus (–)
Unary minus operator negates the value of its operand. For
example,
int a, b = 10;
a = –(b);
The result of this expression is a = –10
Increment Operator (++) and Decrement Operator (– –)
The increment operator is a unary operator that increases the value
of its operand by 1. Similarly, the decrement operator decreases
the value of its operand by 1.
The increment/decrement operators have two variants: prefix and
postfix. In a prefix expression (++x or – –x), the operator is applied
54
RV College
of Go, change the world
Engineerin
g
Example
int x = 10, y;
y = x++; is equivalent to writing
y = x; /*y = 10*/ (First Assign the value and then Incriment)
x = x + 1; /*x = 11*/
Whereas y = ++x; is equivalent to writing
x = x + 1; /*x = 11*/ (First Increment and than Assign the
value)
y = x; /*y = 11*/

int x = 10, y;
y = x- -; is equivalent to writing
y = x; /*y = 10*/ (First Assign the value and then Decriment)
x = x - 1; /*x = 9*/
Whereas y = - -x; is equivalent to writing
x = x - 1; /*x = 9*/ (First Decriment and than Assign the value)55
RV College
of Go, change the world
Engineerin
g

Conditional Operator
The syntax of the conditional operator is
exp1 ? exp2 : exp3
exp1 is evaluated first. If it is true, then exp2 is evaluated and
becomes the result of the expression, otherwise exp3 is evaluated
and becomes the result of the expression. For example,
large = (a > b) ? a : b
The conditional operator is used to find the larger of two given
numbers. First exp1, that is a > b, is evaluated. If a is greater than
b, then large = a, else large = b. Hence, large is equal to either a or
b, but not both.

Exercises: Find greatest of 2 and 3 numbers using ternary operator.

56
RV College
of Go, change the world
Engineerin
g

Bitwise Operators
As the name suggests, bitwise operators perform operations at the
bit level. These operators include: bitwise AND, bitwise OR, bitwise
XOR, and shift operators.
Bitwise AND
Like boolean AND (&&), bitwise AND operator (&) performs
operation on bits instead of bytes, chars, integers, etc.
For example, Table Truth table of bitwise XOR
10101010 & 01010101 = 00000000
Bitwise OR
example,
10101010 | 01010101 = 11111111
Bitwise XOR
example,
10101010 ^ 01010101 = 11111111 57
RV College
of Go, change the world
Engineerin
g

Bitwise NOT (~)


The bitwise NOT or complement is a unary operator that performs
logical negation on each bit of the operand.
example,
~10101011 = 01010100
Shift Operators
C supports two bitwise shift operators. They are shift left (<<) and
shift right (>>). The syntax for a shift operation can be given as
operand op num
For example, if we have
x = 0001 1101
then x << 1 produces 0011 1010
example, if we have x = 0001 1101, then
x >> 1 gives result = 0000 1110
58
RV College
of Go, change the world
Engineerin
g

Assignment Operators
In C language, the assignment operator is responsible for assigning
values to the variables. While the equal sign (=) is the fundamental
assignment operator, C also supports other assignment operators
that provide shorthand ways to represent common variable
assignments.
For example,
int x;
x = 10;
assigns the value 10 to variable x. The assignment operator has
right-to-left associativity, so the expression
a = b = c = 10;
is evaluated as
(a = (b = (c = 10)));
59
RV College
of Go, change the world
Engineerin
g

Assignment Operators

Table Assignment operators

60
RV College
of Go, change the world
Engineerin
g

Comma Operator
The comma operator, which is also called the sequential-evaluation
operator, takes two operands. It works by evaluating the first
expression and discarding its value, and then evaluates the second
expression and returns the value as the result of the expression.
For example, the following statement first increments a, then
increments b, and then assigns the value of b to x.
int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x = 6.

61
RV College
of Go, change the world
Engineerin
g

sizeof Operator
sizeof is a unary operator used to calculate the size of data types.
This operator can be applied to all data types. When using this
operator, the keyword sizeof is followed by a type name, variable,
or expression. The operator returns the size of the data type,
variable, or expression in bytes. That is, the sizeof operator is used
to determine the amount of memory space that the data
type/variable/expression will take.
For example, sizeof(char) returns 1, that is the size of a character
data type. If we have,
int a = 10;
unsigned int result;
result = sizeof(a);
then result = 2, that is, space required to store the variable a in
memory. Since a is an integer, it requires 2 bytes of storage space. 62
RV College
of Go, change the world
Engineerin
g

Operator precedence
Chart Table Operators precedence
Table lists the operators chart
that C language supports in
the order of their
precedence (highest to
lowest). The associativity
indicates the order in which
the operators of equal
precedence in an
expression are evaluated.

63
RV College
of Go, change the world
Engineerin
g

Examples (e) a <= 10 && x >= 1 && b


If we have the following = ((a <= 10) && (x >= 1)) &&
variable declarations: b
int a = 0, b = 1, c = –1; = (1 && 1) && 1
float x = 2.5, y = 0.0; =1
then, (f) !x || !c || b + c
(a) a && b = 0 = ((!x) || (!c)) || (b + c)
(b) a < b && c < b = 1 = (0 || 0) || 0
(c) b + c || ! a =0
= ( b + c) || (!a) (g) x * y < a + b || c
= 0 ||1 = ((x * y) < (a + b)) || c
=1 = (0 < 1) || –1
(d) x * 5 && 5 || ( b / c) =1
= ((x * 5) && 5) || (b / c) (h) (x > y) + !a || c++
= (12.5 && 5) || (1/–1) = ((x > y) + (!a)) || (c++)
=1 = (1 + 1) || 0 64
RV College
of Go, change the world
Engineerin
g

Practice Expressions
int a = 1, b = 0, c = 7;
Expression Numeric Value True/False
a
b
c
a+b
a && b
a || b
!c
!!c
a && !b
a < b && b < c
a > b && b < c
a >= b || b > c
65
RV College
of Go, change the world
Engineerin
g

I/O statements in C
• The most fundamental operation in a C program is to accept
input values from a standard input device and output the data
produced by the program to a standard output device.
• Input and Output statement are used to read and write the data
in C programming. These are embedded in stdio.h (standard
Input/Output header file).
• Input means to provide the program with some data to be used
in the program and Output means to display data on screen or
write the data to a printer or a file.C programming language
provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.
• There are mainly two of Input/Output functions are used for this
purpose. These are discussed as:
• Formatted I/O functions
• Unformatted I/O functions 66
RV College
of Go, change the world
Engineerin
g

Formatted I/O functions

• If we want to assign value to variable that is inputted from the


user at run-time? this is done by using the scanf function that
reads data from the keyboard. Similarly, for outputting results of
the program, printf function is used that sends results to a
terminal.
• A program that uses standard input/output functions must
contain the following statement at the beginning of the program:
#include <stdio.h>

67
RV College
of Go, change the world
Engineerin
g

scanf()
The scanf() function is used to read formatted data from the
keyboard. The syntax of the scanf() function can be given as,
scanf ("control string", arg1, arg2, arg3...argn);
The prototype of the control string can be given as,
%[*][width][modifier]type
* is an optional argument that suppresses assignment of the input
field.
width is an optional argument that specifies the maximum number
of characters to be read.
modifier is an optional argument (h, l, or L) , which modifies the
type specifier.
type specifies the type of data that has to be read.
• The scanf function ignores any blank spaces, tabs, and newlines
entered by the user. 68
RV College
of Go, change the world
Engineerin
g

the following code that shows how we can input value in a variable
of int data type:
int num;
scanf(" %4d ", &num);
The scanf function reads first four digits into the address or the
memory location pointed by num.
Table Type specifiers
Type Qualifying Input
%c For single characters
%d, %i For integer values
%e,%E,%f,%g,%G For floating point numbers
%o For octal numbers
%s For a sequence of (string of) characters
%u For unsigned integer values
%x,%X For hexadecimal values 69
RV College
of Go, change the world
Engineerin
g
printf()
The printf function is used to display information required by the user and
also prints the values of the variables. Its syntax can be given as:
printf ("control string", arg1,arg2,arg3,...,argn);
The prototype of the control string can
be given as below:
%[flags][width][.precision][modifier]type
Each control string must begin with a % sign.
flags is an optional argument, which specifies output justification like
decimal point, numerical sign, trailing zeros or octadecimal or hexadecimal
prefixes.
width is an optional argument which specifies the minimum number of
positions that the output characters will occupy.
precision is an optional argument which specifies the number of digits to
print after the decimal point or the number of characters to print from a
string.
modifier field is same as given for scanf() function. 70
RV College
of Go, change the world
Engineerin
g
The most simple printf statement is
printf ("Welcome to the world of C language");
For float x = 8900.768, the following examples show output under
different format specifications:
printf("%f", x); 8 9 0 0 . 7 6 8

printf("%10f", x); 8 9 0 0 . 7 6 8

printf("%9.2f", x); 8 9 0 0 . 7 7

Table Flags in printf()


Flags Description
– Left–justify within the given field width
+ Displays the data with its numeric sign (either + or –)
Used to provide additional specifiers like o, x, X, 0, 0x, or 0X for octal and
#
hexadecimal values respectively for values different than zero
71
0 The number is left–padded with zeroes (0) instead of spaces
RV College
of Go, change the world
Engineerin
g

Unformatted I/O functions


There are mainly six unformatted I/O functions discussed as follows:
• getchar()
• putchar()
• gets()
• puts()
• getch()
• getche()
• getchar()

72
RV College
of Go, change the world
Engineerin
g

getchar()
This function is an Input function. It is used for reading a single
character from the keyboard. It is a buffered function. Buffered functions
get the input from the keyboard and store it in the memory buffer
temporally until you press the Enter key.
The general syntax is as:
v = getchar();
where v is the variable of character type. For example:
A simple C-program to read a single character from the keyboard is as:
/*To read a single character from the keyboard using the getchar()
function
#include <stdio.h>
main()
{
char n;
n = getchar(); 73
RV College
of Go, change the world
Engineerin
g

putchar()
This function is an output function. It is used to display a single
character on the screen. The general syntax is as:
putchar(v);
where v is the variable of character type. For example:
A simple program is written as below, which will read a single character
using getchar() function and display inputted data using putchar()
function:
/*Program illustrate the use of getchar() and putchar() functions*/
#include <stdio.h>
main()
{
char n;
n = getchar();
putchar(n);
} 74
RV College
of Go, change the world
Engineerin
g

gets()
This function is an input function. It is used to read a string from the
keyboard. It is also a buffered function. It will read a string when you
type the string from the keyboard and press the Enter key from the
keyboard. It will mark null character (‘\0’) in the memory at the end of
the string when you press the enter key. The general syntax is as:
gets(v);
where v is the variable of character type. For example:
A simple C program to illustrate the use of gets() function:
/*Program to explain the use of gets() function*/
#include <stdio.h>
main()
{
char n[20];
gets(n);
} 75
RV College
of Go, change the world
Engineerin
g

puts()
This is an output function. It is used to display a string inputted by
gets() function. It is also used to display a text (message) on the screen
for program simplicity. This function appends a newline (“\n”) character
to the output.
The general syntax is as:
puts(v);
or
puts("text line");
where v is the variable of character type.
Cont.

76
RV College
of Go, change the world
Engineerin
g

A simple C program to illustrate the use of puts() function:


/*Program to illustrate the concept of puts() with gets() functions*/
#include <stdio.h>
main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}
The Output is as follows:
Enter the Name
Geek
Name is:
Geek 77
RV College
of Go, change the world
Engineerin
g

getch()
This is also an input function. This is used to read a single character
from the keyboard like getchar() function. But getchar() function is a
buffered is function, getchar() function is a non-buffered function. The
character data read by this function is directly assigned to a variable
rather it goes to the memory buffer, the character data is directly
assigned to a variable without the need to press the Enter key.
Another use of this function is to maintain the output on the screen till
you have not press the Enter Key. The general syntax is as:
v = getch();
where v is the variable of character type.
Cont.

78
RV College
of Go, change the world
Engineerin
g

A simple C program to illustrate the use of getch() function:


/*Program to explain the use of getch() function*/
#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getch();
puts("Char is :");
putchar(n);
getch();
}
The output is as follows:
Enter the Char
Char is L
79
RV College
of Go, change the world
Engineerin
g

getche()
All are same as getch(0 function execpt it is an echoed function. It
means when you type the character data from the keyboard it will
visible on the screen. The general syntax is as:
v = getche();
where v is the variable of character type.
Cont.

80
RV College
of Go, change the world
Engineerin
g

A simple C program to illustrate the use of getch() function:


/*Program to explain the use of getch() function*/
#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");
putchar(n);
getche();
}
The output is as follows:
Enter the Char L
Char is L
81
RV College
of Go, change the world
Engineerin
g

TYPE CONVERSION AND TYPECASTING


Type conversion or typecasting of variables refers to changing a
variable of one data type into another. While type conversion is
done implicitly, casting has to be done explicitly by the
programmer.
Type Conversion
Type conversion is done when the expression has variables of
different data types. So to evaluate the expression, the data type is
promoted from lower to higher level where the hierarchy of data
types can be given as: double, float, long, int, short, and char. For
example, type conversion is automatically done when we assign an
integer value to a floating point variable. Consider the
following code:
float x;
int y = 3;
x = y; 82
RV College
of Go, change the world
Engineerin
g

Typecasting
Typecasting is also known as forced conversion. It is done when the
value of one data type has to be converted into the value of
another data type. The code to perform typecasting can be given
as:
float salary = 10000.00;
int sal;
sal = (int) salary;
When floating point numbers are converted to integers, the digits
after the decimal are truncated. Therefore, data is lost when
floating point representations are converted to integral
representations.
As we can see in the code, typecasting can be done by placing the
destination data type in parentheses followed by the variable name
that has to be converted. Hence, we conclude that typecasting is
done to make a variable of one data type to act like a variable of83
RV College
of Go, change the world
Engineerin
g

Write a program to calculate the area of a circle.


#include <stdio.h>
#include <conio.h>
int main()
{
float radius;
double area;
clrscr();
printf("\n Enter the radius of the circle : ");
scanf("%f", &radius);
area = 3.14 * radius * radius;
printf(" \n Area = %.2lf", area);
return 0;
}
Output
Enter the radius of the circle : 7
Area = 153.86 84
RV College
of Go, change the world
Engineerin
g
Write a program to convert an integer into the corresponding floating
point number.
#include <stdio.h>
#include <conio.h>
int main()
{
float f_num;
int i_num;
clrscr();
printf("\n Enter any integer: ");
scanf("%d", &i_num);
f_num = (float)i_num;
printf("\n The floating point variant of %d is = %f", i_num, f_num);
return 0;
}
Output
Enter any integer: 56 85
The floating point variant of 56 is = 56.000000
RV College
of Go, change the world
Engineerin
g
Scope of Variables
A scope is a region of the program and broadly speaking there are three
places, where variables can be declared:
• Inside a function or a block which is called local variables,
• In the definition of function parameters which is called formal
parameters.
• Outside of all functions which is called global variables.
Here let us explain what local and global variables are.
Local Variables
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or
block of code. Local variables are not known to functions outside their 86
RV College
of Go, change the world
Engineerin
g
Example : local Variable

#include <stdio.h>
int main ()
{
// Local variable declaration:
int a, b;
int c; // actual initialization
a = 10;
b = 20;
c = a + b;
Printf(“%d”,c);
return 0;
}

87
RV College
of Go, change the world
Engineerin
g
Global Variables

Global variables are defined outside of all the functions, usually on top of
the program. The global variables will hold their type throughout the life-
time of your program.
A global variable can be accessed by any function. That is, a global
variable is available for use throughout your entire program after its
declaration. Following is the example using global and local variables:

88
RV College
of Go, change the world
Engineerin
g
Example for global variable

#include <stdio.h>
// Global variable declaration:
int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
printf(”%d”,g);
return 0;
}
89
RV College
of Go, change the world
Engineerin
g
#include <stdio.h>
// Global variable declaration:
int g = 20;

int main ()
{
// Local variable declaration:
int g = 10;
Printf(“%d:,g);
return 0;
}
When the above code is compiled and executed, it produces the following
result:
10

90
RV College
of Go, change the world
Engineerin
g

END of UNIT-II

91

You might also like