Complete First Unit in Pps -28th Nove 2021
Complete First Unit in Pps -28th Nove 2021
SOLVING
prepared by
Dr.G.Umarani Srikanth, M.E, Phd
Professor / Dept of CSE
Bharath Institute of Higher Education and Research
Chennai
U20CSEJ01 Programming for Problem Solving L T P C
Total Contact Hours - 105 3 0 4 5
Prerequisite – Mathematics knowledge, Analytical and Logical skills.
Course Offered by – Dept. of Computer Science & Engineering
OBJECTIVES
The Course should enable the students to
Contemplate and construct algorithm, flowchart and pseudocode to do programs.
Employ operators and expressions to solve engineering problems.
Handle data in single and multi-dimensional arrays.
Develop routines that are user defined and can be used in various applications.
Build storage constructs using structure and unions.
Build and deploy files to store and retrieve information.
Construct the programming steps and procedures to solve various Engineering
applications.
UNIT I -INTRODUCTION
Passing array element to function – formal and actual parameters – advantages of using functions
– processor directives and #define directives – nested preprocessor macro – advantages of using
functions – pointers and address operator – size of pointer variable and pointer operator – pointer
declaration and dereferencing pointer – void pointer and size of void pointers – arithmetic
operations – incrementing pointers– constant pointers – pointers to array elements and strings –
function pointers – array of function pointers – accessing array of function pointers – null
pointers.
PROGRAMMING LANGUAGE
Definition
It is a language specifically designed to express computations that can be performed by the
computer.
that are used to create programs that control the behavior of a system, to express algorithms or
as a mode of human –computer communication.
-the term of programming language refers to BASIC, C , C++, JAVA.
High level languages are easy to understand, machine language consists of binary number only.
The question of which language is the best depends on following factors.
the type of computer on which programs has to be executed
Type of program
Expertise of programmer.
For example, FORTRAN is a good language for processing numerical data, it does not lend itself to
organize large programs.
-PASCAL can be used to write well-structured and readable programs but Pascal was a larger more
cumbersome language. Running Pascal required purchasing an extra memory card (it needed 64k of
RAM!) . Pascal was taught in computer science curricula, while C was mostly self-taught.
-C++ goes one step ahead of C by incorporating object oriented features , but complex and difficult to
learn.
The combination of efficient execution on limited hardware, and, native access to the underlying OS
and GUI libraries were probably the main reasons for C's success. Not only UNIX. Windows and its
kernels were written mainly in C
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
GENERATION OF PROGRAMMING LANGUAGES
We know that programming languages are the primary tools for creating software.
As of now, hundreds of programming languages exist in the market, some more used than
others, each claiming to be the best.
Back in the 1940s when computer were being developed there were one language - called
machine language exists.
The concept of generations of programming languages is closely connected to the advances in
technology that brought about computer generations.
The Five Generation of Programming Language are
1. Machine language or First Generation language- 1G
2. Assembly language or Second Generation language -2G
3. High level language or Third Generation language -3G
4. Very high level language, known as Fourth Generation language or -4G
5. Fifth Generation language or -5G
(i)Machine language of first generation language
It was used to program the first stored program on computer systems.
This is the lowest level of programming language.
The machine language is the only language that the computer can understand.
All the commands and data values are expressed using 0s and 1s.
-all instructions, memory locations, numbers and characters are represented in strings of 1s and
0s.
These programs are not easy for humans to read, write and debug.
advantage
machine language is that the code can run very fast and efficiently since it is directly executed
by CPU.
Disadvantages
Difficult to learn
Difficult to edit if errors occur
If you want to add some instructions into memory at some location, then all instructions after
insertion point would have to be moved down to make room in memory to accommodate new
instructions.
Code not portable across systems and to transfer the code to a different computer it needs to be
completely rewritten.
(ii)Assembly language or Second Generation language -2G
Assembly language use symbolic programming language that use symbolic notation to represent
machine language instructions. These languages are closely connected to machine language and the
internal architecture of the computer system on which they are used.
Since they are close to machine, assembly language is called low level language.
They were developed in mid1950’s.
They use symbolic codes called mnemonic codes that are easy to remember abbreviations rather
than numbers. Examples of these codes are ADD for add, CMP for compare, MUL for multiply.
Assembly language programs consists of a series of individual statements or instructions that
instruct the computer what to do.
Assembly language consists of a label, operation code, and one or more operands.
Labels are used to identify and reference instructions in the program.
Operation code/ mnemonic specifies operations to be performed: move, add, subtract, compare.
Like the machine language the statement / instructions in assembly language will vary from
machine to another because the language is directly related to internal architecture of the
computer and is not designed to be machine independent. This makes the code written in
assembly language is less portable as the code written in one machine will not run on different
machine.
The code written in assembly language will be very efficient in terms of execution time and main
memory usage as the language is close to the computer.
Programs written in assembly language need a translator known as assembler to convert them
into machine language as the computer does not understand ADD, SUB mnemonics.
Example
MOV AX, 4 //move 4 to register AX
MOV BX, 6 //move 6 to register BX
ADD AX, BX //add the contents of BX and AX and store result in the register AX
(III)Third Generation Language (3GL)
Refinement of second generation programming language.
It spurred the great increase in data processing that occurred in 1960s and 1970s.
The program instructions are not closely related to internal architecture of computer and therefore
called as high-level languages.
A statement written in a high-level language will expand into several machine language
instructions where as in assembly language one statement would generate one machine language
instruction.
3G programming language made programming easier, efficient and less prone to errors.
Example FORTRAN(FORmula translator), COBOL(Common Business Oriented Language)
that made possible for scientist to write programs using familiar terms instead of obscure machine
instructions.
Programs written in High level language can be used to address clients’ problems.
While some high level languages were designed to serve a specific purpose( such as controlling
industry robots or creating graphics) other languages are flexible and considered to be general
purpose languages.
Example – BASIC, FORTRAN, PASCAL, COBOL, C, C++, JAVA.
A translator is need to translate the instructions written in high level language into computer
executable machine language. Such translators are commonly known as Compilers and
interpreters.
3GL have made programming easier to write and debug programs, which gives programmers
more time to think about its overall logic.
Programs written in such language are portable between machines. For example a program
written in standard C can be compiled and executed on any computer that has a standard C
compile.
(iv)Fourth Generation Languages (4GLs)
They are basically non procedural. There is no standard rule that defines what a 4GL.
In non-procedural languages the programmers define what they want the computers to do,
without supplying all the details of how it has to be done.
Characteristics of 4GL are
o Code comprising instructions are written in English like sentences.
o Non procedural, so users concentrates on ‘what ‘ instead of ‘how’ aspect of task.
o Code is easier to maintain.
o Code enhances productivity of the programmer, as they have to type fewer lines of code
to get something done.
Example – Example of 4GL is the Query language that allows a user to request information from a
database with precisely worded English-like sentences. It is used as a database user interface and hides
the specific details of database from the user. For example, when working with Structured Query
Language(SQL) the programmer just needs to remember to few rules of syntax and logic, and it is easier
to learn than COBOL and C.
Let us take an example in which a report has to be generated that displays the total number of students
enrolled in each class and in each semester. Using 4GL, we can write it as
TABLE FILE ENROLMENT
SUM STUDENTS BY SEMESTER BY CLASS
4GL are simpler to learn and work with. But it does not make efficient use of machines
instructions.
(v) Fifth Generation Languages or 5GLs
They are centered on solving problems using constraints given to the program, rather than using
an algorithm written by a programmer.
Constraint based and logic programming languages and some declarative languages form part
of fifth generation languages.
Used in Artificial Intelligence research.
5GL contains visual tools to help develop a program.
Example Prolog, Visual basic, R programming, tensorflow.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
CHARACTERISTICS OF C
C is a high level language which enables the programmer to concentrate on the problem at hand
and not worry about machine code on which the program is running.
Small size – C has only 32 keywords.
Make use of function calls
C is suited for structural programming.
C enables the users to think of problem in terms of functional modules where the collection of
all modules makes up a complete program. This features facilitates easier in programs
debugging, testing and maintenance.
Unlike Pascal, it supports loose typing( character can be treated as an integer and viceversa)/.
Structured language can be organized as a collection of one or more functions.
C program make use of operations and data types, they are fast and efficient.
Facilities lowlevel (bitwise) programming.
Support pointers to refer computer memory, array, structures, and functions.
C is core language as many other programming languages like CH, Java, Perl, etc are based on
C. If you know C, learning other programming language becomes easier.
C is a portable language.
C is an extensible language as it enables the user to add his own function to the C library.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
TAXONOMY OF C LANGUAGE
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
USES OF C
C is a simple language that is used by the software.
C language is primarily used for system programming. The portability, efficiency, the ability to
access specific hardware addresses and low runtime demand on system resources make it a
good choice for implementing operating systems and embedded system applications.
C has been widely accepted by professionals that compilers, libraries and interpreters of other
programming languages are often implemented in C.
Used to implement end-user applications.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
STRUCTURE OF A C PROGRAM
A C program composed of pre-processor commands, a global declaration section and one or
more functions.
Pre-processor directives
Global declarations
main()
{
Local declarations
Statements
}
function1()
{
Local declarations
Statements
}
.
.
.
functionN()
{
Local declarations
Statements
}
Pre-processor directives
Contain special instructions that indicate how to prepare the program for compilation.
One of the most important and used pre-processor commands is include which tells the
compiler that to execute the program, some information needed from the specified header file.
A C program contains one or more functions, where a function is defined as a group of C
statements that are executed together. The statements in a C function are written in logical
sequence to perform a specific task.
The main C function is the most important function and is a part of enemy C program. The
execution of C program begins at this function.
All functions are divided into two parts: declaration section and statement section,
Declaration section precedes the statement section used to describe the data that will be used
in function. Data declared within a function are known as local declaration as that data will be
visible only within the function.
Statement section in a function contains the code that manipulate the data to perform a
specified task.
We can conclude that a C program can have any number of functions depending on tasks that
have to be performed and each function can have any number of statements arranged according
to specific meaningful sequences.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Definition –Algorithm
•An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which specify a finite
sequence of operations that provides the solution to a problem, or to a specific class of problems for any
allowable set of input quantities (if there are inputs).
•Alternatively, we can define an algorithm as a set or list of instructions for carrying out some process step by
step. A recipe in a cookbook is an excellent example of an algorithm. The recipe includes the requirements for
the cooking or ingredients and the method of cooking them until you end up with a nice cooked dish.
An algorithm is a set of instructions that, if faithfully followed, will produce a solution to a given problem or
perform some specified tasks. When an instruction is followed, we say it is executed.
FLOWCHARTS
Flowcharting is a tool developed in the computer industry, for showing the steps involved in a process.
A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by arrows - each
shape represents a step in the process, and the arrows show the order in which they occur. Flowcharting
combines symbols and flow-lines, to show figuratively the operation of an algorithm.
How a Computer Solves a Problem
Solving a problem on a computer involves the following activities:
1. Define the problem.
2. Analyze the problem.
3. Develop an algorithm (a method) for solving the problem.
4. Write the computer program that implements the algorithm.
5. Test and debug (find the errors in) the program.
6. Document the program. (Explain how the program works and how to use it.)
7. Maintain the program.
Flowcharting is a tool developed in the computer industry, for showing the steps involved in a process.
A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by arrows -
each shape represents a step in the process, and the arrows show the order in which they occur.
Flowcharting combines symbols and flowlines, to show figuratively the operation of an
algorithm Examples of Algorithms and Flowcharts.
In computing, there are dozens of different symbols used in flowcharting. In business process
analysis, a couple of symbols are sufficient. A box with text inside indicates a step in the process,
while a diamond with text represents a decision point. See the figure for an example.
Flowcharting Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language programs: Terminal,
Process, input/output, Decision, Connector and Predefined Process. This is not a complete list of all
the possible flowcharting symbols, it is the ones used most often in the structure of Assembly language
programming.
Example 1.Design an algorithm and the corresponding flowchart for adding the test scores as given
below:26, 49, 98, 87, 62, 75
a) Algorithm
1. Start
2. Sum = 0
3. Get the first testscore
4. Add first testscore to sum
5. Get the second testscore
6. Add to sum
7. Get the third testscore
8. Add to sum
9. Get the Forth testscore
10. Add to sum
11. Get the fifth testscore
12. Add to sum
13. Get the sixth testscore
14. Add to sum
15. Output the sum
16. Stop
b) The corresponding flowchart is as follows:
The problem with this algorithm is that, some of the steps appear more than once, i.e. step 5 get second
number, step 7, get third number, etc.
One could shorten the algorithm or flowchart as follows:
1. start
2. sum = 0
3. Get a value
4. sum = sum + value
5. Go to step 3 to get next Value
6. Output the sum
7. Stop
Flowchart
start
Sum=0
Get a value
sum=sum+value
Do you want to
yes get a value
no
stop
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
PSEUDOCODE
• Pseudocode (which means fake code, because its not really programming code) specifies the steps
required to accomplish the task.
• Pseudocode is a type of structured English that is used to specify an algorithm.
• Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules.
Why is Pseudocode Necessary?
The programming process is a complicated one.
You must first understand the program specifications.
Then you need to organize your thoughts and create the program.
You must break the main tasks that must be accomplished into smaller ones in order to be able
to eventually write fully developed code.
Writing Pseudocode will save you time later during the construction & testing phase of a
program's development.
Pseudocode is one of the tools that can be used to write a preliminary plan that can be developed
into a computer program.
Pseudocode is a generic way of describing an algorithm without use of any specific
programming language syntax.
For example, suppose you are required to design an algorithm for finding the average of six
numbers, and the sum of the numbers is given. The pseudocode will be as follows;
Start
Get the sum
Average = sum / 6
Output the average
Stop
Example 4: The following pseudo-code describes an algorithm which will accept two numbers from
the keyboard and calculate the sum and product displaying the answer on the monitor screen.
use variables sum, product, number1, number2 of type real
display “Input two numbers”
accept number1, number2
sum = number1 + number2
print “The sum is “, sum
product = number1* number2
print “The Product is”, product
end program
examples
program
#include<stdio.h>
void main()
{
float rate, balance, interest;
printf("rate and balance values in Rupees\n\n");
scanf("%f %f", &rate, &balance);
interest=rate*balance;
printf("the value of interest = %.2f", interest);
}
Output
rate and balance values in Rupees
0.9
10000
the value of interest = 9000.00
program
#include<stdio.h>
void main()
{ int x,y,z,sum, product;
float average;
printf(" type x, y, z values\n");
scanf("%d %d %d",&x,&y,&z);
sum=x+y+z;
printf("enter the value of sum=%d\n",sum);
average=sum/3;
printf("enter the value of average=%.2f\n", average);
product = x*y*z;
printf("enter the value of product =%d\n", product);
}
output
type x, y, z values
45
67
12
enter the value of sum=124
enter the value of average=41.00
enter the value of product =36180
program
#include<stdio.h>
void main()
{
int a,b;
printf(" type a, b\n");
scanf("%d %d" ,&a,&b);
if (a<b) printf("a is small and b is big\n");
else printf("a is small and b is big\n");
}
Output
type a, b
56
78
a is small and b is big
pseudocode
count assigned zero
While count < 5
Display "I love computers!“
Increment count
End while
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALPHABET SET OF C
Defines a fundamental units used to represent information
May be a letter, digit, special symbol used to represent information.
These characters when combined together to form tokens.
English alphabet {a,b,c,…,z, A, B,C,…, Z}
Digits {0, 1, 2,…, 9}
Special characters {~, !, @, #, $, %, &,*,(,),-,_, +,=,%, /, {,}, [, ], \ , |, ;, :, ‘, “, <, >, ,, ., ?, /}
Escape sequences :
o \' Single Quote
o \” double quotes
o \\ Backslash
o \n New Line
o \r Carriage Return
o \t horizontal Tab
o \v vertical tab
o \b Backspace
o \f Form Feed
o \ooo Octal value
o \xhh Hex value
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
COMMENTS
A well-documented program is a good practice as a programmer. It makes a program more readable and
error finding become easier. One important part of good documentation is Comments.
In computer programming, a comment is a programmer-readable explanation or annotation in
the source code of a computer program
Comments are statements that are not executed by the compiler and interpreter.
Example: This example goes same for C and C++ as the style of commenting remains same for both
the language.
// C program to illustrate
// use of multi-line comment
#include <stdio.h>
int main(void)
{
// Single line Welcome user comment
printf("Welcome to class");
return 0;
}
Output:
Welcome to class
Multi-line comment
Represented as /* any_text */ start with forward slash and asterisk (/*) and end with asterisk and
forward slash (*/).It is used to denote multi-line comment. It can apply comment to more than a single
line. It is referred to as C-Style comment as it was introduced in C programming.
/*Comment starts
continues
continues
.
.
.
Comment ends*/
Example: This example goes same for C and C++ as the style of commenting remains same for both
the language.
/* C program to illustrate use of multi-line comment */
#include <stdio.h>
int main(void)
{
ESCAPE SEQUENCES
In C Programming, the word escape sequences means to escape the character from the sequences of
words and give special meaning to the escaped character.
Example
Let us consider the following word "hello\nworld". Clearly, n is the character which escapes from the
sequences of word, helloworld and a special meaning is given to n i.e) new line.
\b Backspace 008
\? Question 063
\\ Backslash 092
\0 Null 000
\n Escape Sequence
newline.c
#include <stdio.h>
int main()
{
printf("Hello \nProgrammer ");
return 0;
}
output
Hello
Programmer
Note:Statement followed by \n will be printed in New Line.
\t Escape Sequence
horizontalspaces.c
#include <stdio.h>
int main()
{
printf("Hello\tProgrammer ");
return 0;
}
Output
Hello Programmer
Note:Statement followed by \t will be printed after 8 space.
\b Escape Sequence
backspace.c
#include <stdio.h>
int main()
{
printf("Hello\b Programmer ");
return 0;
}
Output
Hell Programmer
Note:\b will backspace a character.
\r Escape Sequence
returncarriage.c
//C program to illustrate \r escape sequence
#include <stdio.h>
int main(void)
{
// Here we are using \r, which is carriage return character.
printf("Hello friday \rsat");
return (0);
}
Output
satlo friday
\a Escape Sequence
alarm.c
#include <stdio.h>
int main()
{
printf("This will make a bell sound\a ");
return 0;
}
Output
Output
'Hello Programmer'
Note:
\' will print single quote '.
Output
"Hello Programmer"
Note:
\"\" will print double quote ".
\? Escape Sequence
questionmark.c
#include <stdio.h>
int main()
{
printf("How are you\? ");
return 0;
}
Output
How are you?
Note:
\? will print? (Question mark).
\\ Escape Sequence
backslash.c
#include <stdio.h>
int main()
{
printf("C\\learn\\from\\2braces.com ");
return 0;
}
Output
C\learn\from\2braces.com
Note:
\\ will print a single backslash (\).
\f Escape Sequence
formfeed.c
#include <stdio.h>
int main()
{
printf("\f - female sign. ");
return 0;
}
Output
♀ - female sign.
Note:
\f will print female sign (♀).
\v Escape Sequence
#include <stdio.h>
int main()
{
printf("\v - male sign. ");
return 0;
}
Output
♂ - male sign.
Note:
\v will print male sign (♂).
\0 Escape Sequence (means \zero)
#include <stdio.h>
int main()
{
printf("Hello \0 Programmer ");
return 0;
}
Output
Hello
Note: The statement followed by \0 will not display.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
TOKENS
Definition
C program is basically a collection of many functions. But it has basic building blocks,
these basic buildings blocks in C language which are constructed together to write a C
program. This basic building blocks are called Token.
Each and every smallest individual unit in a C program is known as C tokens
Simply we can say that C program is also a collection of tokens, comments, and
whitespaces.
In C, Programming tokens are of six types. They are,
NOTE:
3 Identifier -443 43
5 Special Symbol * @
6 Operators * ++
Token Meaning
Special Symbols other than the Alphabets and Digits and white-spaces
Symbol
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
KEYWORDS IN C
Keywords in C can be defined as the pre-defined or the reserved words having its own importance,
and each keyword has its own functionality. Since keywords are the pre-defined words used by the
compiler, so they cannot be used as the variable names. If the keywords are used as the variable names,
it means that we are assigning a different meaning to the keyword, which is not allowed. C language
supports 32 keywords given below:
do if Static while
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IDENTIFIERS
The C programmer needs to make up names for things such as variables, function names
and symbolic constants. A name that makes up is called a user identifier.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.
It does not contain the underscore character. It can contain the underscore character.
example.
int main()
{
int a=10;
int A=20;
printf("Value of a is : %d",a);
printf("\nValue of A is :%d",A);
return 0;
}
Output
Value of a is : 10
Value of A is :20
The above output shows that the values of both the variables, 'a' and 'A' are different. herefore, we
conclude that the identifiers are case sensitive.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
DATA TYPES
Each variable in C has an associated data type. Each data type requires different amounts of memory
and has some specific operations which can be performed over it. Let us briefly describe them one by
one:
Following are the examples of some very common data types used in C:
char: The most basic data type in C. It stores a single character and requires a single byte of
memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with single precision.
double: It is used to store decimal numbers (numbers with floating point value) with double
precision.
Integers
Integers are whole numbers with a range of values supported by particular machine. Generally integers
occupy one word of storage, and since the word sizes of machines vary(16 or 32 bits) the size of an
integer that can be stored depends on the computer. If we use a 16 bit word length, the size of the integer
value is limited to the range -32768 to +32767. A signed integer use one bit for sign and 15 bits for the
magnitude of the number. Similarly a 32bit word length can store an integer ranging from 2,147,483,648
to 2,147,483, 647.
In order to provide some control over the range of numbers and storage space,
C has 3 classes of integer storage namely
short int
int,
long int, in both signed and unsigned forms.
For example short int represents fair small integer values and requires half the amount of storage
as a regular int number uses.
Unlike signed integers, unsigned integers use all the bits for the magnitude of the number and
are always positive.
Floating point number are stored in 32 bits with 6 digits of precision. Floating point numbers are defined
C by the keyword float. When the accuracy provided by a float number is not sufficient, the type double
can be used to define the number. A double data type number uses 64 bits giving a precision of 14 digits.
These are known as double precision numbers. Double type represents the same data type that float
represents, but with a greater precision. To extend the precision further, we may use long double which
uses 80 bits.
Character types
A single character can be defined as a character type data. Characters are usually stored in 8 bits of
internal storage. The qualifier signed or unsigned may be applied to char. While unsigned characters
have values between 0 and 255 singed characters have value from -128 to 127.
These ranges may vary from compiler to compiler. Below is list of ranges along with the memory
requirement and format specifiers on 16bit gcc compiler.
We can use the sizeof() operator to check the size of a variable. See the following C program for the
usage of the various data types:
#include<stdio.h>
int main()
{
int a = 1;
char b = 'G';
double c = 3.14;
printf("Hello World!\n");
// printing the variables defined above along with their sizes
printf("character: is %c and size is %lu byte.\n", b, sizeof(char));
printf("integer: value is %d and my size is %lu bytes.\n", a, sizeof(int));
printf("double: value is %lf and my size is %lu bytes.\n", c, sizeof(double));
printf("Bye! See you soon. :)\n");
return 0;
}
Output
Hello World!
character: is G and size is 1 byte.
integer:value is 1 and my size is 4 bytes.
double:value is 3.140000 and my size is 8 bytes.
Bye! See you soon. :)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
FORMAT SPECIFIERS IN C
Format specifiers define the type of data to be printed on standard output. You need to use format
specifiers whether you're printing formatted output with printf() or accepting input with scanf().
Some of the % specifiers that you can use in ANSI C are as follows:
%c a single character
%s a string
%n prints nothing
%% the % symbol
Examples:
%c single character format specifier:
#include <stdio.h>
int main()
{
char first_ch = 'f';
printf("%c\n", first_ch);
return 0;
}
Output:
f
1c
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
VARIABLES
DEF :A variable is defined as a meaningful name given to a data storage location in computer
memory. When using a variable, we actually refer to address of the memory where the data is stored.
C supports two kinds of variables - numeric and character
1. Numeric variable
They can be used to store either integer values or floating point values.
While an integer value is s whole number without a fractional part or decimal point, a floating
point vale can have a decimal point.
Numeric variables may be associated with modifiers like short, long, signed and unsigned.
The difference between signed and unsinged numeric variables is that signed variables can be
either negative or positive but unsigned variables van only be positive.
Therefore by using the unsigned variables we can increase the maximum positive range. To
declare an unsigned variable the unsigned modifier must be added during the declaration of the
variable.
2. Character variable
They are just single characters enclosed within single quotes. These characters could be any character
from the ASCII character set - may be letters, numerals or special characters. In C, number that is given
in single quotes is not the same as a number without them.
3. Declaring variable
Each variable to be used in the program must be declared. To declare a variable, specify the data type of
the variable followed by its name. The data type indicates the kind of the values that the variable will
store. Variables names should always be meaningful and must reflect the purpose of their usage in the
program. The memory location of the variable is of importance to the compiler only and not to the
programmer. Programmers must only be concerned with accessing data through their symbolic names.
Variable declaration always ends with a semicolon.
For example
int emp_sal;
float salary;
Char grade;
Double balance;
Variables should be declared before using them. Variables should be declared closest to their first
point of use to make the source code easier to maintain.
In C, variables are declared at the basic places as follows/:
1. When a variable is declared inside a function it is known as a local variable.
2. When a variable is declared in the definition of function parameters it is known as formal
parameter.
3. When the variables is declared outside all functions, it is known as a global variable.
4. Initializing variables
Initialize the variable we can also initialize them with some value. For example
int exp_sal=5;
float salary = 2345.78;
char grade=’A’;
If you want to both the variables to be
declared in a single statement then write
int count=0, flag=1;
When variables are declared but not initialized they usually contain garbage values.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
CONSTANTS
Definition
They are identifiers whose value don’t change. While values of variables can be changed at any time,
values of constants never be changed.
Constants are used to define fixed values like pi. It is an explicit data value specified by the
programmer. The value of the constant is known to the compiler at the compile time. C allows the
programmer to specify constants of integer type, floating point type, character type and string type.
Diagram
Integer constants
A constant of integer type consists of a sequence of digits. For example, 1, 34, 567 are valid integer
constants. An integer like 1234 is of type int. For a long integer constant the literal is succeeded with
either ‘L’ or ‘l’ (like 1234567L). Similarly an unsigned int literal is written with a ‘U’ or ‘u’ suffix.
Therefore 1234L, 1234l, 1234U, 1234u, 1234LU are valid integer constants.
Integer literals can be expressed in decimal, octal or hexadecimal notation. By default an integer is
expressed in decimal notation. Decimal integers consists of a set of digits, o through 9, preceded by an
optional – or + sign. Examples of decimal integer constants include: 1223, -123, +123
While writing integer constants, embedded system spaces, commas, and non-digit characters are not
allowed. Hence the following constants are considered as invalid.
123 456
12,34,567
$123
Floating point constants
A floating point constant consists of integer part, a decimal point, a fractional part and an exponent
field containing e or E followed by an integer where the fractional part and integer part are a sequence
of digits. Some floating point numbers may have certain parts missing. Some valid examples of
floating point numbers are: 0.02, -0.23, 123.456, +0.34, 0.9, -0.7.
A literal like 0.07 is treated as of type double by default. To make it a float type literal, you must
specify it using suffix ‘F’ or ‘f. Consider some valid floating point literals given below.
A floating point number may be expressed in scientific notation. The mantissa is either a floating
point number or an integer and exponent is an integer with an optional plus or minus sign. Therefore
the following are valid floating point numbers.
0.5e2, 14E-2, 1.2e+3, 2.1E-3, -5.6e-2.
Character constants
A character constants consists of a single character enclosed in single quotes. For example ‘a’ and ‘@’
are character constants. All escape sequences are also character constants.
String constants
A string constant is a sequence of characters enclosed in double quotes. So “a” is not the same as ‘a’.
The characters comprising the string constant are stored in successive memory locations. When a
string constant is encountered in a C program, the compiler records the address of the first character
and appends a null character (\0’) to the string to mark at the end of the string.
Declaring constants
To declare a constant, precede the normal variable declaration with const keyword and assign it a
value. For example,
Const float pi=3.14;
The const keyword specifies that the value of pi cannot change.
Another way to designate a constant is to use preprocessor command define.
EXAMPLE: #define pi 3.14159
#define service _tax 0.12
Constant names are usually written in capital letters to visually distinguish them from other variable
names which are written in lower case letters. #define is a compiler pre-processor directive not a
statement.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
of A is :20
STRINGS
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the
null character at the end of the array, the size of the character array containing the string is one more
than the number of characters in the word "Hello."
Char name[]=’A’ ;
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[ ] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print the
above mentioned string −
#include <stdio.h>
int main () {
What is String in C?
A String in C is nothing but a collection of characters in a linear sequence. 'C' always treats a string a
single data even though it contains whitespaces. A single character is defined using single quote
representation. A string is represented using double quote marks.
A C String is a simple array with char as a data type. 'C' language does not directly support string as a
data type. Hence, to display a String in C, you need to make use of a character array.
The above example represents string variables with an array size of 15. This means that the given C
string array is capable of holding 15 characters at most. The indexing of array begins from 0 hence it
will store characters from a 0-14 position. The C compiler automatically adds a NULL character
'\0' to the character array created.
Let's study the String initialization in C. Following example demonstrates the initialization of Strings
in C,
When writing interactive programs which ask the user for input, C provides the scanf(), gets(), and
fgets() functions to find a line of text entered from the user.
When we use scanf() to read, we use the "%s" format specifier without using the "&" to access the
variable address because an array name acts as a pointer. For example:
#include <stdio.h>
int main()
{
char name[10];
int age;
printf("Enter your first name and age: \n");
scanf("%s %d", &name, &age);
printf("You entered: %s %d", name, age);
}
Output:
The problem with the scanf function is that it never reads entire Strings in C. It will halt the reading
process as soon as whitespace, form feed, vertical tab, newline or a carriage return occurs. Suppose we
give input as "Guru99 Tutorials" then the scanf function will never read an entire string as a
whitespace character occurs between the two names. The scanf function will only read Guru99.
In order to read a string contains spaces, we use the gets() function. Gets ignores the whitespaces.
It stops reading when a newline is reached (the Enter key is pressed).For example:
#include <stdio.h>
int main() {
char full_name[25];
printf("Enter your full name: ");
gets(full_name);
printf("My full name is %s ",full_name);
return 0;
}
Output:
Another safer alternative to gets() is fgets() function which reads a specified number of characters. For
example:
#include <stdio.h>
int main() {
char name[10];
printf("Enter your name plz: ");
fgets(name, 10, stdin);
printf("My name is %s ",name);
return 0;}
Output:
The standard printf function is used for printing or displaying Strings in C on an output device. The
format specifier used is %s
Example,
printf("%s", name);
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
printf()
%w.p type-specifier
Where
w is the number that specifies the total number of columns for the output value
p is number that specifies the number of digits to the right of the decimal point or the number
of characters to be prited from a string.
Both w and p are optional.
type-specifiers for printf()
Printf(“ x = %d”, x)
The following examples illustrate the output of the number 9876 under different formats.
Printf(“%-06d”,9876) 987600
It is possible to force the printing to be left –justified by placing a minus sign directely after
the % character as shown in fourth example.
It is also possible to pad with zeros the leading blanks by placing a 0 before the field width
specifier in the last item above.
The minus(-) and zero(0) are known as flags. Long integers may be printed by specifying ld in
the place of d in the format specification. Similarly we may use hd for printing short integers.
example
#include<stdio.h>
void main(void)
{
int m=12345;
long n =987654;
printf("%d\n", m);
printf("%10d\n", m);
printf("%o10d\n", m);
printf("%-10d\n", m);
printf("%10ld\n", n);
printf("%10ld\n", -n);
}
output
12345
12345
3007110d
12345
987654
-987654
integer w indicates the minimum number of positions that are to be used for the display of the
value and
the integer p indicates the number of digits to be displayed after the decimal point.
The value, when displayed, is rounded to p decimal places and printed right-justified in the
field of w column.
Leading blanks and trailing zeros will appear as necessary. The default precision is 6 decimal
places. The negative numbers will be printed with minus sign.
following examples illustrate the output of the number y=98.7654 under different formats
specifications.
Printf(“enter the data value= %7.4f \n” , 98.7654)
Program
#include<stdio.h>
void main()
{
float y=98.7654;
printf("% 7.4f\n", y);
printf("%f\n",y);
printf("7.2f\n", y);
printf("-7.2f\n",y);
printf("07.2f\n",y);
printf("\n");
printf("%10.2e\n", y);
printf("%12.4e\n", -y);
printf("%-10.2e\n",y);
printf("%e\n",y);
}
Output
98.7654
98.765404
7.2f
-7.2f
07.2f
9.88e+01
-9.8765e+01
9.88e+01
9.876540e+01
int main()
{
char a= 'c';
printf("Value of a is: %c", a);
return 0;
}
Output
Printing of strings
It is of the form %w.ps, where w specified the field width for display and
p instructs that only the first p characters of the string are to be displayed. The display is
right-justified.
The following examples show the effect of variety of specifications in printing a string “NEW
DELHI 110001” containing 16 characters including blanks.
scanf()
The general form of scanf is
Scanf(“control string”, &arg1, &arg2, …. &argn);
The control sting specifies the field format in which the data is to be entered and the arguments arg1,
arg2, …, argn specify the address of locations where the data is stored. Control string and arguments
are separated by commas.
Output
enter 3 integer numbers
34 56 78
34 56 78
Output
enter serial number and name one
34
welcome
34 welcome
The corresponding argument should be a pointer to a character array. %c may be used to read a single
character when the argument is a pointer to a char variable. When we use %wc for reading a string, the
system will wait until the wth character is keyed in.
getchar()
Reading a single character is achived by getchar() function.
The general form
variable name = getchar();
Variable name is a valid C name that has been declared as char type. When this statement is encounted
the computer waits until a key is pressed and then assigns this characte as a value to getchar function.
Since getchar is used on the rightside of an assignmetn statement the character value of getchar() is in
turn assigned to the variable name on the left.
#include<stdio.h>
void main()
{
char d;
printf("ENTER THE CHARACTER\n");
d=getchar();
printf("%c",d);
}
Output
ENTER THE CHARACTER
y
y
Writing a character
like getchar,there is an analogous function putchar for writing characters one at a time to the terminal.
It take the form as
putchar(variable name);
Where the variable_name is a type char variable containing a character.This statement displays the
character contained in the variable_name at the terminal
For example the statements
answer = ‘Y’;
putchar(answer) will display Y in the terminal. The statement putchar(‘\n’); would cause the curson to
move on the beginning of the next line.
#include<stdio.h>
void main()
{
char d;
printf("ENTER THE CHARACTER\n");
d=getchar();
putchar(d);
}
Output
ENTER THE CHARACTER
i
i
@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
EXPRESSIONS
definition
An expression is a formula in which operands are linked to each other by the use of operators to
compute a value. An operand can be a function reference, a variable, an array element or a
constant.
An expression is a combination of variables constants and operators written according to the
syntax of C language. In C every expression evaluates to a value i.e., every expression results in
some value of a certain type that can be assigned to a variable. Some examples of C expressions
are shown in the table given below.
Algebraic Expression C Expression
a x b – c a * b – c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a * b / c
(x / y) + c x / y + c
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression is evaluated
first and then replaces the previous value of the variable on the left hand side. All variables used in the
expression must be assigned values before evaluation is attempted.
x=a*b–c
y=b/c*a
z = a – b / c + d;
#include <stdio.h>
int main()
{
int a,b,c;
float x,y,z;
a=9;
b=12;
c=3;
x=a-b/3+c*2-1;
y=a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
printf("x = %f",x);
printf("y = %f",y);
printf("z = %f",z);
return 0;
}
output
x = 10.000000y = 7.000000z = 4.000000
Precedence in Arithmetic Operators
An arithmetic expression without parenthesis will be evaluated from left to right using the rules of
precedence of operators. There are two distinct priority levels of arithmetic operators in C.
High priority * / %
Low priority + -
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
C - SCOPE RULES
A scope in any programming is a region of the program where a defined variable can have its existence
and beyond that variable it cannot be accessed.
There are three places where variables can be declared in C programming language −
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to functions
outside their own. The following example shows how local variables are used. Here all the variables a,
b, and c are local to main() function.
example
#include <stdio.h>
int main () {
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Output
value of a = 10, b = 20 and c = 30
Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold
their values throughout the lifetime of your program and they can be accessed inside any of the functions
defined for the program.A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. The following program show how
global variables are used in a program.
EXAMPLE
#include <stdio.h>
/* global variable declaration */
int g;
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Output
value of a = 10, b = 20 and g = 30
A program can have same name for local and global variables but the value of local variable
inside a function will take preference. Here is an example −
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{ /* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}
Output
value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take precedence over
global variables. Following is an example −
example
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main () {
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
output
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
STORAGE CLASSES
Every variable in C programming has two properties: type and storage class. Type refers to the data
type of a variable. And, storage class determines the scope, visibility and lifetime of a variable.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Local (auto) Variable
The variables declared inside a block are automatic or local variables. The local variables exist only
inside the block in which it is declared. The example above defines two variables with in the same
storage class. 'auto' can only be used within functions, i.e., local variables.
Example
#include <stdio.h>
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
return 0;
}
Output:
Example 2
#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}
Output:
11 20 20 20 11
Global Variable/ external variable
Variables that are declared outside of all functions are known as external or global variables. They are
accessible from any function inside the program.
#include <stdio.h>
void display();
extern int n = 5; // global variable
int main()
{
++n;
display();
return 0;
}
void display()
{
++n;
printf("n = %d", n);
}
Output
7
Register Variable
It is a special kind of variable that stores in the CPU register. The advantages of register variables are
faster than the remaining variables. The register storage class is used to define local variables that
should be stored in a register instead of RAM. This means that the variable has a maximum size equal
to the register size (usually one word) and can’t have the unary ‘&’ operator applied to it (as it does not
have a memory location).
#include <stdio.h>
int main()
{
register int a = 10;
++a;
printf("Value of a : %d", a);
printf("\nEnter a value");
scanf("%d" , a);
--a;
printf("\n Value of a : %d", a);
return 0;
}
Output:
Value of a : 11
Enter a value 30
Value of a : 29
Static Variable
A static variable is declared by using the static keyword. For example;
static int i;
The value of a static variable persists until the end of the program.
int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}
Output
6 11
During the first function call, the value of c is initialized to 1. Its value is increased by 5. Now, the
value of c is 6, which is printed on the screen.
During the second function call, c is not initialized to 1 again. It's because c is a static variable. The
value c is increased by 5. Now, its value will be 11, which is printed on the screen.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
OPERATORS IN C
• An operator is a symbol that specifies the mathematical, logical or relational operation to be
performed.
• C language supports different types of operators, which can be used with variables and
constants to form expressions.
• These operators can be categorized into the following major groups.
• Comma operator
• Unary operators
• Pre and post increment and decrement operators
• Arithmetic operators
• Relational operators
• Logical operators
• Sizeof operator
• Conditional operators
• Assignment operators
• Bitwise operators
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
COMMA OPERATOR
comma.c
commaprintf.c
commascanf.c
The comma operator can be used to link the related expressions together. A comma-linked list of
evaluated left to right and he value of right-most expression is the value of the combined expression.
For example
int i = (5, 10); /* 10 is assigned to i*/
int j = (f1(), f2()); /* f1() is called (evaluated) first followed by f2().
The returned value of f2() is assigned to j */
Value = (x=10, y=5, x+y); //first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15 to
value, Since comma operator has lowest precedence of all operators , the parenthesis are necessary.
example
#include <stdio.h>
int main()
{
int x = 10;
int y = 15;
Output
15
example
#include <stdio.h>
int f1() {
return 43;
}
int f2() {
return 123 ;
}
int main(void) {
int a;
a = (f1() , f2());
printf("%d", a);
return 0;
}
Output
It gives 123 as output as the ‘, ’ works as operator and being in braces it works and evaluates the
second expression and gives output.
Exchanging values :
t = x, x =y, y =t;
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
OUTPUT:
123456789
#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
OUTPUT:
20 19 18 17 16 15 14 13 12 11
#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
1234
Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-increment
operator.
Step 2 : This incremented value “1” is compared with 5 in while expression.
Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and output is displayed as “1
2 3 4”.
#include <stdio.h>
int main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
12345
Step 1 : In this program, value of i “0” is compared with 5 in while expression.
Step 2 : Then, value of “i” is incremented from 0 to 1 using post-increment operator.
Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and output is displayed as “1
2 3 4 5”.
#include <stdio.h>
int main()
{
int i=10;
while(--i > 5 )
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
9876
Step 1 : In above program, value of “i” is decremented from 10 to 9 using pre-decrement
operator.
Step 2 : This decremented value “9” is compared with 5 in while expression.
Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and output is displayed as “9
8 7 6”.
#include <stdio.h>
int main()
{
int i=10;
while(i-- > 5 )
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
98765
Step 1 : In this program, value of i “10” is compared with 5 in while expression.
Step 2 : Then, value of “i” is decremented from 10 to 9 using post-decrement operator.
Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
Above 3
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ASSIGNMENT OPERATORS IN C
Assignment operators are used to assigning value to a variable. The left side operand of the assignment
operator is a variable and right side operand of the assignment operator is a value. The value on the
right side must be of the same data-type of the variable on the left side otherwise the compiler will
raise an error.
For example:
a = 10;
b = 20;
ch = 'y';
“+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the variable
on the left.
Example:
(a += b) can be written as (a = a + b)
EXAMPLE
// C program to demonstrate
// working of Assignment operators
#include <stdio.h>
int main()
{
// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("Value of a is %d\n", a);
return 0;
}
Output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
& (bitwise AND) : Bitwise AND is a binary operator and requires two operands. When we use the
bitwise AND operator, the bit in the first operand is ANDed with the corresponding bit in the second
operand. The result of AND is 1 only when the bits in both operands are 1, otherwise it is 0.
| (bitwise OR) : Bitwise OR is a binary operator and requires two operands. When we use the bitwise
OR operator, the bit in the first operand is ORed with the corresponding bit in the second operand. The
result of OR is 0 only when the bits in both operands are 0, otherwise it is 1.
^ (bitwise XOR) : Bitwise XOR is a binary operator and requires two operands. When we use the
bitwise XOR operator, the bit in the first operand is XORed with the corresponding bit in the second
operand. The result of XOR is 1, if bits of both operands have different value, otherwise it is 0.
<< (bitwise left shift) : Bitwise left shift operator is used for shifting the bits left. It requires two
operands; the left operand is the operand whose bits are shifted and the right operand indicates the
number of bits to be shifted.
>> (bitwise right shift) : Bitwise right shift operator is used for shifting the bits right. It requires two
operands; the left operand is the operand whose bits are shifted and the right operand indicates the
number of bits to be shifted.
~ (bitwise NOT) : Bitwise NOT (One's complement) operator is an unary operator (works on only
one operand). It changes 1 to 0 and 0 to 1.
#include <stdio.h>
int main(void)
{
unsigned int a = 4, b = 5; /* a = 4(00000100), b = 5(00000101) */
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a&b); /* The result is 00000100 */
printf("a|b = %d\n", a|b); /* The result is 00000101 */
printf("a^b = %d\n", a^b); /* The result is 00000001 */
printf("~a = %d\n", a = ~a); /* The result is 11111011 */
printf("b<<1 = %d\n", b<<1); /* The result is 00001010 */
printf("b>>1 = %d\n", b>>1); /* The result is 00000010 */
return 0;
}
Output:
a = 4, b = 5
a&b = 4
a|b = 5
a^b = 1
~a = -5
b<<1 = 10
b>>1 = 2
sizeof() Operator
sizeof is an unary operator that gives the size of its operand in terms of bytes. The operand can be a
variable, constant or any datatype( int, float, char etc). For Example, sizeof(char) gives the size
occupied by a char data type.
The following program demonstrates how you use sizeof() operator to check the size of
fundamental data types on your system.
#include <stdio.h>
int main(void)
{
printf("Size of int = %u\n", sizeof(int));
printf("Size of char = %u\n", sizeof(char));
printf("Size of float = %u\n", sizeof(float));
printf("Size of double = %u\n", sizeof(double));
return 0;
}
Output:
Size of int = 4
Size of char = 1
Size of float = 4
Size of double = 8
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ARITHMETIC OPERATORS
* Multiplication
/ Division
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;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
The operators +, - and * computes addition, subtraction, and multiplication respectively as you might
have expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler
neglects the term after the decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1.
The % operator can only be used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
C ASSIGNMENT OPERATORS
An assignment operator is used for assigning a value to a variable. The most common assignment
operator is =
Operator Example Same as
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
return 0;
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
C RELATIONAL OPERATORS
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.
== Equal to 5 == 3 is evaluated to 0
return 0;
}
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
C LOGICAL OPERATORS
An expression containing logical operator returns either 0 or 1 depending upon whether expression
results true or false. Logical operators are commonly used in decision making in C programming.
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Example
#include <stdio.h>
int main() {
char a = 'S';
double b = 4.65;
printf("Size of variable a : %d\n",sizeof(a));
printf("Size of an expression : %d\n",sizeof(a+b));
int s = (int)(a+b);
printf("Size of explicitly converted expression : %d\n",sizeof(s));
return 0;
}
Output
Size of variable a : 1
Size of an expression : 8
Size of explicitly converted expression : 4
Example
#include<stdio.h>
int main()
{
char text[]="California";
printf("number of characters in the text =%d", sizeof text);
return 0;
}
Output
number of characters in the text =11
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
CONDITIONAL OPERATOR IN C
The conditional operator is also known as a ternary operator. The conditional statements are the
decision-making statements which depends upon the output of the expression. It is represented by two
symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also
a decision-making statement.
OUTPUT:
If we provide the age of user above 18, then the output would be:
Now, we will see how a conditional operator is used to assign the value to a variable.
Output
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ARROW OPERATOR
This operator(->) is built using a minus(-) operator and a greater than(>) relational operator. Moreover,
it helps us access the members of the struct or union that a pointer variable refers to.
The . (dot) operator and the -> (arrow) operator are used to reference individual members of classes,
structures, and unions.
The dot operator is applied to the actual object. The arrow operator is used with a pointer to an object.
For example, consider the following structure −
struct student
{
char first_name[16];
int age;
int regno;
} cse_biher;
To assign the value "zara" to the first_name member of object emp, you would write something as
follows −
strcpy(cse_biher->regno,"u20cse012");
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@