SlideShare a Scribd company logo
FIT NOTES
UNIT-7
[C Language : Basics, Constants, Variables and Data Types, Operators and Expressions,
Input & output operations]
Basics
A Computer language includes various languages that are used to communicate with a Computer
machine. All the languages that are now available are categorized into two basic types of languages:
Low-level language and High level language.
• Low Level Language: The main function of the Low level language is to operate, manage
and manipulate the hardware and system components. Low level language is also divided
into two parts are Machine language and Assembly language.
▪ Machine language: Machine language is a collection of binary digits (comprised of
only two characters: 0 and 1) or bits that the computer reads and interprets. Machine
language is the only language a computer is capable of understanding. It is also
known as machine code or object code.
Provided By Shipra Swati
FIT NOTES
While easily understood by computers, machine languages are almost impossible for
humans to use because they consist entirely of numbers. Machine language is the
lowest-level programming language. Every CPU has its own unique machine
language. Programs must be rewritten or recompiled, therefore, to run on different
types of computers.
▪ Assembly language: A much more readable variation of machine language, called
assembly language, uses mnemonic codes to refer to machine code instructions,
rather than using the instructions' numeric values directly. A mnemonic is a symbolic
name for a single executable machine language instruction (an opcode), and there is
at least one opcode mnemonic defined for each machine language instruction. Each
instruction typically consists of an operation or opcode plus zero or more operands.
It has the same structures and set of commands as machine language, but it allows a
programmer to use names instead of numbers. This language is still useful for
programmers when speed is necessary or when they need to carry out an operation
that is not possible in high-level languages. So, it is an intermediate-level
programming language which is higher (is easier to use but runs slower) than
machine language and lower (is more difficult to use but runs faster) than a high-
level language such as Basic, Fortran, C/C++ or Java.
Programs written in assembly language are converted into machine language by
specialized programs called assemblers for their execution by the machine
(computer). An assembler program creates object code by translating combinations
of mnemonics and syntax for operations and addressing modes into their numerical
equivalents. Assembly languages generally lack high-level conveniences such as
variables and functions, and they are not portable between various families of
processors.
For example, on the Zilog Z80 processor, the machine code 00000101 , which
causes the CPU to decrement the B processor register, would be represented in
assembly language as DEC B .
Assembly language is the most basic programming language available for any
processor. Each type of CPU has its own assembly language, so an assembly
language program written for one type of CPU won't run on another.
• High level language: A high-level language is machine-independent, sophisticated
programming language that uses familiar English (or any human language) like syntax. It
makes programming easier by reducing the amount of knowledge of the internal workings
of the computer that was needed to write programs in case of assembly language or machine
language. This results in easier and less error-prone programming.
High-level language has a higher level of abstraction from the computer, and focuses more
on the programming logic rather than the underlying hardware components such as memory
addressing and register utilization. So, it allows programmers to concentrate on application
development without bothering about the machine architecture. Some HLL examples are
Basic, Fortran, C/C++ or Java.
Provided By Shipra Swati
FIT NOTES
A translator is required to the high level language to machine language for execution. The
translator may be an interpreter and Compiler that helps to convert high level codes into
binary code for a Computer to understand.
Compilers translate the entire source code program before execution. Interpreters translate
source code programs one line at a time. Interpreters are more interactive than compilers.
Introduction to C
C is a programming language developed by Dennis Ritchie at AT & T’s Bell Laboratories of USA
in 1972. C is very popular because it is reliable, simple and easy to use.
C language has evolved from three different structured language ALGOL, BCPL and B Language.
It uses many concepts from these languages and introduced many new concepts such as data types,
struct, pointer. In 1988, the language was formalised by American National Standard
Institute(ANSI). In 1990, a version of C language was approved by the International Standard
Organisation(ISO).
Provided By Shipra Swati
FIT NOTES
Features of C language
• It is a robust language with rich set of built-in functions and operators that can be used to
write any complex program.
• The C compiler combines the capabilities of an assembly language with features of a high-
level language.
• Programs Written in C are efficient and fast. This is due to its variety of data type and
powerful operators.
• It is many time faster than BASIC.
• C is highly portable this means that programs once written can be run on another machines
with little or no modification.
• A C program is basically a collection of functions that are supported by C library. We can
also create our own function and add it to C library.
• C language is the most widely used language in operating systems and embedded system
development today.
Applications of C
• C programming language can be used to design the system software like operating system
and Compiler.
• To develop application software like database and spread sheets.
• For Develop Graphical related application like computer and mobile games.
• To evaluate any kind of mathematical equation use c language.
• C programming language can be used to design the compilers.
• UNIX Kernal is completely developed in C Language.
• For Creating Compilers of different Languages which can take input from other language
and convert it into lower level machine dependent language.
• C programming language can be used to design Operating System.
• C programming language can be used to design Network Devices.
Steps of Executing C Program
Step 1 : First Step is Creating and Editing Program.
• Write C Program using Text Editor or IDE.
• Save Program by using [.C] Extension, which is called “Source Program“.
#include <stdio.h>
#include <conio.h>
void main(){
//Variable or constant declaration
clrscr();
printf(“Hello World..”);
getch();
}
Provided By Shipra Swati
FIT NOTES
Step 2 : Second step is Compiling C Program.
• C Source code with [.C] Extension is given as input to compiler and compiler convert it
into Equivalent Machine Instruction.
• In the IDE used in our lab, C/C++ program can be compiled using key [Alt + F9 ] or
only by F9 [Also, menu based option is available for compiling in IDE]
• Compiler Checks for errors. During compilation, if compiler finds any error then it
will report it. User have to re-edit the program and after re-editing program, and
saving [F2], Compiler again check for any error.
• If source code is error-free then Code is converted into Object File [.Obj].
Step 3: Linking Libraries if program is error free.
• Program is linked with included header files, which includes many standard library
functions. Some of the functions are used in the program.
• This process of linking is executed by Linker.
Step 4: Exceution of C program.
• Final step is executing the successfully compiled (i.e. error-free) program to generate the
expected output.
• To run the C program Key [Ctrl+F9] is used [Menu based option is also available to
RUN the program].
• If any run-time errors are reported, then user needs to check for relevent error, re-edit the
program, save the changes, re-compile and run the modified program.
Provided By Shipra Swati
FIT NOTES
Below is the explanation of individual lines of the first C program written above:
C Basic commands Explanation
#include <stdio.h>
This is a preprocessor command that includes standard input output
header file (stdio.h) from the C library before compiling a C program.
Printf() is an example of standard input function.
#include <conio.h>
It includes the console input output library functions. The getch() and
clrscr() function is defined in conio.h file.
void main() This is the main function from where execution of any C program begins.
{ This indicates the beginning of the main function.
//Variable or
constant declaration
whatever is given inside the command “//” in any C program, won’t be
considered for compilation and execution.
clrscr();
It is a predefined function in "conio.h" (console input output header file),
which is used to clear the console screen.
printf(“Hello_World
.. “);
printf command prints the output onto the screen.
getch(); This command waits for any character input from keyboard.
} This indicates the end of the main function.
Parts of a C program
All C programs are having sections/parts which are mentioned below:
• Preprocessor directives: Preprocessing directives are lines in your program that start with #
such as #include, #define etc.
▪ The #include preprocessor directive is used to paste code of given file into current
file before compilation. Ex: #include<stdio.h>
▪ #define is preprocessor statement in C Language, which is used to declare macro. A
macro is a block of code which has been given a name. Any occurance of that name
is replaced by the value of the macro.
Example 1:
#include <stdio.h>
#define AGE 10
void main(){
   clrscr();
   printf("Age = %d n", AGE);
   getch();
}
Provided By Shipra Swati
FIT NOTES
Example 2:
#define AREA(x) ( 3.14 * x * x )
main( ){
    float r1 = 6.25, r2 = 2.5, a ;
    a = AREA ( r1 ) ;
    printf ( "nArea of circle = %f", a ) ;
    a = AREA ( r2 ) ;
    printf ( "nArea of circle = %f", a ) ;
}
• Function: A function is a sequence of statement required to perform a specific task. It can
be system-defined and user-defined. main() is system-defined function, which starts the
execution of C program. printf() and scanf(), clrscr() and getch() are also examples of
system-defined functions.
• Variables declaration: Declare all variables used in the program. [In C programs, required
variables should be declared after opening curly braces { and before clrscr()]
• Statements & Expressions: The statements or other expressions which needs to be
executed are put after clrscr() and before closing curly braces of main }, which is also
logical end of the program.
• Comment: There are two ways of writing comments:
▪ Single line comment: Syntax:
example:
// Hello this is my first C program
// I am from B.Tech 1st
Sem
▪ Multiline comment: Syntax:
example:
/* Hello this is my first C program
I am from B.Tech 1st
Sem */
Data Types
Data types are declarations for memory locations or variables that determine the characteristics of
the data that may be stored and the type of operations that are permitted involving them. C language
support two different types of data types:
Provided By Shipra Swati
FIT NOTES
These are also called primary and secondary datatypes. The primary datatypes can also be of
following types:
Varous characteristics of these data types such as size, range (minimum and maximum value) and
format specifiers are listed below:
*** The size and range depend on the compiler being used. Like for gcc compiler (Compiler for
ubuntu OS), long double data type occupies 12 bytes, whereas for windows compiler, long double
occupies 10 bytes. To check the size of different data types, sizeof operator can be used. To know
different properties of data types, such as their minimum and maximum values, different macros
such as INT_MAX, CHAR_MIN, FLT_MAX, LDBL_MIN etc are defined in two header files:
limits.h (for integers and characters) and float.h. Following is a C program, which uses these
macros to display range of diffent data types:
Provided By Shipra Swati
2.2
3.4 1.1 10
FIT NOTES
C PROGRAM
// C program to check size and minimum and maximum value of different primitive data types
#include<limits.h>
#include<float.h>
#define UCHAR_MIN 0
#define USHRT_MIN 0
#define UINT_MIN 0
#define ULONG_MIN 0
void main(){
char c;
signed char sC;
unsigned char uC;
short signed int sSI;
short unsigned int sUI;
int i;
signed int sI;
unsigned int uI;
long signed int lI;
long unsigned int lUI;
float f;
double d;
long double lD;
printf("n -----------------------------------------------------------------------------n");
printf(" t Data Type ttt Size t MIN_VAL t MAX_VAL tn");
printf(" -------------------------------------------------------------------------------n");
printf(" t char tttt %d t %ld tt %ld tt n", sizeof(c), CHAR_MIN, CHAR_MAX);
printf(" t signed char ttt %d t %ld tt %ld tt n", sizeof(sC), SCHAR_MIN,
SCHAR_MAX);
printf(" t unsigned char ttt %d t %ld tt %ld tt n", sizeof(uC), UCHAR_MIN,
UCHAR_MAX);
printf(" t short signed int tt %d t %ld t %ld tt n", sizeof(sSI), SHRT_MIN, SHRT_MAX);
printf(" t short unsigned signed int t %d t %ld tt %ld tt n", sizeof(sUI), USHRT_MIN,
USHRT_MAX);
printf(" t int tttt %d t %ld t %ld tt n", sizeof(i), INT_MIN, INT_MAX);
printf(" t unsigned int ttt %d t %ld tt %u tt n", sizeof(uI), UINT_MIN, UINT_MAX);
printf(" t long signed int tt %d t %ld t %ld tt n", sizeof(lI), LONG_MIN, LONG_MAX);
printf(" t long unsigned int tt %d t %lu tt %lu tt n", sizeof(lUI), ULONG_MIN,
ULONG_MAX);
printf(" t float tttt %d t %e t %e t n", sizeof(f), FLT_MIN, FLT_MAX);
printf(" t double ttt %d t %e t %e t n", sizeof(d), DBL_MIN, DBL_MAX);
printf(" t long double ttt %d t %Le %Le tt n", sizeof(lD), LDBL_MIN, LDBL_MAX);
printf(" -------------------------------------------------------------------------------nn");
}
Provided By Shipra Swati
FIT NOTES
OUTPUT
Variables
A variable is an entity whose value can change during program execution.Variable names are names
given to locations in memory. These locations can contain integer, real or character values based on
the types of variables.
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. There are some set of rules, which must be followed while naming
any variable. These rules are listed below:
• The 1st letter should be alphabet or Underscore (_).
• Variables can be combination of alphabets and digits.
• Underscore (_) is the only special character allowed.
• Variables can be written in both Uppercase and Lowercase or combination of both.
• Variables are Case Sensitive.
• No Spaces allowed between Characters.
• Variable name should not start with a number.
• Variable name should not make use to the C Reserved Keywords.
Keywords
Keywords are the words whose meaning
has already been explained to the C
compiler. The keywords cannot be used as
variable names. The keywords are also
called ‘Reserved words’. There are only 32
keywords available in C, which is given
here:
Provided By Shipra Swati
FIT NOTES
Constants
A constant is a fix value that doesn't change while program execution. There are basically 2 types of
constants
• Primary constants:- Integer constants, Real constants, Character constaints.
• Secondary constants:- Array, Structure, Union, Pointer, etc.
*** Home Assignment: Rules for Constructing Integer, Real and Character Constant.
On a broader level, primary constants can be of two types: Numeric and Character, which have
further sub-categories as shown below:
• For having certain variables with constant values, we can use a qualifier const at the time of
initialization. For example :
const float pie =3.147;
• In C, constant can also be used using preprocessor directive. For example :
#define pie 3.147
Provided By Shipra Swati
FIT NOTES
Operators and expressions
We can define operators as symbols that helps us to perform specific mathematical and logical
computations on operands. C has a rich set of operators which can be classified as:
1. Arithmetic operator
2. Increments and Decrement Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Conditional Operator
7. Bitwise Operators
1. Arithmetic Operator: An arithmetic operator performs mathematical operations such as
addition, subtraction and multiplication on numerical values (constants and variables).
Note: ‘%’ cannot be used on floating data type.
Example:
// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
    int a = 9,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);
    c=a%b;
    printf("Remainder when a divided by b = %d n",c);
    return 0;
}
Provided By Shipra Swati
FIT NOTES
OUTPUT:
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
2. Increments and Decrement Operators: C programming has two operators increment ++ and
decrement -- to change (increase or decrease) the value of an operand by 1. These operators can be
used as prefix (operator is placed before operand) or postfix (operator is placed after operand). The
general syntax of these operators are:
Increment Operator: m++ (postfix) or ++m (prefix);
Decrement Operator: m-- (postfix) or --m (prefix);
In the example above, m++ simply means m=m+1; and m-- simply means m=m-1;
Increment and decrement operators are mostly used in for and while loops. ++m and m++ performs
the same operation when they form statements independently but they function differently when
they are used in right hand side of an expression. A prefix operator ++m, firstly adds 1 to the
operand and then the result is assigned to the variable on the left whereas a postfix operator m++,
firstly assigns value to the variable on the left and then increases the operand by 1. Same is in the
case of decrement operator.
Provided By Shipra Swati
Independent statement
First Decrease
Then Assign
First Assign
Then Decrease
FIT NOTES
3. Assignment Operator: The Assignment Operator evaluates an expression on the right of the
expression and substitutes it to the value or variable on the left of the expression. ‘=’ is the
assignment operator in C. The value on the right side must be of the same data-type of variable on
the left side otherwise the compiler will raise an error. C also allows the use of shorthand
assignment operators, which take following form:
var op= exp; is the same as the assignment var = var op exp;
Here, var is a variable, op is arithmetic operator, exp is an expression. In this case, ‘op=’ is known
as shorthand assignment operator. The commonly used shorthand assignment operators are as
follows:
Operator Description Example Same As
= assigns values from right side operands to left side operand a=b a=b
+=
adds right operand to the left operand and assign the result to
left
a+=b a=a+b
-=
subtracts right operand from the left operand and assign the
result to left operand
a-=b a=a-b
*=
mutiply left operand with the right operand and assign the result
to left operand
a*=b a=a*b
/=
divides left operand with the right operand and assign the result
to left operand
a/=b a=a/b
%=
calculate modulus using two operands and assign the result to
left operand
a%=b a=a%b
4. Relational Operator/Comparison Operator: A relational operator checks the relationship
between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0
Provided By Shipra Swati
FIT NOTES
5. Logical Operators: Logical operators are used to combine multiple conditions or to complement
the evaluation of the original condition in consideration. it can check multiple condition at a time.
The result of the operation of a logical operator is a boolean value : either true or false. C language
provide three types of logical operators:
Operator Meaning of
Operator
Example
&& Logial AND True only if all operands are true.
If c = 5 and d = 2 then,
expression ((c == 5) && (d > 5)) equals to 0.
|| Logical OR True if even one operand is true.
If c = 5 and d = 2 then,
expression ((c == 5) || (d > 5)) equals to 1.
! Logical NOT The logical not operator takes single expression and evaluates to true
if the expression is false and evaluates to false if the expression is
true. In other words it just reverses the value of the expression.
If c = 5 then, expression !(c == 5) equals to 0.
6. Conditional Operator: A conditional operator is a ternary operator, that is, it works on 3
operands. It uses operator pair “?” and “:”. The general syntax of conditional operator is:
expression1 ? expression2 : expression3 ;
Explanation-
• The question mark "?" in the syntax represents the if part.
• The first expression (expression 1) is use to check true or false condition only.
• If that condition (expression 1) is true then the expression on the left side of " : " i.e
expression 2 is executed.
• If that condition (expression 1) is false then the expression on the right side of " : " i.e
expression 3 is executed.
Example C Program:
#include <stdio.h>
void main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);
// If test condition (February == 'l') is true, days equal to 29.
// If test condition (February =='l') is false, days equal to 28.
days = (February == '1') ? 29 : 28;
printf("Number of days in February = %d",days);
getch();
}
Output:
If this year is leap year, enter 1. If not enter any integer: 1
Number of days in February = 29
Provided By Shipra Swati
FIT NOTES
7. Bitwise Operator: Bit :- Binary Digit ( 0 , 1 ).
Bitwise operators are the special operator which work on bit of the operands. The operators are first
converted to bit-level and then calculation is performed on the operands. The mathematical
operations such as addition , subtraction , multiplication etc. can be performed at bit-level for faster
processing. Bitwise operators are not applied to float or double. C language provide six types of
Bitwise operators :
Operators Meaning of operators Description
& Bit wise AND
The output of bitwise AND is 1 if the corresponding bits of two
operands is 1, otherwise 0. Example: Bit Operation AND of 12 and 25:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
00001100
& 00011001
-------------
00001000 = 8 (In decimal)
| Bit wise OR
The output of bitwise OR is 1 if at least one corresponding bit of two
operands is 1. Example: Bit Operation OR of 12 and 25:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
00001100
| 00011001
-------------
00011101 = 29 (In decimal)
^
Bit wise exclusive
OR
The result of XOR is 1 if corresponding two bits of operands are
different. Example: Bit Operation XOR of 12 and 25:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
00001100
^ 00011001
-------------
00010101 = 21 (In decimal)
~ Bit wise complement
Bitwise compliment operator is an unary operator (works on only one
operand). It changes 1 to 0 and 0 to 1. Example: Bitwise complement
Operation of 35:
35 = 00100011 (In Binary)
~ 00100011
-------------
11011100 = 220 (In decimal)
*** But the computer interprets this number as -36. 2's Complement of
-36 is: (1+ complement of binary equivalent of 36)
1+complement of 00100100 => 1+11011011 =>11011100.
So, Bitwise complement of any number N is -(N+1)
Provided By Shipra Swati
FIT NOTES
Operators Meaning of operators Description
<< Shift left
Left shift operator shifts all bits towards left by certain number of
specified bits. Example
212 = 11010100 (In binary)
212 << 1 = 110101000 (In binary) [Left shift by one bit]
212 << 0 =11010100 (Shift by 0)
212 << 4 = 110101000000 (In binary) =3392(In decimal)
>> Shift right
Right shift operator shifts all bits towards right by certain number of
specified bits. Example:
212 = 11010100 (In binary)
212 >> 2 = 00110101 (In binary) [Right shift by two bits]
212 >> 7 = 00000001 (In binary)
212 >> 8 = 00000000
212 >> 0 = 11010100 (No Shift)
*** Operators that operate or work with two operands are binary operators. Operators that operate
or work with single operand are unary operators.
C Expressions
C expression is a combination of variables, constants and operators written in a proper syntax. Ex:
• Arithmetic expression is an expression which contains arithmetic operators.
• Relational expression is an expression which contains relational operator.
• An expression which combines two or more relational expressions is known as logical
expression
Hierarchy of Operations
The priority or precedence in which the operations given in an expression are performed is called
the hierarchy of operations. The hierarchy of commonly used arithmetic operators is shown below:
Example: Determine the hierarchy of operations and evaluate the following expression:
kk = 3 / 2 * 4 + 3 / 8 + 3
Stepwise evaluation of this expression is shown below:
kk = 3 / 2 * 4 + 3 / 8 + 3 operation: /
kk = 1 * 4 + 3 / 8 + 3 operation: *
kk = 4 + 3 / 8 + 3 operation: / [division in int variables]
kk = 4 + 0 + 3 operation: +
kk = 4 + 3 operation: +
kk = 7 RESULT
Provided By Shipra Swati
FIT NOTES
Following is the operator precedence chart, where precedence of operator decreases from top to
bottom:
Provided By Shipra Swati
FIT NOTES
Associativity of Operators
When an expression contains two operators of equal priority the tie between them is settled using
the associativity of the operators. Associativity can be of two types: Left to Right or Right to Left.
Left to Right associativity means that the left operand must be unambiguous, i.e. it must not be
involved in evaluation of any other sub-expression. Similarly, in case of Right to Left associativity
the right operand must be unambiguous.
Example: Consider the expression a = 3 / 2 * 5 ;
Here there is a tie between operators of same priority, / and *. Both operator has same Left to Right
associativity. Following table shows which operand is unambiguous and which is not for each
operator.
Since both / and * have L to R associativity and only / has unambiguous left operand (necessary
condition for L to R associativity) it is performed earlier.
Example: Consider one more expression a = b = 3 ;
Here both assignment operators have the same priority and same associativity (Right to Left).
Following table shows for each operator, which operand is unambiguous and which is not.
Since both = have R to L associativity and only the second = has unambiguous right operand
(necessary condition for R to L associativity) the second = is performed earlier.
Example: Consider yet another expression z = a * b + c / d ;
Here * and / enjoys same priority and same associativity (Left to Right). Table given below shows
for each operator which operand is unambiguous and which is not.
Provided By Shipra Swati
FIT NOTES
Here since left operands for both operators are unambiguous Compiler is free to perform * or /
operation as per its convenience since no matter which is performed earlier the result would be
same (which was not the case with earlier examples).
Input & output operations
The operations which took place in order to take data and make the display of the processed
information are known as input & output operations. The screen and keyboard together are called a
console. C programming has several in-built library functions to perform input and output tasks.
Console I/O functions can be further classified into two categories: formatted and unformatted
console I/O functions. The functions available under each of these two categories are shown in
following Figure:
The basic difference between them is that the formatted functions allow the input read from
the keyboard or the output displayed on the VDU (visual diplay unit) to be formatted as per our
requirements. For example, if values of average marks and percentage marks are to be displayed on
the screen, then the details like where this output would appear on the screen, how many spaces
would be present between the two values, the number of places after the decimal points, etc. can be
controlled using formatted functions.
Formatted Function
• scanf() and printf() functions: The scanf() function reads formatted input from standard
input (keyboard) whereas the printf() function sends formatted output to the standard output
(screen).
printf ( "format string", list of variables ) ;
The format string can contain:
(a) Characters that are simply printed as they are
(b) Format specifier that begin with a % sign, such as %d, %c, %f
(c) Escape sequences that begin with a  sign, such as t (Tab), n (New line)
Provided By Shipra Swati
FIT NOTES
For example, look at the following program:
main( ){
int avg = 346 ;
float per = 69.2 ;
printf ( "Average = %dnPercentage = %f", avg, per ) ;
}
The output of the program:
Average = 346
Percentage = 69.200000
printf( ) function interprets the contents of the format string from left to right. So long as it
doesn’t come across either a % or a  it continues to dump the characters that it encounters,
on to the screen. In this example Average = is dumped on the screen. The moment it comes
across a format specifier in the format string it picks up the first variable in the list of
variables and prints its value in the specified format. In this example, the moment %d is met
the variable avg is picked up and its value is printed. Similarly, when an escape sequence n
is met it places the cursor at the beginning of the next line. Then Percentage = is printed as
it is and when %f is encountered, second variable from the list of variables, per is picked
and its value is printed. The %d and %f used in the printf( ) tell printf( ) to print the value of
avg as a decimal integer and the value of per as a float.
List of format specifiers for different variables in explained in earlier section.
Format specifiers (&d, %f, %c etc) can contain field-width specifier to tell printf- where this
output would appear on the screen, how many spaces would be present between the two
values, the number of places after the decimal points, etc. Following example illustrates the
idea:
// C program showing different options with format specifiers
#include <stdio.h>
void main()
{
    int integer = 9876;
    float decimal = 987.6543;
    char character = 'A';
    //  Prints the number right justified within 6 columns
        printf("n4   digit   integer   right   justified   to   6   column:   %6dn",
integer);
    // Tries to print number right justified to 3 digits but 
    // the number is not right adjusted because there are only 4 numbers
        printf("4   digit   integer   right   justified   to   3   column:   %3dn",
integer);
Provided By Shipra Swati
FIT NOTES
    
    // Tries to rond integer variable, which makes nosense
    // but compiler shows a warning, no error and
    // simply displays the integer without formatting space 
     printf("4 digit integer rounded to 2 digits (No Effect): %.2dn",
integer);
     
   
    // Tries to print the integer in exponential form, which again makes
no sense
    // Compilation results in warning not error, but some ABRUPT RESULT
is produced
     printf("4 digit integer in exponential form(ABRUPT result): %en",
integer);
    // Rounds to two digit places
    printf("Floating point number rounded to 2 digits: %.2fn",decimal);
    
       // Justifies the number within 10 places with rounding it to 2
digits
       printf("Floating point number right justified to 10 columns and
rounded to 2 digits: %10.2fn",decimal);
    // Rounds to 0 digit places
    printf("Floating point number rounded to 0 digits: %.fn",decimal);
    // Prints the number in exponential notation(scientific notation)
    printf("Floating point number in exponential form: %en",decimal);
    
    // Prints the character right justified in 10 places
        printf("Print   the   character   right   justified   in   10   columns:
%10cn",character);
    
    // Tries to round character upto 2 digits, which makes no sense
    // No compiler error but warning and no formatting is made
        printf("Character   rounded   upto   two   digits(No   Effect):
%.2cn",character);
        
    // Tries to print the character in exponent form
    // No compiler error but warning and ABRUPT result is generated
        printf("Charcter   in   exponential   form(ABRUPT   result):
%enn",character);  
}   
Provided By Shipra Swati
FIT NOTES
OUTPUT
Genearl Syntax of scanf(): scanf ( "format string", list of addresses of variables );
For example: scanf ( "%d %f %c", &c, &a, &ch ) ;
All format specifiers, listed in earlier section is applicable to scanf().
Unformatted Functions
• getchar() & putchar() functions: The getchar() function reads a single character from the
terminal and putchar() function prints the single character passed to it on the screen.
C Program:
#include <stdio.h>
void main( ){
int c;
printf("Enter a character: ");
c=getchar();
printf("nYou entered: ");
putchar(c);
printf("nn");
}
OUTPUT
Enter a character: A
You entered: A
• gets() and puts() functions: The gets() function reads a line from stdin (standard input,
which is keyboard). It is terminated when an Enter key is hit i.e., when this function
encoungters a new line. Thus, spaces and tabs are perfectly acceptable as part of the input
string. The puts() function writes the string and a trailing newline to stdout (standard output,
which is screen).
Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops reading characters
when it encounters a space, but gets() reads space as character too.
Provided By Shipra Swati
FIT NOTES
C Program:
#include<stdio.h>
void main()
{
 char str[100];
 printf("Enter a string: ");
 gets( str );
 puts( str );
}
*** Note:
str[100] is a character array, which will be explained in unit 9. Till that time, just explore
the example as it is.
OUTPUT
Enter a string: Hello, How are U?
Hello, How are U?
Provided By Shipra Swati

More Related Content

What's hot

Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
Neeru Mittal
 
Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.
Md Hossen
 
What is Compiler?
What is Compiler?What is Compiler?
What is Compiler?
Huawei Technologies
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
Akhil Kaushik
 
Introduction to Programming Concepts By Aamir Saleem Ansari
Introduction to Programming Concepts By Aamir Saleem AnsariIntroduction to Programming Concepts By Aamir Saleem Ansari
Introduction to Programming Concepts By Aamir Saleem Ansari
Tech
 
Introduction to compiler
Introduction to compilerIntroduction to compiler
Introduction to compilerAbha Damani
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge
imtiazalijoono
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions
ray143eddie
 
Introduction to compiler development
Introduction to compiler developmentIntroduction to compiler development
Introduction to compiler development
DeepOad
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer ProgrammingProf. Erwin Globio
 
Translators(compiler assembler interpretor).
Translators(compiler assembler interpretor).Translators(compiler assembler interpretor).
Translators(compiler assembler interpretor).
JayminSuhagiya
 
Insight into progam execution ppt
Insight into progam execution pptInsight into progam execution ppt
Insight into progam execution ppt
Keerty Smile
 
Compiler design tutorial
Compiler design tutorialCompiler design tutorial
Compiler design tutorial
Varsha Shukla
 
Chapter 5-programming
Chapter 5-programmingChapter 5-programming
Chapter 5-programmingAten Kecik
 
COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis: COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis:
Jyothishmathi Institute of Technology and Science Karimnagar
 
The Programmer Life Cycle
The Programmer Life CycleThe Programmer Life Cycle
The Programmer Life Cycle
Russell Ovans
 
Interpreted and compiled language
Interpreted and compiled languageInterpreted and compiled language
Interpreted and compiled language
baabtra.com - No. 1 supplier of quality freshers
 

What's hot (20)

Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.
 
df
dfdf
df
 
What is Compiler?
What is Compiler?What is Compiler?
What is Compiler?
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
 
Introduction to Programming Concepts By Aamir Saleem Ansari
Introduction to Programming Concepts By Aamir Saleem AnsariIntroduction to Programming Concepts By Aamir Saleem Ansari
Introduction to Programming Concepts By Aamir Saleem Ansari
 
Introduction to compiler
Introduction to compilerIntroduction to compiler
Introduction to compiler
 
compiler vs interpreter
compiler vs interpretercompiler vs interpreter
compiler vs interpreter
 
Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge Programming Fundamentals and basic knowledge
Programming Fundamentals and basic knowledge
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions
 
Introduction to compiler development
Introduction to compiler developmentIntroduction to compiler development
Introduction to compiler development
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer Programming
 
Translators(compiler assembler interpretor).
Translators(compiler assembler interpretor).Translators(compiler assembler interpretor).
Translators(compiler assembler interpretor).
 
Insight into progam execution ppt
Insight into progam execution pptInsight into progam execution ppt
Insight into progam execution ppt
 
Compiler design tutorial
Compiler design tutorialCompiler design tutorial
Compiler design tutorial
 
Chapter 5-programming
Chapter 5-programmingChapter 5-programming
Chapter 5-programming
 
COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis: COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis:
 
The Programmer Life Cycle
The Programmer Life CycleThe Programmer Life Cycle
The Programmer Life Cycle
 
Interpreted and compiled language
Interpreted and compiled languageInterpreted and compiled language
Interpreted and compiled language
 

Similar to Fundamental of Information Technology - UNIT 7

Programming in C
Programming in CProgramming in C
Programming in C
Rvishnupriya2
 
Introduction to c language
Introduction to c language Introduction to c language
Introduction to c language
BAKRANIYA KALPESH
 
Intoduction to c language
Intoduction to c languageIntoduction to c language
Intoduction to c language
Student
 
C.pdf
C.pdfC.pdf
Introduction to C Programming Language.pptx
Introduction to C Programming Language.pptxIntroduction to C Programming Language.pptx
Introduction to C Programming Language.pptx
AnithaTAssistantProf
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
Noel Malle
 
Chapter 1 Introduction to C .pptx
Chapter 1 Introduction to C .pptxChapter 1 Introduction to C .pptx
Chapter 1 Introduction to C .pptx
Abdalla536859
 
Introduction to Computer
Introduction to ComputerIntroduction to Computer
Introduction to Computer
zaheeriqbal41
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)
nharsh2308
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
Subramanyambharathis
 
Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)
Nuzhat Memon
 
Software programming and development
Software programming and developmentSoftware programming and development
Software programming and development
Ali Raza
 
C-PROGRAMMING-LANGUAGE.pptx
C-PROGRAMMING-LANGUAGE.pptxC-PROGRAMMING-LANGUAGE.pptx
C-PROGRAMMING-LANGUAGE.pptx
DhirendraShahi2
 
Introduction to Computer Programming (general background)
Introduction to Computer Programming (general background)Introduction to Computer Programming (general background)
Introduction to Computer Programming (general background)
Chao-Lung Yang
 
C programming
C programming C programming
C programming
Rohan Gajre
 
C Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYC Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYRajeshkumar Reddy
 
Understanding C and its Applications.pdf
Understanding C and its Applications.pdfUnderstanding C and its Applications.pdf
Understanding C and its Applications.pdf
AdeleHansley
 
C programming introduction
C programming introductionC programming introduction
C programming introduction
Ducat
 

Similar to Fundamental of Information Technology - UNIT 7 (20)

Programming in C
Programming in CProgramming in C
Programming in C
 
Introduction to c language
Introduction to c language Introduction to c language
Introduction to c language
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Intoduction to c language
Intoduction to c languageIntoduction to c language
Intoduction to c language
 
C.pdf
C.pdfC.pdf
C.pdf
 
Introduction to C Programming Language.pptx
Introduction to C Programming Language.pptxIntroduction to C Programming Language.pptx
Introduction to C Programming Language.pptx
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
 
Chapter 1 Introduction to C .pptx
Chapter 1 Introduction to C .pptxChapter 1 Introduction to C .pptx
Chapter 1 Introduction to C .pptx
 
Introduction to Computer
Introduction to ComputerIntroduction to Computer
Introduction to Computer
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
 
Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)Std 10 computer chapter 10 introduction to c language (part1)
Std 10 computer chapter 10 introduction to c language (part1)
 
Software programming and development
Software programming and developmentSoftware programming and development
Software programming and development
 
C-PROGRAMMING-LANGUAGE.pptx
C-PROGRAMMING-LANGUAGE.pptxC-PROGRAMMING-LANGUAGE.pptx
C-PROGRAMMING-LANGUAGE.pptx
 
Introduction to Computer Programming (general background)
Introduction to Computer Programming (general background)Introduction to Computer Programming (general background)
Introduction to Computer Programming (general background)
 
C programming
C programming C programming
C programming
 
C Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYC Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDY
 
Understanding C and its Applications.pdf
Understanding C and its Applications.pdfUnderstanding C and its Applications.pdf
Understanding C and its Applications.pdf
 
C programming introduction
C programming introductionC programming introduction
C programming introduction
 

More from Shipra Swati

Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process Scheduling
Shipra Swati
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of Process
Shipra Swati
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-Introduction
Shipra Swati
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
Java unit 14
Java unit 14Java unit 14
Java unit 14
Shipra Swati
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
Shipra Swati
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
Shipra Swati
 
Java unit 2
Java unit 2Java unit 2
Java unit 2
Shipra Swati
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
Shipra Swati
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
Shipra Swati
 
Ai lab manual
Ai lab manualAi lab manual
Ai lab manual
Shipra Swati
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6
Shipra Swati
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information Technology
Shipra Swati
 
Disk Management
Disk ManagementDisk Management
Disk Management
Shipra Swati
 
File Systems
File SystemsFile Systems
File Systems
Shipra Swati
 
Memory Management
Memory ManagementMemory Management
Memory Management
Shipra Swati
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
Shipra Swati
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
Shipra Swati
 

More from Shipra Swati (20)

Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process Scheduling
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of Process
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-Introduction
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Java unit 14
Java unit 14Java unit 14
Java unit 14
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
 
Java unit 2
Java unit 2Java unit 2
Java unit 2
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
 
Ai lab manual
Ai lab manualAi lab manual
Ai lab manual
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information Technology
 
Disk Management
Disk ManagementDisk Management
Disk Management
 
File Systems
File SystemsFile Systems
File Systems
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
 

Recently uploaded

Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 

Recently uploaded (20)

Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 

Fundamental of Information Technology - UNIT 7

  • 1. FIT NOTES UNIT-7 [C Language : Basics, Constants, Variables and Data Types, Operators and Expressions, Input & output operations] Basics A Computer language includes various languages that are used to communicate with a Computer machine. All the languages that are now available are categorized into two basic types of languages: Low-level language and High level language. • Low Level Language: The main function of the Low level language is to operate, manage and manipulate the hardware and system components. Low level language is also divided into two parts are Machine language and Assembly language. ▪ Machine language: Machine language is a collection of binary digits (comprised of only two characters: 0 and 1) or bits that the computer reads and interprets. Machine language is the only language a computer is capable of understanding. It is also known as machine code or object code. Provided By Shipra Swati
  • 2. FIT NOTES While easily understood by computers, machine languages are almost impossible for humans to use because they consist entirely of numbers. Machine language is the lowest-level programming language. Every CPU has its own unique machine language. Programs must be rewritten or recompiled, therefore, to run on different types of computers. ▪ Assembly language: A much more readable variation of machine language, called assembly language, uses mnemonic codes to refer to machine code instructions, rather than using the instructions' numeric values directly. A mnemonic is a symbolic name for a single executable machine language instruction (an opcode), and there is at least one opcode mnemonic defined for each machine language instruction. Each instruction typically consists of an operation or opcode plus zero or more operands. It has the same structures and set of commands as machine language, but it allows a programmer to use names instead of numbers. This language is still useful for programmers when speed is necessary or when they need to carry out an operation that is not possible in high-level languages. So, it is an intermediate-level programming language which is higher (is easier to use but runs slower) than machine language and lower (is more difficult to use but runs faster) than a high- level language such as Basic, Fortran, C/C++ or Java. Programs written in assembly language are converted into machine language by specialized programs called assemblers for their execution by the machine (computer). An assembler program creates object code by translating combinations of mnemonics and syntax for operations and addressing modes into their numerical equivalents. Assembly languages generally lack high-level conveniences such as variables and functions, and they are not portable between various families of processors. For example, on the Zilog Z80 processor, the machine code 00000101 , which causes the CPU to decrement the B processor register, would be represented in assembly language as DEC B . Assembly language is the most basic programming language available for any processor. Each type of CPU has its own assembly language, so an assembly language program written for one type of CPU won't run on another. • High level language: A high-level language is machine-independent, sophisticated programming language that uses familiar English (or any human language) like syntax. It makes programming easier by reducing the amount of knowledge of the internal workings of the computer that was needed to write programs in case of assembly language or machine language. This results in easier and less error-prone programming. High-level language has a higher level of abstraction from the computer, and focuses more on the programming logic rather than the underlying hardware components such as memory addressing and register utilization. So, it allows programmers to concentrate on application development without bothering about the machine architecture. Some HLL examples are Basic, Fortran, C/C++ or Java. Provided By Shipra Swati
  • 3. FIT NOTES A translator is required to the high level language to machine language for execution. The translator may be an interpreter and Compiler that helps to convert high level codes into binary code for a Computer to understand. Compilers translate the entire source code program before execution. Interpreters translate source code programs one line at a time. Interpreters are more interactive than compilers. Introduction to C C is a programming language developed by Dennis Ritchie at AT & T’s Bell Laboratories of USA in 1972. C is very popular because it is reliable, simple and easy to use. C language has evolved from three different structured language ALGOL, BCPL and B Language. It uses many concepts from these languages and introduced many new concepts such as data types, struct, pointer. In 1988, the language was formalised by American National Standard Institute(ANSI). In 1990, a version of C language was approved by the International Standard Organisation(ISO). Provided By Shipra Swati
  • 4. FIT NOTES Features of C language • It is a robust language with rich set of built-in functions and operators that can be used to write any complex program. • The C compiler combines the capabilities of an assembly language with features of a high- level language. • Programs Written in C are efficient and fast. This is due to its variety of data type and powerful operators. • It is many time faster than BASIC. • C is highly portable this means that programs once written can be run on another machines with little or no modification. • A C program is basically a collection of functions that are supported by C library. We can also create our own function and add it to C library. • C language is the most widely used language in operating systems and embedded system development today. Applications of C • C programming language can be used to design the system software like operating system and Compiler. • To develop application software like database and spread sheets. • For Develop Graphical related application like computer and mobile games. • To evaluate any kind of mathematical equation use c language. • C programming language can be used to design the compilers. • UNIX Kernal is completely developed in C Language. • For Creating Compilers of different Languages which can take input from other language and convert it into lower level machine dependent language. • C programming language can be used to design Operating System. • C programming language can be used to design Network Devices. Steps of Executing C Program Step 1 : First Step is Creating and Editing Program. • Write C Program using Text Editor or IDE. • Save Program by using [.C] Extension, which is called “Source Program“. #include <stdio.h> #include <conio.h> void main(){ //Variable or constant declaration clrscr(); printf(“Hello World..”); getch(); } Provided By Shipra Swati
  • 5. FIT NOTES Step 2 : Second step is Compiling C Program. • C Source code with [.C] Extension is given as input to compiler and compiler convert it into Equivalent Machine Instruction. • In the IDE used in our lab, C/C++ program can be compiled using key [Alt + F9 ] or only by F9 [Also, menu based option is available for compiling in IDE] • Compiler Checks for errors. During compilation, if compiler finds any error then it will report it. User have to re-edit the program and after re-editing program, and saving [F2], Compiler again check for any error. • If source code is error-free then Code is converted into Object File [.Obj]. Step 3: Linking Libraries if program is error free. • Program is linked with included header files, which includes many standard library functions. Some of the functions are used in the program. • This process of linking is executed by Linker. Step 4: Exceution of C program. • Final step is executing the successfully compiled (i.e. error-free) program to generate the expected output. • To run the C program Key [Ctrl+F9] is used [Menu based option is also available to RUN the program]. • If any run-time errors are reported, then user needs to check for relevent error, re-edit the program, save the changes, re-compile and run the modified program. Provided By Shipra Swati
  • 6. FIT NOTES Below is the explanation of individual lines of the first C program written above: C Basic commands Explanation #include <stdio.h> This is a preprocessor command that includes standard input output header file (stdio.h) from the C library before compiling a C program. Printf() is an example of standard input function. #include <conio.h> It includes the console input output library functions. The getch() and clrscr() function is defined in conio.h file. void main() This is the main function from where execution of any C program begins. { This indicates the beginning of the main function. //Variable or constant declaration whatever is given inside the command “//” in any C program, won’t be considered for compilation and execution. clrscr(); It is a predefined function in "conio.h" (console input output header file), which is used to clear the console screen. printf(“Hello_World .. “); printf command prints the output onto the screen. getch(); This command waits for any character input from keyboard. } This indicates the end of the main function. Parts of a C program All C programs are having sections/parts which are mentioned below: • Preprocessor directives: Preprocessing directives are lines in your program that start with # such as #include, #define etc. ▪ The #include preprocessor directive is used to paste code of given file into current file before compilation. Ex: #include<stdio.h> ▪ #define is preprocessor statement in C Language, which is used to declare macro. A macro is a block of code which has been given a name. Any occurance of that name is replaced by the value of the macro. Example 1: #include <stdio.h> #define AGE 10 void main(){    clrscr();    printf("Age = %d n", AGE);    getch(); } Provided By Shipra Swati
  • 7. FIT NOTES Example 2: #define AREA(x) ( 3.14 * x * x ) main( ){     float r1 = 6.25, r2 = 2.5, a ;     a = AREA ( r1 ) ;     printf ( "nArea of circle = %f", a ) ;     a = AREA ( r2 ) ;     printf ( "nArea of circle = %f", a ) ; } • Function: A function is a sequence of statement required to perform a specific task. It can be system-defined and user-defined. main() is system-defined function, which starts the execution of C program. printf() and scanf(), clrscr() and getch() are also examples of system-defined functions. • Variables declaration: Declare all variables used in the program. [In C programs, required variables should be declared after opening curly braces { and before clrscr()] • Statements & Expressions: The statements or other expressions which needs to be executed are put after clrscr() and before closing curly braces of main }, which is also logical end of the program. • Comment: There are two ways of writing comments: ▪ Single line comment: Syntax: example: // Hello this is my first C program // I am from B.Tech 1st Sem ▪ Multiline comment: Syntax: example: /* Hello this is my first C program I am from B.Tech 1st Sem */ Data Types Data types are declarations for memory locations or variables that determine the characteristics of the data that may be stored and the type of operations that are permitted involving them. C language support two different types of data types: Provided By Shipra Swati
  • 8. FIT NOTES These are also called primary and secondary datatypes. The primary datatypes can also be of following types: Varous characteristics of these data types such as size, range (minimum and maximum value) and format specifiers are listed below: *** The size and range depend on the compiler being used. Like for gcc compiler (Compiler for ubuntu OS), long double data type occupies 12 bytes, whereas for windows compiler, long double occupies 10 bytes. To check the size of different data types, sizeof operator can be used. To know different properties of data types, such as their minimum and maximum values, different macros such as INT_MAX, CHAR_MIN, FLT_MAX, LDBL_MIN etc are defined in two header files: limits.h (for integers and characters) and float.h. Following is a C program, which uses these macros to display range of diffent data types: Provided By Shipra Swati 2.2 3.4 1.1 10
  • 9. FIT NOTES C PROGRAM // C program to check size and minimum and maximum value of different primitive data types #include<limits.h> #include<float.h> #define UCHAR_MIN 0 #define USHRT_MIN 0 #define UINT_MIN 0 #define ULONG_MIN 0 void main(){ char c; signed char sC; unsigned char uC; short signed int sSI; short unsigned int sUI; int i; signed int sI; unsigned int uI; long signed int lI; long unsigned int lUI; float f; double d; long double lD; printf("n -----------------------------------------------------------------------------n"); printf(" t Data Type ttt Size t MIN_VAL t MAX_VAL tn"); printf(" -------------------------------------------------------------------------------n"); printf(" t char tttt %d t %ld tt %ld tt n", sizeof(c), CHAR_MIN, CHAR_MAX); printf(" t signed char ttt %d t %ld tt %ld tt n", sizeof(sC), SCHAR_MIN, SCHAR_MAX); printf(" t unsigned char ttt %d t %ld tt %ld tt n", sizeof(uC), UCHAR_MIN, UCHAR_MAX); printf(" t short signed int tt %d t %ld t %ld tt n", sizeof(sSI), SHRT_MIN, SHRT_MAX); printf(" t short unsigned signed int t %d t %ld tt %ld tt n", sizeof(sUI), USHRT_MIN, USHRT_MAX); printf(" t int tttt %d t %ld t %ld tt n", sizeof(i), INT_MIN, INT_MAX); printf(" t unsigned int ttt %d t %ld tt %u tt n", sizeof(uI), UINT_MIN, UINT_MAX); printf(" t long signed int tt %d t %ld t %ld tt n", sizeof(lI), LONG_MIN, LONG_MAX); printf(" t long unsigned int tt %d t %lu tt %lu tt n", sizeof(lUI), ULONG_MIN, ULONG_MAX); printf(" t float tttt %d t %e t %e t n", sizeof(f), FLT_MIN, FLT_MAX); printf(" t double ttt %d t %e t %e t n", sizeof(d), DBL_MIN, DBL_MAX); printf(" t long double ttt %d t %Le %Le tt n", sizeof(lD), LDBL_MIN, LDBL_MAX); printf(" -------------------------------------------------------------------------------nn"); } Provided By Shipra Swati
  • 10. FIT NOTES OUTPUT Variables A variable is an entity whose value can change during program execution.Variable names are names given to locations in memory. These locations can contain integer, real or character values based on the types of variables. 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. There are some set of rules, which must be followed while naming any variable. These rules are listed below: • The 1st letter should be alphabet or Underscore (_). • Variables can be combination of alphabets and digits. • Underscore (_) is the only special character allowed. • Variables can be written in both Uppercase and Lowercase or combination of both. • Variables are Case Sensitive. • No Spaces allowed between Characters. • Variable name should not start with a number. • Variable name should not make use to the C Reserved Keywords. Keywords Keywords are the words whose meaning has already been explained to the C compiler. The keywords cannot be used as variable names. The keywords are also called ‘Reserved words’. There are only 32 keywords available in C, which is given here: Provided By Shipra Swati
  • 11. FIT NOTES Constants A constant is a fix value that doesn't change while program execution. There are basically 2 types of constants • Primary constants:- Integer constants, Real constants, Character constaints. • Secondary constants:- Array, Structure, Union, Pointer, etc. *** Home Assignment: Rules for Constructing Integer, Real and Character Constant. On a broader level, primary constants can be of two types: Numeric and Character, which have further sub-categories as shown below: • For having certain variables with constant values, we can use a qualifier const at the time of initialization. For example : const float pie =3.147; • In C, constant can also be used using preprocessor directive. For example : #define pie 3.147 Provided By Shipra Swati
  • 12. FIT NOTES Operators and expressions We can define operators as symbols that helps us to perform specific mathematical and logical computations on operands. C has a rich set of operators which can be classified as: 1. Arithmetic operator 2. Increments and Decrement Operators 3. Assignment Operators 4. Relational Operators 5. Logical Operators 6. Conditional Operator 7. Bitwise Operators 1. Arithmetic Operator: An arithmetic operator performs mathematical operations such as addition, subtraction and multiplication on numerical values (constants and variables). Note: ‘%’ cannot be used on floating data type. Example: // C Program to demonstrate the working of arithmetic operators #include <stdio.h> int main() {     int a = 9,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);     c=a%b;     printf("Remainder when a divided by b = %d n",c);     return 0; } Provided By Shipra Swati
  • 13. FIT NOTES OUTPUT: a+b = 13 a-b = 5 a*b = 36 a/b = 2 Remainder when a divided by b=1 2. Increments and Decrement Operators: C programming has two operators increment ++ and decrement -- to change (increase or decrease) the value of an operand by 1. These operators can be used as prefix (operator is placed before operand) or postfix (operator is placed after operand). The general syntax of these operators are: Increment Operator: m++ (postfix) or ++m (prefix); Decrement Operator: m-- (postfix) or --m (prefix); In the example above, m++ simply means m=m+1; and m-- simply means m=m-1; Increment and decrement operators are mostly used in for and while loops. ++m and m++ performs the same operation when they form statements independently but they function differently when they are used in right hand side of an expression. A prefix operator ++m, firstly adds 1 to the operand and then the result is assigned to the variable on the left whereas a postfix operator m++, firstly assigns value to the variable on the left and then increases the operand by 1. Same is in the case of decrement operator. Provided By Shipra Swati Independent statement First Decrease Then Assign First Assign Then Decrease
  • 14. FIT NOTES 3. Assignment Operator: The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression. ‘=’ is the assignment operator in C. The value on the right side must be of the same data-type of variable on the left side otherwise the compiler will raise an error. C also allows the use of shorthand assignment operators, which take following form: var op= exp; is the same as the assignment var = var op exp; Here, var is a variable, op is arithmetic operator, exp is an expression. In this case, ‘op=’ is known as shorthand assignment operator. The commonly used shorthand assignment operators are as follows: Operator Description Example Same As = assigns values from right side operands to left side operand a=b a=b += adds right operand to the left operand and assign the result to left a+=b a=a+b -= subtracts right operand from the left operand and assign the result to left operand a-=b a=a-b *= mutiply left operand with the right operand and assign the result to left operand a*=b a=a*b /= divides left operand with the right operand and assign the result to left operand a/=b a=a/b %= calculate modulus using two operands and assign the result to left operand a%=b a=a%b 4. Relational Operator/Comparison Operator: A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0. Relational operators are used in decision making and loops. Operator Meaning of Operator Example == Equal to 5 == 3 returns 0 > Greater than 5 > 3 returns 1 < Less than 5 < 3 returns 0 != Not equal to 5 != 3 returns 1 >= Greater than or equal to 5 >= 3 returns 1 <= Less than or equal to 5 <= 3 return 0 Provided By Shipra Swati
  • 15. FIT NOTES 5. Logical Operators: Logical operators are used to combine multiple conditions or to complement the evaluation of the original condition in consideration. it can check multiple condition at a time. The result of the operation of a logical operator is a boolean value : either true or false. C language provide three types of logical operators: Operator Meaning of Operator Example && Logial AND True only if all operands are true. If c = 5 and d = 2 then, expression ((c == 5) && (d > 5)) equals to 0. || Logical OR True if even one operand is true. If c = 5 and d = 2 then, expression ((c == 5) || (d > 5)) equals to 1. ! Logical NOT The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression. If c = 5 then, expression !(c == 5) equals to 0. 6. Conditional Operator: A conditional operator is a ternary operator, that is, it works on 3 operands. It uses operator pair “?” and “:”. The general syntax of conditional operator is: expression1 ? expression2 : expression3 ; Explanation- • The question mark "?" in the syntax represents the if part. • The first expression (expression 1) is use to check true or false condition only. • If that condition (expression 1) is true then the expression on the left side of " : " i.e expression 2 is executed. • If that condition (expression 1) is false then the expression on the right side of " : " i.e expression 3 is executed. Example C Program: #include <stdio.h> void main(){ char February; int days; printf("If this year is leap year, enter 1. If not enter any integer: "); scanf("%c",&February); // If test condition (February == 'l') is true, days equal to 29. // If test condition (February =='l') is false, days equal to 28. days = (February == '1') ? 29 : 28; printf("Number of days in February = %d",days); getch(); } Output: If this year is leap year, enter 1. If not enter any integer: 1 Number of days in February = 29 Provided By Shipra Swati
  • 16. FIT NOTES 7. Bitwise Operator: Bit :- Binary Digit ( 0 , 1 ). Bitwise operators are the special operator which work on bit of the operands. The operators are first converted to bit-level and then calculation is performed on the operands. The mathematical operations such as addition , subtraction , multiplication etc. can be performed at bit-level for faster processing. Bitwise operators are not applied to float or double. C language provide six types of Bitwise operators : Operators Meaning of operators Description & Bit wise AND The output of bitwise AND is 1 if the corresponding bits of two operands is 1, otherwise 0. Example: Bit Operation AND of 12 and 25: 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) 00001100 & 00011001 ------------- 00001000 = 8 (In decimal) | Bit wise OR The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. Example: Bit Operation OR of 12 and 25: 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) 00001100 | 00011001 ------------- 00011101 = 29 (In decimal) ^ Bit wise exclusive OR The result of XOR is 1 if corresponding two bits of operands are different. Example: Bit Operation XOR of 12 and 25: 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) 00001100 ^ 00011001 ------------- 00010101 = 21 (In decimal) ~ Bit wise complement Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. Example: Bitwise complement Operation of 35: 35 = 00100011 (In Binary) ~ 00100011 ------------- 11011100 = 220 (In decimal) *** But the computer interprets this number as -36. 2's Complement of -36 is: (1+ complement of binary equivalent of 36) 1+complement of 00100100 => 1+11011011 =>11011100. So, Bitwise complement of any number N is -(N+1) Provided By Shipra Swati
  • 17. FIT NOTES Operators Meaning of operators Description << Shift left Left shift operator shifts all bits towards left by certain number of specified bits. Example 212 = 11010100 (In binary) 212 << 1 = 110101000 (In binary) [Left shift by one bit] 212 << 0 =11010100 (Shift by 0) 212 << 4 = 110101000000 (In binary) =3392(In decimal) >> Shift right Right shift operator shifts all bits towards right by certain number of specified bits. Example: 212 = 11010100 (In binary) 212 >> 2 = 00110101 (In binary) [Right shift by two bits] 212 >> 7 = 00000001 (In binary) 212 >> 8 = 00000000 212 >> 0 = 11010100 (No Shift) *** Operators that operate or work with two operands are binary operators. Operators that operate or work with single operand are unary operators. C Expressions C expression is a combination of variables, constants and operators written in a proper syntax. Ex: • Arithmetic expression is an expression which contains arithmetic operators. • Relational expression is an expression which contains relational operator. • An expression which combines two or more relational expressions is known as logical expression Hierarchy of Operations The priority or precedence in which the operations given in an expression are performed is called the hierarchy of operations. The hierarchy of commonly used arithmetic operators is shown below: Example: Determine the hierarchy of operations and evaluate the following expression: kk = 3 / 2 * 4 + 3 / 8 + 3 Stepwise evaluation of this expression is shown below: kk = 3 / 2 * 4 + 3 / 8 + 3 operation: / kk = 1 * 4 + 3 / 8 + 3 operation: * kk = 4 + 3 / 8 + 3 operation: / [division in int variables] kk = 4 + 0 + 3 operation: + kk = 4 + 3 operation: + kk = 7 RESULT Provided By Shipra Swati
  • 18. FIT NOTES Following is the operator precedence chart, where precedence of operator decreases from top to bottom: Provided By Shipra Swati
  • 19. FIT NOTES Associativity of Operators When an expression contains two operators of equal priority the tie between them is settled using the associativity of the operators. Associativity can be of two types: Left to Right or Right to Left. Left to Right associativity means that the left operand must be unambiguous, i.e. it must not be involved in evaluation of any other sub-expression. Similarly, in case of Right to Left associativity the right operand must be unambiguous. Example: Consider the expression a = 3 / 2 * 5 ; Here there is a tie between operators of same priority, / and *. Both operator has same Left to Right associativity. Following table shows which operand is unambiguous and which is not for each operator. Since both / and * have L to R associativity and only / has unambiguous left operand (necessary condition for L to R associativity) it is performed earlier. Example: Consider one more expression a = b = 3 ; Here both assignment operators have the same priority and same associativity (Right to Left). Following table shows for each operator, which operand is unambiguous and which is not. Since both = have R to L associativity and only the second = has unambiguous right operand (necessary condition for R to L associativity) the second = is performed earlier. Example: Consider yet another expression z = a * b + c / d ; Here * and / enjoys same priority and same associativity (Left to Right). Table given below shows for each operator which operand is unambiguous and which is not. Provided By Shipra Swati
  • 20. FIT NOTES Here since left operands for both operators are unambiguous Compiler is free to perform * or / operation as per its convenience since no matter which is performed earlier the result would be same (which was not the case with earlier examples). Input & output operations The operations which took place in order to take data and make the display of the processed information are known as input & output operations. The screen and keyboard together are called a console. C programming has several in-built library functions to perform input and output tasks. Console I/O functions can be further classified into two categories: formatted and unformatted console I/O functions. The functions available under each of these two categories are shown in following Figure: The basic difference between them is that the formatted functions allow the input read from the keyboard or the output displayed on the VDU (visual diplay unit) to be formatted as per our requirements. For example, if values of average marks and percentage marks are to be displayed on the screen, then the details like where this output would appear on the screen, how many spaces would be present between the two values, the number of places after the decimal points, etc. can be controlled using formatted functions. Formatted Function • scanf() and printf() functions: The scanf() function reads formatted input from standard input (keyboard) whereas the printf() function sends formatted output to the standard output (screen). printf ( "format string", list of variables ) ; The format string can contain: (a) Characters that are simply printed as they are (b) Format specifier that begin with a % sign, such as %d, %c, %f (c) Escape sequences that begin with a sign, such as t (Tab), n (New line) Provided By Shipra Swati
  • 21. FIT NOTES For example, look at the following program: main( ){ int avg = 346 ; float per = 69.2 ; printf ( "Average = %dnPercentage = %f", avg, per ) ; } The output of the program: Average = 346 Percentage = 69.200000 printf( ) function interprets the contents of the format string from left to right. So long as it doesn’t come across either a % or a it continues to dump the characters that it encounters, on to the screen. In this example Average = is dumped on the screen. The moment it comes across a format specifier in the format string it picks up the first variable in the list of variables and prints its value in the specified format. In this example, the moment %d is met the variable avg is picked up and its value is printed. Similarly, when an escape sequence n is met it places the cursor at the beginning of the next line. Then Percentage = is printed as it is and when %f is encountered, second variable from the list of variables, per is picked and its value is printed. The %d and %f used in the printf( ) tell printf( ) to print the value of avg as a decimal integer and the value of per as a float. List of format specifiers for different variables in explained in earlier section. Format specifiers (&d, %f, %c etc) can contain field-width specifier to tell printf- where this output would appear on the screen, how many spaces would be present between the two values, the number of places after the decimal points, etc. Following example illustrates the idea: // C program showing different options with format specifiers #include <stdio.h> void main() {     int integer = 9876;     float decimal = 987.6543;     char character = 'A';     //  Prints the number right justified within 6 columns         printf("n4   digit   integer   right   justified   to   6   column:   %6dn", integer);     // Tries to print number right justified to 3 digits but      // the number is not right adjusted because there are only 4 numbers         printf("4   digit   integer   right   justified   to   3   column:   %3dn", integer); Provided By Shipra Swati
  • 22. FIT NOTES          // Tries to rond integer variable, which makes nosense     // but compiler shows a warning, no error and     // simply displays the integer without formatting space       printf("4 digit integer rounded to 2 digits (No Effect): %.2dn", integer);               // Tries to print the integer in exponential form, which again makes no sense     // Compilation results in warning not error, but some ABRUPT RESULT is produced      printf("4 digit integer in exponential form(ABRUPT result): %en", integer);     // Rounds to two digit places     printf("Floating point number rounded to 2 digits: %.2fn",decimal);             // Justifies the number within 10 places with rounding it to 2 digits        printf("Floating point number right justified to 10 columns and rounded to 2 digits: %10.2fn",decimal);     // Rounds to 0 digit places     printf("Floating point number rounded to 0 digits: %.fn",decimal);     // Prints the number in exponential notation(scientific notation)     printf("Floating point number in exponential form: %en",decimal);          // Prints the character right justified in 10 places         printf("Print   the   character   right   justified   in   10   columns: %10cn",character);          // Tries to round character upto 2 digits, which makes no sense     // No compiler error but warning and no formatting is made         printf("Character   rounded   upto   two   digits(No   Effect): %.2cn",character);              // Tries to print the character in exponent form     // No compiler error but warning and ABRUPT result is generated         printf("Charcter   in   exponential   form(ABRUPT   result): %enn",character);   }    Provided By Shipra Swati
  • 23. FIT NOTES OUTPUT Genearl Syntax of scanf(): scanf ( "format string", list of addresses of variables ); For example: scanf ( "%d %f %c", &c, &a, &ch ) ; All format specifiers, listed in earlier section is applicable to scanf(). Unformatted Functions • getchar() & putchar() functions: The getchar() function reads a single character from the terminal and putchar() function prints the single character passed to it on the screen. C Program: #include <stdio.h> void main( ){ int c; printf("Enter a character: "); c=getchar(); printf("nYou entered: "); putchar(c); printf("nn"); } OUTPUT Enter a character: A You entered: A • gets() and puts() functions: The gets() function reads a line from stdin (standard input, which is keyboard). It is terminated when an Enter key is hit i.e., when this function encoungters a new line. Thus, spaces and tabs are perfectly acceptable as part of the input string. The puts() function writes the string and a trailing newline to stdout (standard output, which is screen). Difference between scanf() and gets() The main difference between these two functions is that scanf() stops reading characters when it encounters a space, but gets() reads space as character too. Provided By Shipra Swati
  • 24. FIT NOTES C Program: #include<stdio.h> void main() {  char str[100];  printf("Enter a string: ");  gets( str );  puts( str ); } *** Note: str[100] is a character array, which will be explained in unit 9. Till that time, just explore the example as it is. OUTPUT Enter a string: Hello, How are U? Hello, How are U? Provided By Shipra Swati