0% found this document useful (0 votes)
9 views36 pages

Unit 2

This document provides an introduction to the C programming language, covering basic concepts such as data types, variables, operators, and the life cycle of a C program. It details various operators including arithmetic, relational, and logical operators, as well as the structure and features of C. Additionally, it explains keywords, identifiers, constants, and the use of escape sequences in C programming.

Uploaded by

AK
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)
9 views36 pages

Unit 2

This document provides an introduction to the C programming language, covering basic concepts such as data types, variables, operators, and the life cycle of a C program. It details various operators including arithmetic, relational, and logical operators, as well as the structure and features of C. Additionally, it explains keywords, identifiers, constants, and the use of escape sequences in C programming.

Uploaded by

AK
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/ 36

UNIT-II

INTRODUCTION TO C PROGRAM & OPERATORS

Topics: First C program - Hello world, How to open a command prompt on


Windows or Linux How to read and print on screen - printf(),scanf(),getchar(),
putchar() Variables and Data types - Variables, Identifiers, data types and sizes,
type conversions, difference between declaration and definition of a variable,
Constants.

Life cycle of a C program (Preprocessing, Compilation, Assembly, Linking, Loading,


Execution), Compiling from the command line, Macros.

Operators – equality and assignment, Compound assignment operators, Increment


and decrement operators, Performance comparison between pre and post
increment/decrement operators, bitwise operators (AND, OR, NOT and XOR),
Logical Operators, comma operator, precedence and associativity, Logical
operators (AND, OR, NOT).

C LANGUAGE
C was invented in 1972 at AT & T Bell labs by Dennis Ritchie. Dennis
Ritchie was also involved in writing a new Operating System called Unix
along with other scientists Ken Thompson and Brian Kernighan. C was
extensively used in Unix about 90% of the code in Unix is in C.

Features of C language:
• Structured
• High Level/Middle Level
• Robust
• Portable
• Supports pointers
• Extensible

1
Structured:
C is structured procedure-oriented language, it divides the problem
into smaller modules called functions or procedures.

High Level/Middle Level:


Programs written in C must be translated by the Compiler (system
software) into machine level language.
While in middle level languages programmers can write a code that can be
translated by the assemblers into machine code, which helps the
programmers to interact directly with the hardware.

Portable:
C is portable that is code written on one machine can be easily
ported or executed on other machines as long as that machine supports
the same C compiler.

Robust:
C is robust language that is programs written in C do not crash so
easily. It recovers quickly whenever programs results into an erroneous
condition.

Extensible:
C is extensible language that is it allows new features and
modifications to be made to the existing programs written in C.

Supports pointers:
C supports the use of pointers that allows the programmers to
manipulate the memory directly.

CHARACTER SET
• Character-set refers to the set of alphabets, letters and some special
characters that are valid in C language.
• For example, the characters in C are:
→ Letters A-X, a-z, both upper and lower
→ Digits 0-9
2
→ Symbols such as + - * / % # @ ‘ ] { “ $ etc.
→ White spaces

TOKENS
• A token is a smallest element of a C program.
• One or more characters are grouped in sequence to form
meaningful words. These meaningful words are called tokens.
• The tokens are broadly classified as follows
→ Keywords ex: if, for, while, int, float, char
→ Identifiers ex: sum, length
→ Constants ex: 10, 10.5, 'a', "sri"
→ Operators ex: + - * /
→ Special symbols ex: [], (), {}

KEYWORDS

• Keywords are tokens which are reserved by C for a definite purpose.


• Each keyword has fixed meaning and that cannot be changed by the
user.
• C supports about 32 keywords.

Rules for using keywords


• Keywords cannot be used as a variable or function.
• All keywords should be written in lower letters.

3
• Following keywords are as listed below:

break case char const continue default goto


double else float for if int volatile
register return short signed sizeof struct
switch typedef unsigned void while do
long auto static enum extern union

IDENTIFIER
• Identifier is used to represent various parts of a program such as
variables, constants, functions etc.
• An identifier is a word consisting of sequence of
→ Letters
→ Digits or "_"(underscore)

• For ex:
Average,_Percent, total100

Few Valid Identifiers


Ex. Length, _breadth, area51, Num5_sol, _percent_ etc.

Few Invalid Identifiers


Ex. 10Average, -Sum, Sol?ution, Div/quot etc.

Rules for an Identifier


• Can start with a letter or underscore
• Can’t start with a digit or special symbol or operator
• Can’t contain special symbol or operator
• Can’t be a keyword

CONSTANTS
• A constant is an identifier whose value remains fixed throughout the
execution of the program.
• The constants cannot be modified in the program.
4
• For example:
1, 3.14512 , ‘z’, “pcdnotes"

Different types of constants are:


1) Integer Constant:
• An integer is a whole number without any fraction part.
• There are 3 types of integer constants:
i) Integer & Decimal constants (0 1 2 3 4 5 6 7 8 9)
Integer Constants
For ex: 0, -9, 22
ii) Octal constants (0 1 2 3 4 5 6 7)
For ex: 021, 077, 033
iii) Hexadecimal constants (0 1 2 3 4 5 6 7 8 9 A B C D E F)
For ex: 0x7f, 0x2a, 0x521

2) Floating Point Constant

• The floating point constant is a real number.


• The floating point constants can be represented using 2 forms:

i) Fractional Form
• A floating point number represented using fractional form has an
integer part followed by a dot and a fractional part.
• For ex:
0.5, -0.99
ii) Scientific Notation (Exponent Form)
• The floating point number represented using scientific notation has
three parts namely:
mantissa E exponent

5
• For ex:
9.86E3 imply 9.86*103

3) Character Constant
• A symbol enclosed within a pair of single quotes(') is called a
character constant.
• Each character is associated with a unique value called an ASCII
(American Standard Code for Information Interchange) code.
For ex: '9', 'a', '\n'
4) String Constant
• A sequence of characters enclosed within a pair of double quotes(“) is
called a string constant.
• The string always ends with NULL character (denoted by \0) character.
• For ex:
"9" "a" "sri" "\n"

5) Escape Sequence Characters


• An escape sequence character begins with a backslash and is followed
by one character.
• A backslash (\) along with some characters give rise to special print
effects by changing (escaping) the meaning of some characters.
• The complete set of escape sequences are:
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

6
OPERATOR
• An operator can be any symbol like + - * / that specifies what operation
need to be performed on the data.
• For ex:
+ indicates add operation
* indicates multiplication operation Operand

• An operand can be a constant or a variable.


o Expression
• An expression is combination of operands and operator
that reduces to a single value.
• For ex:
Consider the following expression a+b here a and b
are operands while + is an operator

CLASSIFICATION OF OPERATORS
Operator Name For Example
Arithmetic operators +-*/%
Increment/decrement operators ++ --
Assignment operators =
Relational operators < > ==
Logical operators && || ~
Conditional operator ?:
Bitwise operators &|^
Comma operator ,
Special operators [], sizeof,→

7
ARITHMETIC OPERATORS
• These operators are used to perform arithmetic operations such as
addition, subtraction,

There are 5 arithmetic operators:


Operator Meaning of Operator
+ addition
- subtraction
* multiplication
/ division
% modulus
• Division symbol (/)
→ divides the first operand by second operand and
→ returns the quotient.

Quotient is the result obtained after division operation.


• Modulus symbol (%)
→ divides the first operand by second operand and
→ returns the remainder.
Remainder is the result obtained after modulus operation.
• To perform modulus operation, both operands must be integers.
• Program to demonstrate the working of arithmetic operators.

#include<stdio.h>
int main()
{
int a=11,b=4,c;
c=a+b;
printf("a+b=%d \n", c);
c=a-b;
printf("a-b=%d \n", c);
c=a*b;
printf("a*b=%d \n", c);
c=a/b;
printf("a/b=%d \n", c);
8
c=a%b;
printf("Remainder when a is divided by b=%d ", c);
return 1;
}

Output:
a+b=15
a-b=7
a*b=44
a/b=2
Remainder when a is divided by b= 1

INCREMENT OPERATOR
• ++ is an increment operator.
• As the name indicates, increment means increase, i.e. this operator is
used to increase the value of a variable by 1.
• For example:
If b=5
then b++ or ++b; // b becomes 6
• The increment operator is classified into 2 categories:
1) Post increment Ex: b++
2) Pre increment Ex: ++b

• As the name indicates, post-increment means first uses the value of


variable and then increases the value of variable by 1.
• As the name indicates, pre-increment means first increases the value of
variable by 1 and then uses the updated value of the variable.
• For ex:
If x= 10,
then z= x++; assigns the value 10 to z & then increments value of x
but z = ++x; assigns the value 11 to z

Example: Program to illustrate the use of increment operators.


#include<stdio.h>
int main()
9
{
int x=10,y = 10, z ;
z= x++;
printf(“ z=%d x= %d\n”, z, x);
z = ++y+x;
printf(“ z=%d y= %d”, z, y++);
return 1;
}
Output:
z=10 x=11
z=22 y=11

DECREMENT OPERATOR
• -- is a decrement operator.
• As the name indicates, decrement means decrease, i.e. this operator is
used to decrease the value of a variable by 1.
• For example:
If b=5
then b-- or --b; // b becomes 4

• Similar to increment operator, the decrement operator is classified into


two categories:
i) Post decrement Ex: b--
ii) Pre decrement Ex: --b

• For ex:
If x=10,
then z= x--; // z becomes 10,
but z = --x; // z becomes 9
Example: Program to illustrate the use of decrement operators.
int main()
{
int x=10,y = 10, z ;
z= x--;
printf(“ z=%d x= %d\n”, z, x);
10
z = --y;
printf(“ z=%d y= %d”, z, y);
}
Output:
z=10 x=9
z=9 y=9

ASSIGNMENT OPERATOR
• The most common assignment operator is =.
• This operator assigns the value in right side to the left side.
• The syntax is shown below:
variable=expression;
• For ex:
c=5; //5 is assigned to c
b=c; //value of c is assigned to b
5=c; // Error! 5 is a constant.
• The operators such as +=,*= are called shorthand assignment operators.
• For ex,
a=a+10: can be written as a+=10;

• In the same way, we have:


Operator Example
a-= a-=b a=a-b
a*= b c*=b a=a*b
a/= a/=b a=a/b
a%=b a%=b a=a%b

RELATIONAL OPERATORS
• Relational operators are used to find the relationship between two
operands.
• The output of relational expression is either true(1) or false(0).
• For example
a>b //If a is greater than b, then a>b returns 1 else a>b returns 0.
• The 2 operands may be constants, variables or expressions.

11
There are 6 relational operators:
Operator Meaning of Operator Example
> Greater than 7>4 returns true (1)
< Less than 7<4 returns false (0)
>= Greater than or equal to 7>=4 returns true (1)
<= Less than or equal to 7<=4 return false (0)
== Equal to 7==4 returns false (0)
!= Not equal to 7!=4 returns true(1)

• For ex:
Condition Return values
8> 7 1 (or true)
8>7 0 (or false)
8+7<15 0 (or false)
• Example: Program to illustrate the use of all relational operators.
#include<stdio.h>
int main()
{ printf(“7>4 : %d \n”, 7>4);
printf(“7>=4 : %d \n”, 7>=4);
printf(“7<4 : %d \n”, 7<4);
printf(“7<=4 : %d \n”, 7<=4);
printf(“7==4 : %d \n”, 7==4);
printf(“7!=4 : %d ”, 7!=4);
return 1;

Output:
7>4 : 1
7>=4 : 1
7<4 : 0
7<=4 : 0
7==4 : 0
7!=4 : 1
12
LOGICAL OPERATORS
• These operators are used to perform logical operations like negation,
conjunction and disjunction.
• The output of logical expression is either true(1) or false(0).
• There are 3 logical operators:

Operator Meaning with Examples


&& Logical AND If c=3 and d=1 then ((c==3) && (d>2)) returns false.
|| Logical OR If c=3 and d=1 then ((c==3) || (d>3)) returns true.
! Logical NOT If c=3 then !(c==3) returns false.
• All non zero values(i.e. any value >0 or < 0 ) will be treated as true, while
zero value(i.e. 0 ) will be treated as false.
Truth table
A B A&&B A||B !A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0

• Example: Program to illustrate the use of all logical operators.


#include<stdio.h>
int main()
{
clrscr ( );
printf(“5 && 0 : %d \n”, 5 && 0 );
printf(“5 || 0 : %d \n”, 5 || 0 );
printf(“ !0 : %d”, !0 );
return 1;

13
Output:
5 && 0 : 0
5 || 0 : 1
!0 : 1

• Example: Program to illustrate the use of both relational & Logical


operators.

#include<stdio.h>
int main()
{
printf(“7>5 && 5< 8 : %d \n”, 7>5 && 5<8);
printf(“ 7<5 || 5==5 : % d \n”, 7<5 || 5==5);
printf(“!(3 ==3) : %d ”, !(3==3));
return 1;
}
Output:
7>5 && 5<8 : 1
7<5 || 5==5 : 1
!(3 ==3) : 0

TERNARY OPERATOR (CONDITIONAL OPERATOR)


• The conditional operator is also called a ternary operator it has three
parts.
• Conditional operators are used for decision making in C.
• The syntax is shown below:
(exp1)? exp2: exp3;
where exp1 is an expression evaluated to true or false;

If exp1 is evaluated to true, exp2 is executed;


If exp1 is evaluated to false, exp3 is executed.

14
Example: Program to find biggest of 2 numbers using conditional operator.

#include<stdio.h>
int main()
{
int a,b, big ;
printf(“Enter two different numbers:\n”);
scanf(“%d%d”, &a, &b);
big=(a>b)? a : b;
printf(“ Biggest number is ”, big);
return 1;
}
Output:
Enter two different numbers: 88 79
Biggest number is 88

Example: Program to find biggest of 3 numbers using conditional operator.

#include<stdio.h>
int main()
{
int a,b,c big ;
printf(“Enter two different numbers:\n”);
scanf(“%d%d%d”, &a, &b, &c);
big=(a>b)? ((a>c)?:a:c) : (b>c)?b:c ;
printf(“ Biggest of three number is ”, big);
return 1;
}
Output:
Enter two different numbers: 88 79 99
Biggest number is 99

15
BITWISE OPERATORS
• These operators are used to perform logical operation (and, or, not) on
individual bits of a binary number.
• There are 6 bitwise operators:

Operators Meaning of operators


& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Truth Table
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0

• Ex : Assuming 1- byte short int :


for ~ (bitwise complement) Ex for & (bitwise AND)

a = 12 00001100 b= 15 00001111
~a= 11110011 ~b = 11110000
a & b 0000 1100

• Ex for || (bitwise OR) Ex for ^ (bitwise xor)


a = 12 00001100 b= 15 00001111
a | b = 00001111 a ^ b =00000011

• The operator that is used to shift the data by a specified number of bit
positions towards left or right is called shift operator.
• The syntax is shown below for << The syntax is shown below for >>
b=a << num; b=a >> num; where a is value to be shifted

16
and num is number of bits to be shifted.

• Ex for <<(left shift): Ex for >>(right shift):


a = 13 0000 1101 a = 13 0000 1101
b=a<<1 0001 1010 b=a<<1 0000 0110

Comma Operator:
The comma operator (represented by the token ,) is a binary operator that
evaluates its first operand and discards the result, it then evaluates the second
operand and returns the value (and type). The comma operator has the lowest
precedence of any C operator.
int x , y;
y=(x=10,x=x+20);
printf(“x=%d”,x);
Output:
x=30, y=30;

BASIC CONCEPTS OF A C PROGRAM


• The structure of a C program is shown below:
Documentation Section
Link Section
Preprocessor Section
Global Declaration Section
int main()
{
declaration section;

statement-1 // Executable section starts


statement-2
statement-3
……………………………………………………………
statement-N // Executable section ends
return 1;
}

17
User defined function-definition(s)➔ optional

Documentation Section
• This section allows to document by adding Comments to the
program. Comments are portions of the code ignored by the
compiler. The comments allow the user to make simple notes in the
source-code.
• For ex. // this is an example for single line comment
/* this is an example for multiple line comment */
Link Section
This section contains the header files to be included if any inbuilt functions
have been used by the program. For ex. If sqrt() function has been used to
find the square root then #include<math.h> needs to be included.
Generally, #include<stdio.h> header is always included because most
programs would be using input or output functions such as scanf() and
printf().
Preprocessor Directives
• The preprocessor accepts the source program and prepare the source
program for compilation.
• The preprocessor-statements start with symbol #.
• The normal preprocessor used in all programs is include.
• The #include directive instructs the preprocessor to
include the specified file-contents in the beginning of the
program.
• For ex:
#include<stdio.h>
main()
Global declaration section
• If user wishes to declare any variable outside the main program
which needs to be accessed by any part of the program then he may
declare it in this section just before main function.

18
• Every C program should have a function called as main() and is an entry
point to the program (a gateway to the program) that is always executed.
• The statements enclosed within left and right curly brace is called body
of the function. The main() function is divided into 2 parts:

Declaration Section
• The variables that are used within the function main() should be
declared in the declaration-section only.
• The variables declared inside a function are called local-variables.
The compiler allocates the memory for these variables based on
their types for ex. if the variable is an integer then it allocates 4
Bytes, if it’s of char type then 1-Byte and so on. Ex: int p, t, r;

Executable Section
• This contains the instructions given to the computer to perform a
specific task.
• The task may be to:
→ display a message
→ read data or
→ do some task ex. add two numbers etc.

User Defined Function-definition(s): If user has any user defined functions


then those definitions are written outside the main function.
Example: Program to display a message on the screen.

#include<stdio.h>
int main()
{
printf(“Welcome to C”);
return 1;
}
Output:
Welcome to C

19
Life cycle of a C program
Source Executable
Pre- Object Linking
Program Compile File
process file
(P1.o) (P1.exe)
(P1.c)

Library files

Source Program: Any C file say P1.C program is edited and given to a C
compiler. Figure above shows the different phases of
execution of C program.

Pre-Processing: This is the first phase through which source code is passed. In
this phase any statements defined in this section (before the main()
function) are processed, if used in the program.
This phase includes:
• Removal of Comments
• Expansion of Macros
• Expansion of the included files.
• Conditional compilation

For ex. printf and scanf statements, if used in the program, will have been
checked with their definitions stored in the header file <stdio.h>.

Compile: The next step is to compile and produce an; intermediate file that
contains assembly level instructions P1.s.

During this phase the compiler checks for the syntax errors such as
declaration of variables, initialization if any, the correct syntax of the C
program etc. If any errors are encountered then they get displayed with
corresponding line numbers.
The assembler converts the P1.s file after correction and successful
compilation of the program to an object file P1.o.

20
Linking:
This is the final phase in which all the linking of function calls with their
definitions are done. Linker knows where all these functions are implemented.
Linker does some extra work also, it adds some extra code to our program
which is required when the program starts and ends.

Linking produces the executable file P1.exe (a.out by default on Linux/Unix


machines), which is the machine code (binary code) which will be actually
executed by the processor.

Loader:
Loader takes the image (P1.exe) generated and loads it into RAM and informs
the CPU the starting address of the code for execution (running of the
program).

BASIC DATA TYPES


• The data type defines the type of data stored in a variable and hence in
the memory-location.
Three basic data types in C:
int , float and char

• C supports three classes of data types:


1) Primary data type
for ex: int, float, char and void
2) Derived data types
For ex: array
3) User defined data types
For ex: structure

Primary data types in C:


1) int
• An int is a keyword, used to define integers.
• Using int keyword, the programmer can inform the compiler that the
data associated with this keyword should be treated as integer.
21
• C supports 3 different sizes of integer:
• short int
• int
• long int
2) float
• A float is a keyword which is used to define floating point numbers.
• Compiler allocates 4 bytes of memory.
• C supports 3 different sizes of float:
o float
o double
o long double
• compiler allocates 8 bytes of memory to the data type double, while
16 bytes to long double.

3) char
• A char is a keyword which allows defining and store a single
character.
• Compiler allocates 1 byte of memory.
4) void
• void is an empty data type indicates that no value is associated with this
data type, and it does not occupy any space in the memory.
• Generally used with functions to indicate that the function does not
return any value.

22
Range of data types for 16-bit processor
Data type Bytes Range of data type
char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
float 4 bytes 3.4E-38 to 3.4E38
double 8 bytes 1.7E-308 to1.7E308
long 8 bytes -223372036854775808 to
+9223372036854775807
unsigned long 8 bytes 0 to
18446744073709551615

Qualifiers
• Qualifiers alter the meaning of primary data types to yield a new data
type.

Size Qualifiers
• Size qualifiers alter the size of primary data type.
• The keywords long and short are 2 size qualifiers.
For example:
long int i; //The size of int is 2 bytes but, when long
//keyword is used, variable will be of 4 bytes
short int i; //The size of int is 2 bytes but, when short
//keyword is used, that variable will be of 1
//byte

Sign Qualifiers
• Whether a variable can hold positive value, negative value or both
values is specified by sign qualifiers.
• Keywords signed and unsigned are used for sign qualifiers.
23
unsigned int a; //unsigned variable can hold zero &
// positive values only
signed int b; //signed variable can hold zero , positive
//and negative values

Constant Qualifiers
• Constant qualifiers can be declared with keyword const.
• An identifier declared by using a const keyword cannot be modified.

const int p=20; //the value of p cannot be changed in the


//program.

VARIABLE
• A variable is an identifier whose value can be changed during execution
of the program. Variable is a name given to a memory-location where the
data(value) can be stored.

• Using the variable-name, the data can be


→ stored in a memory-location and
→ accessed or manipulated

Rules for defining a variable


1) The first character in the variable should be a letter or an underscore.
2) The first character can be followed by letters or digits or underscore.
3) No special symbols or white spaces are allowed (other than letters,
digits and underscore).
4) Length of a variable can be up to a maximum of 31 characters.
5) Keywords should not be used as variable-names.

• Valid variables:
area, rate_of_interest, _temperature_, celcius25
Invalid variables:
3fact, ?sum, sum-of-digits, length62$, for,
int, if
24
Declaration of Variable
• The declaration tells the complier
• what is the name of the variable used
• what type of data is held by the variable
• The syntax is shown below:
data_type variable1, variable2, variable3;
where variable1, variable2, variable3 are variable-names
of data_type that could be int, float or char type.

• For ex:
int a, b, c;
float x, y, z;

Initialization of Variable

• The variables are not initialized when they are declared. Hence, variables
normally contain garbage values and hence they have to be initialized with
valid data.

• Syntax is shown below:


• For ex:
int xyz = 10;

data_type variable_name

assignment operator data (value)

float pi=3.1416;
char c='z';

DATA INPUT/OUTPUT FUNCTIONS


• There are many library functions for input and output operations in C
language.
25
• For ex:
getch( ), putch(), scanf( ), printf( )
• For using these functions in a C-program there should be preprocessor
statement #include<stdio.h> in the beginning of the program before the
declaration of main function.

Input Function
• The input functions are used to read the data from the keyboard and
store in memory-location.
• For ex:
scanf(), getchar(), getch(), getche(), gets()

Output Functions
• The output functions are used to receive the data from memory-
locations through the variables and display on the monitor.
• For ex:
printf(), putchar(), putch(), puts()

Types of I/O Functions:


• There are 2 types of I/O Functions as shown below:

26
UNFORMATTED I/O
getchar() and putchar()

• getchar() is used to
➢ reads a character from the keyboard and stores the character into a
memory-location or buffer.
• After typing a character ENTER key needs to be pressed.
• The syntax is shown below:
char variable_name = getchar( );
• For ex:
char z;
z= getchar( );
• putchar() is used to display a character stored in the memory-location on
the screen.

#include<stdio.h>
int main()
{
char x;
printf(“Type a character followed by ENTER key: \n”);
x = getchar();
putchar(x); // same as printf(“%c”, x);
return 1;
}

Output:
Type a character followed by ENTER key: N
N

• getch(), getche() and putch()


• getch() is used to read a character from the keyboard without echo (i.e.
typed character will not be visible on the screen) and without waiting for
the enter key to be pressed. The character thus entered will not be stored
in the memory location or buffer.
27
• getche() is used to read a character from the keyboard by echoing (i.e.
typed character will be visible on the screen) and without waiting for
the enter key to be pressed. The character thus entered will not be
stored in the memory location or buffer.

• putch() is used to display a character stored in memory-location on the


screen.

#include<stdio.h>
int main()
{
char x;
printf(“Type a alphabet: \n ”);
x = getch();
putch(x);
return 1;
}
Output:
Type a alphabet: K //K is not visible
K prints K to the output screen

• getche() is same as getchar() function


• gets() and puts()
gets() is used to
o read a string from the keyboard and
o stores the string in memory-location

puts() is used to display a string stored in memory-locations on the screen.


#include<stdio.h>
int main()
{
char str[20];
printf("Enter a string: \n");
gets(str);
28
puts(str); // same as printf("%s", str);
return 1;
}
Output:
Enter a string: GEHU
GEHU

Disadvantage of Unformatted I/O


• It is not possible to read/print any other data except characters i.e. it is
not possible to read/print integer numbers, floating point numbers etc.

FORMATTED I/O
scanf()
• Input function to read data from the keyboard
• The scanf function does the following tasks:
→ Scans a series of input fields one character at a time
→ Formats each field according to a corresponding format-specifier
passed in format-string (format means convert).
→ Stores the formatted input at an address passed as an argument i.e.
address-list
• Syntax is shown below:
scanf("formatted-string", address-list);
where formatted-string contains one or more format-specifiers address-
list is a list of variables. Each variable name must be preceded by &
• For ex:
int x;
float y;
char z;
scanf("%d %f %c", &x, &y, &z);

Format specifiers Meaning


%d an int argument in decimal
%ld a long int argument in decimal
%c a character
%s a string
29
%f a float or double argument
%e same as %f, but use exponential notation
%o an int argument in octal (base 8)
%x an int argument in hexadecimal (base 16)

printf
The printf function does the following tasks:
→ Accept a series of arguments
→ Applies to each argument a format-specifier contained in the format-
string
→ Prints the formatted data to the screen
• The syntax is shown below:
printf("format-string", variable-list);
where format-string contains one or more format-specifiers
variable-list contains names of variables
• For ex:
printf("%d %f %c", x, y, z );

• Example: Program to read age of a person and display the same to the
screen.

#include<stdio.h>
int main()
{
int age;
printf(“Enter your age:”);
scanf(“%d”, &age);
printf(“Your age is %d years ”, age);
return 1;
}

Output:
Enter your age:21
Your age is 21 years
30
VARIATIONS IN OUTPUT FUNCTION FOR INTEGER AND FLOATS

• Integer and floating-points can be displayed in different formats in C as


shown below:

#include<stdio.h>
int main()
{
printf("%6d \n",9876);
// Prints the number right justified within 6 columns
printf("%3d \n",9876);
// Prints the number to be right justified to 3 columns but, there are 4
//digits so number is not right justified
printf("%.2f \n",987.6543);
// Prints the number rounded to two decimal places
printf("%.f \n",987.6543);
// Prints the number with six decimal places
printf("%e ",987.6543);
// Prints the number in exponential notation(scientific //notation)
return 1;
}

Output:
9876
9876
987.65
988
9.876543e+002

31
TYPE CONVERSION
• Type conversion is used to convert data of one type to data of another
type.
• Type conversion is of 2 types as shown in below figure:

Conversion Hierarchy:
Any implicit type conversions are made by converting the lower type to
higher type as shown below:

IMPLICIT CONVERSION
• If a compiler converts one type of data into another type of data
automatically, it is known as implicit conversions.
• There may be data loss whenever in implicit conversion takes place i.e
while converting from float to int the fractional part will be truncated,
double to float causes rounding of digit and long to int causes dropping of
excess higher order bits.
• The conversion always takes place from lower rank to higher rank.

For ex, int to float as shown in the above datatype hierarchy.


• For ex:
int a = 22;
float b=11;
32
float c = a/b; =0.500000

• If one operand type is same as other operand type, no conversion takes


place and type of result remains same as the operands i.e.
int= int + int
float=float + int
long int = int + long int
• Conversion rules are as follows:
→ If either operand is long double, converts the other to long double.
→ Otherwise, if either operand is double, converts the other to double.
→ Otherwise, if either operand is float, converts the other to float.
→ Otherwise, converts char and short to int.
→ Then, if either operand is long, converts the other to long.
• Example: Program to illustrate implicit conversion.
#include<stdio.h>
int main()
{ float a = 22;
int b=11;
float d ;
d=b/a;
printf("d Value is : %f ", d );
return 1;
}
Output:
d
Value is : 0.500000

EXPLICIT CONVERSION
• When the data of one type is converted explicitly to another type with
the help of some pre-defined types, it is called as explicit conversion.
• The syntax is shown below:
data_type1 v1;

data_type2 v2= (data_type2) v1;


where v1 can be expression or operand or value
33
• For ex:
int b=11;
int c = 22;
float d= (float)b/c=11/22=0.500000

• Example: Program to illustrate explicit conversion.

#include<stdio.h>
int main()
{
int b=11;
int c = 22;
float d;
d=(float)b/c;
printf("d Value is : %f ", d );
return 0;
}
Output:
d Value is : 0.500000

THE PRECEDENCE OF OPERATORS


• The order in which different operators are used to evaluate in an
expression is called precedence of operators.

PRECEDENCE TABLE
Rank Operator Associativity Rank Operator Associativity
1 () Left to Right 9 ^ (Bitwise Left to right
[] XOR)

.

++ --
2 - Unary minus Right to left 10 | (Bitwise OR) Left to Right
++ (prefix
increment)
- - (prefix
34
decrement)
~ (one’s
complement)
* (indirection
Or
dereference)
& (Address of)
! (Logical Not)
(type) type cast
sizeof
3 * / % (Modulus ) Left to Right 11 && Left to Right
4 + - (Binary Left to Right 12 || Left to Right
Addition or
Subtraction)
5 << >> Left to Right 13 ?: (Ternary Right to left
operator)
6 < >= Left to Right 14 = Right to left
` < <= +=
-=
*=
/=
>>= etc.
7 == != Left to Right 15 , Left to Right
8 & (Bitwise AND) Left to Right

Example to understand the operator precedence available in C


programming language.
#include<stdio.h>
int main()
{ int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; /* (30 * 15 ) / 5 */
printf("Value of (a + b) * c / d is : %d \n", e );
e = ((a + b) * c) / d; /* (30 * 15 ) / 5 */
printf("Value of ((a + b) * c) / d is : %d \n" , e );
e = (a + b) * (c / d); /* (30) * (15/5) */
printf("Value of (a + b) * (c / d) is : %d \n", e );
35
e = a + (b * c) / d; /* 20 + (150/5) */
printf("Value of a + (b * c) / d is : %d " , e );
return 1;
}

Output:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

Q. Write a C expression to the following expressions (Assume all quantities


of same type)
5𝑥+3𝑦
i. A = ii) 𝐵 = √𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐) iii) C=𝑒 |𝑥+𝑦−10|
𝑎+𝑏
𝑒 √𝑥 + 𝑒 √𝑦 −𝑏+√𝑏2 −4𝑎𝑐
iv) x25+y35 v) X= vi) 𝑥 =
𝑥𝑠𝑖𝑛√𝑦 2𝑎

=========================End of UNIT-II ======================

36

You might also like