0% found this document useful (0 votes)
12 views

Complete First Unit in Pps -28th Nove 2021

The document outlines the course U20CSEJ01 - Programming for Problem Solving, detailing its objectives, prerequisites, and structure over five units. It covers fundamental programming concepts, including algorithms, data types, operators, functions, pointers, structures, and the evolution of programming languages, particularly C. The course aims to equip students with problem-solving skills through programming and understanding of various programming paradigms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Complete First Unit in Pps -28th Nove 2021

The document outlines the course U20CSEJ01 - Programming for Problem Solving, detailing its objectives, prerequisites, and structure over five units. It covers fundamental programming concepts, including algorithms, data types, operators, functions, pointers, structures, and the evolution of programming languages, particularly C. The course aims to equip students with problem-solving skills through programming and understanding of various programming paradigms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

U20CSEJ01 – PROGRAMMING FOR PROBLEM

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

Evolution of programming & languages – problem solving through programming – Creating


algorithms – Drawing flowcharts- Writing pseudocode- Evolution of C language, its usage
history– Input and output functions: printf and scanf – Variables and identifiers – Expressions-
single line and multiline comments – Constants, Keywords – Values, Names, Scope, Binding,
Storage classes– Numeric data types: integer- Numeric Data types: floating point – Non-
Numeric data types: char and string - Increment and decrement operator – comma, Arrow and
assignment operator – Bitwise and Size of operator.

UNIT II OPERATORS & LOOPING STATEMENTS

Relational and logical operators-condition operators- operator precedence – expressions with


pre/post increment operator – expressions with conditional and assignment operators- if
statement in expression –l- value and r-value in expression– control statements – if else, else if
and nested if – switch case – iterations, conditional and unconditional branches – for loop, while
loop, do while loop, goto, break, continue – array basics and types – array initialization and
declaration -initialization of one dimensional array – accessing and indexing one dimensional
array – Array operations – One dimensional array operations.

UNIT III ARRAY & FUNCTIONS

Initializing and accessing 2D array-initializing multidimensional array-array programs-2D array


contiguous memory- array advantages and limitations-array construction for real time
applications - common programming errors- string basics - string declaration and initialization-
string functions-gets(), puts()- getchar() - putchar()- printf()- string functions –atoi, strlen, strcat,
strcmp, - string functions :sprint, sscanf, strrev, strcpy, strtok,- arithmetic characters on strings
– functions declaration and definition – types: call by value, call by reference - function with
and without arguments and no return values – passing arrays to functions with return types-
recursion and recursion functions.

UNIT IV FUNCTIONS & POINTERS

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.

UNIT V STRUCTURE & UNION

Initializing Structure, Declaring structure variable – structure using typedef, Accessing


members– Nested structure – Accessing elements in a structured array – Array of structure –
Accessing elements in structure array – Passing Array of structure to function – Array of pointers
to structures – Bit manipulation to structure and pointer to structure – Union Basic and
declaration – Accessing union members- Pointers to Union – Dynamic memory allocation,
mallaoc, realloc, free – Allocation Dynamic array – Multidimensional array using dynamic
memory allocation – file:opening, defining, closing, File modes, File types – writing contents
into a file – Reading file contents – Appending an existing file – File permissions and rights –
changing permissions and rights.
UNIT I -INTRODUCTION

Evolution of programming & languages – problem solving through programming – Creating


algorithms – Drawing flowcharts- Writing pseudocode- Evolution of C language, its usage history–
Input and output functions: printf and scanf – Variables and identifiers – Expressions- single line
and multiline comments – Constants, Keywords – Values, Names, Scope, Binding, Storage classes–
Numeric data types: integer- Numeric Data types: floating point – Non-Numeric data types: char
and string - Increment and decrement operator – comma, Arrow and assignment operator –
Bitwise and Size of operator. 12

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

EVOLUTION OF C LANGUAGE- HISTORY


• C is derived from ALGOL (first language to use block structure) in the 1960s which led the
way for the development if structured programming concepts.
• Before C several other programming languages were developed. For example, In the year 1967
a language called BCPL (Basic Combined Programming language) was developed by Martin
Richard for writing system software. It was a type-less language which facilitated direct
access of memory. This made it useful for system programmers.
• In the year 1970, ken Thompson developed a language using features of BCPL called B which
was used to develop the first version of unix OS at Bell laboratories.
• The programming language C was developed in the early 1970s by Dennis Ritchie at Bell
laboratories to be used by Unix OS.
• It was named C because many of its features were derived from an earlier language called ‘B’.
Both BCPL and B are typeless languages.
• C was developed in the year 1972 that took concepts from ALGOL, BCPL and B.
• Since UNIX operating system was developed at BELL laboratories along with C language, C
and UNIX are strongly associated with each other.
• During 1970s, C has evolved into what is known as “traditional C”.
• It was become popular In 1978, C was documented and popularized in the book The C
programming Language “K & R C” by Kernighan and Dennis Ritchie.
• In the year 1983, The American National Standards Institute (ANSI) started working on
defining the standard for C.
• In 1990, International Standard Organisation (ISO) adopted the ANSI standard. This version of
C came to be known as C89.
• In the year 1995, some micro changes were made to C89 known as C95.
• In 1999, some significant changes were made to C95 known to be C99.
Some of the changes in the C99 version are
 Extension to the characters types, so that they can support even non-english characters that is
all the special symbols like @,#,$,%, {, }and so on.
 Boolean data type, like bool x=true; or bool x = false;
 Extension to the integer type like short int and long int, again signed and unsigned short int and
signed and unsigned long int
 Including definitions in the for statement
 Inclusion of imaginary and complex types
 Addition of //, known as line comment.

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

WRITING A FIRST C PROGRAM


To write a C program we need to write the code, for this open a text editor.
 If you are a windows user you may have to use notepad and if you prefer to work on
UNIX/LINUX you can use vi editor.
 Once the text editor is opened on your screen, type the following statements.
#include<stdio.h>
int main()
{
printf(“\n welcome to the world of C”);
return 0;
}
Output
welcome to the world of C
#include<stdio.h>
 This is a pre-processor command that comes as the first statement in our code
 All pre-processor commands start with a symbol #.
 #include statement tells the compiler to include the standard input/output library or
header file in the program.
 This file has some built-in functions. By simply including this header file in our code,
we can use this function directly. It contains functions for input and output of data like
reading values from keyboard and printing results on screen.
int main()
 Every C program contains main() function which is the starting point of the program.
 int is the return value of the main() function.
 After all the statements in the program have need written, the last statement of the
program will return an integer value to the operating systems.
 {} – the two curly brackets are used to group all related statements of main function.
 All the statements between braces from function body.
printf(“\n welcome to the world of C”);
 printf function is defined in stdio.h and used to print text on the screen. The message
that has to be displayed on the screen is enclosed within double quotes and put inside
brackets.
 ‘\n’ – escape sequence and represents a newline character, used to print the message on
a newline on the screen.
return 0;
this is the return command that is used to return the value of the 0s to give an indication
that there were no errors during execution of the program.
Now we have written all statements using text editor save the file as first.c
Using the command prompt change to the directing in which you had saved your file and
then type
C:\> tc first.c – to compiler C program which will produce .exe file. Then run the .exe file
to produce the output of the program.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

ALGORITHMS, PSEUDOCODE AND FLOWCHARTS


An algorithm is a representation of a solution to a problem. If a problem can be defined as a
difference between a desired situation and the current situation in which one is, then a problem
solution is a procedure, or method, for transforming the current situation to the desired one. We
solve many such trivial problems every day without even thinking about it, for example making
breakfast, travelling to the workplace etc. But the solution to such problems requires little
intellectual effort and is relatively unimportant. However, the solution of a more interesting
problem of more importance usually involves stating the problem in an understandable form and
communicating the solution to others. In the case where a computer is part of the means of
solving the problem, a procedure, explicitly stating the steps leading to the solution, must be
transmitted to the computer. This concept of problem solution and communication makes the
study of algorithms important to computer science.

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

•In other words, an algorithm is a step-by-step procedure to solve a given problem.

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

Example—Develop the Algorithm


Using the notion of an algorithm and the concept of a variable, we develop the following algorithm for
calculating the area of a square, given one side:

Algorithm for calculating area of square, given one side:


1. Ask the user for the length of a side.
2. Store the value in the box s.
3. Calculate the area of the square (s × s).
4. Store the area in the box a.
5. Print the value in box a, appropriately labelled.
6. Stop.

There are two tools used to implement an algorithm.


1.Flowchart
2. Pseudocode

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

The corresponding flowchart will appear as follows


Example 3: This is the pseudo-code required to input three numbers from the keyboard and output the
addition as result.
Use variables: sum, number1, number2, number3 of type integer
Accept number1, number2, number3
Sum = number1 + number2 + number3
Print sum
End program

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: If then Else


if age > 17
Display a message indicating you can vote.
else
Display a message indicating you can't vote.
Endif

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

Single line and mulitline comments in C

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.

In C/C++ there are two types of comments :


1. Single line comment
2. Multi-line comment
Single line Comment
 Represented as // double forward slash.
 It is used to denote a single line comment. It applies comment to a single line only. It is
referred to as C++-style comments as it is originally part of C++ programming.

for example:// single line comment


a = s * s; //calculate area; store result in a

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)
{

/* Multi-line Welcome user comment written to demonstrate


comments
in C/C++ */
printf("Welcome to class");
return 0;
}
Output:
Welcome to class
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

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.

Escape Sequences Facts


 An Escape sequences are non-printing characters.
 An Escape sequences are certain characters associated with \ (backslash).
 An Escape sequences always begin with \ (backslash) and is followed by one
character.
 An Escape sequences are mostly used in printf() statement.

Escape Sequences Table


There are 12 escape sequences in C Programming. They are
Escape Sequence Use ASCII Value

\n New Line 010

\t Horizontal tab 009

\b Backspace 008

\r Carriage Return 013

\a Alert Bell 007

\' Single quote 039

\" Double quote 034

\? Question 063

\\ Backslash 092

\f Form feed 012


Escape Sequence Use ASCII Value

\v Vertical tab 011

\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

This will make a bell sound


Note:
\a will audio you a bell sound 🔔.
\' Escape Sequence
singlequote.c
#include <stdio.h>
int main()
{
printf("\'Hello Programmer\' ");
return 0;
}

Output
'Hello Programmer'
Note:
\' will print single quote '.

\" Escape Sequence


doublequote.c
#include <stdio.h>
int main()
{
printf("\"Hello Programmer\" ");
return 0;
}

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:

 In C Programming punctuation, individual words, characters etc are


called tokens.
 Tokens are basic building blocks of C Programming
We have learnt different type of tokens in C. In the upcoming chapters we will learn C
tokens, keywords and identifiers in more details.
o Token Type Example 1 Example 2

1 Keyword int for

2 Constants height sum

3 Identifier -443 43

4 String "Hello" "atnyla"

5 Special Symbol * @

6 Operators * ++

Token Meaning

Keyword A variable is a meaningful name of data storage location in computer


memory. When using a variable you refer to memory address of computer

Constant Constants are expressions with a fixed value

Identifier The term identifier is usually used for variable names

String Sequence of characters


Token Meaning

Special Symbols other than the Alphabets and Digits and white-spaces
Symbol

Operators A symbol that represents a specific mathematical or non-mathematical


action

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
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:

auto Double Int struct

break Else Long switch

case Enum Register typedef

char Extern Return union

const Float Short unsigned

continue For Signed void

default goto Sizeof volatile

do if Static while

Keywords are those words which tells the compiler what to do .


Keywords Rules
 Keywords are always in lowercase letters.
 Keywords cannot be changed by a programmer.
 Keywords cannot be used as variable name, function name, array name by a programmer.

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

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.

Rules for naming identifiers


1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
2. The first letter of an identifier should be either a letter or an underscore. Use of underscore as the
first character must be avoided as several compiler defined identifiers in the standard C library
have underscores as their first characters.
3. You cannot use keywords like int, while etc. as identifiers.
4. the identifier is longer than 31 characters.
5. There cannot be 2 successive underscores
6. The case of alphabetic characters that form the identifier name is significant. For example,
‘FIRST’ is different from ‘first’ and ‘First’.

Valid identifiers: total, sum, average, x, y, mark_1, x1, roll_number, r, R, sumOfRoots1and2,


_XYZ, maxThrowsPerTurn, TURNS_PER_GAME, R2D2, root1

Examples of invalid identifiers:


hotToHandle // does not start with a letter
Net Pay // contains a space
ALPHA;BETA // contains an invalid character

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

DIFFERENCE BETWEEN IDENTIFIERS AND KEYWORDS


Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It must be written in a lowercase letter. It can be written in both lowercase and


uppercase letters.

Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.

It is a combination of alphabetical characters. It is a combination of alphanumeric characters.

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

Numeric and non numeric

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 types

Size range Format


Type
(bytes) Specifier

Char or signed char 1 -128 to 128 %c

Unsigned char 1 0 to 255 %c

Int or signed int 2 -32768 to +32767 %i or %d

Unsigned int 2 0 to 65535 %u

short int or unsigned -32768 to +32767


2 %hd
short int

long int or signed -2147483648 to 2147483647 %ld or


4
long int %li

unsigned long int 4 0 to 4,294,967,295 %lu

Float 4 3.4E-38 to 3.4E+38 %f or %g


Double 8 -1.7E-308 to 1.7E+308 %lf

long double 10 -3.4e-4932 to 1.1e+4932 %lf

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:

SPECIFIER USED FOR

%c a single character

%s a string

%hi short (signed)

%hu short (unsigned)

%Lf long double

%n prints nothing

%d a decimal integer (assumes base 10)

%i a decimal integer (detects the base automatically)

%o an octal (base 8) integer

%x a hexadecimal (base 16) integer

%p an address (or pointer)

%f a floating point number for floats

%u int unsigned decimal

%e a floating point number in scientific notation

%E a floating point number in scientific notation

%% 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

%s string format specifier:


#include <stdio.h>
int main()
{
char str[] = "freeCodeCamp";
printf("%s\n", str);
return 0;
}
Output:
freeCodeCamp

Character input with the %c format specifier:


#include <stdio.h>
int main() {
char user_ch;
scanf("%c", &user_ch); // user inputs Y
printf("%c\n", user_ch);
return 0;
}
Output:
Y

String input with the %s format specifier:


#include <stdio.h>
int main()
{
char user_str[20];
scanf("%s", user_str); // user inputs fCC
printf("%s\n", user_str);
return 0;
}
Output:
fCC

%d and %i decimal integer format specifiers:


#include <stdio.h>
int main() {
int found = 2015, curr = 2020;
printf("%d\n", found);
printf("%i\n", curr);
return 0;
}
Output:
2015
2020

%f and %e floating point number format specifiers:


#include <stdio.h>
int main() {
float num = 19.99;
printf("%f\n", num);
printf("%e\n", num);
return 0;
}
Output:
19.990000
1.999000e+01

%o octal integer format specifier:


#include <stdio.h>
int main() {
int num = 31;
printf("%o\n", num);
return 0;
}
Output:
37

%x hexadecimal integer format specifier:


#include <stdio.h>
int main() {
int c = 28;
printf("%x\n", c);
return 0;
}
Output:
1c
%c single character format specifier:
#include <stdio.h>
int main() {
char first_ch = 'f';
printf("%c\n", first_ch);
return 0;
}
Output:
f

%s string format specifier:


#include <stdio.h>
int main() {
char str[] = "freeCodeCamp";
printf("%s\n", str);
return 0;
}
Output:

Character input with the %c format specifier:


#include <stdio.h>
int main() {
char user_ch;
scanf("%c", &user_ch); // user inputs Y
printf("%c\n", user_ch);
return 0;
}
Output:
Y

String input with the %s format specifier:


#include <stdio.h>
int main() {
char user_str[20];
scanf("%s", user_str); // user inputs fCC
printf("%s\n", user_str);
return 0;
}
Output:
fCC

%d and %i decimal integer format specifiers:


#include <stdio.h>
int main() {
int found = 2015, curr = 2020;
printf("%d\n", found);
printf("%i\n", curr);
return 0;
}
Output:
2015
2020

%f and %e floating point number format specifiers:


#include <stdio.h>
int main() {
float num = 19.99;
printf("%f\n", num);
printf("%e\n", num);
return 0;
}
Output:
19.990000
1.999000e+01

%o octal integer format specifier:


#include <stdio.h>
int main() {
int num = 31;
printf("%o\n", num);
return 0;
}
Output:
37

%x hexadecimal integer format specifier:


#include <stdio.h>
int main() {
int c = 28;
printf("%x\n", c);
return 0;
}
Output:

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 () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello

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.

Example, "Welcome to the world of programming!"

How to Declare and Initialize a String in C

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 general syntax for declaring a variable as a String in C is as follows,

char string_variable_name [array_size];

The classic Declaration of strings can be done as follow:

char string_name[string_length] = "string";


The size of an array must be defined while declaring a C String variable because it is used to calculate
how many characters are going to be stored inside the string variable in C. Some valid examples of
string declaration are as follows,

char first_name[15]; //declaration of a string variable


char last_name[15];

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,

char first_name[15] = "ANTHONY";


char first_name[15] = {'A','N','T','H','O','N','Y','\0'}; // NULL character '\0' is required at end in this dec
laration
char string1 [6] = "hello";/* string size = 'h'+'e'+'l'+'l'+'o'+"NULL" = 6 */
char string2 [ ] = "world"; /* string size = 'w'+'o'+'r'+'l'+'d'+"NULL" = 6 */
char string3[6] = {'h', 'e', 'l', 'l', 'o', '\0'} ; /*Declaration as set of characters ,Size 6*/

String Input: Read a String

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:

Enter your first name and age:


John_Smith 48

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:

Enter your full name: Dennis Ritchie


My full name is Dennis Ritchie

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:

Enter your name plz: Carlos


My name is Carlos

The fgets() arguments are :

 the string name,


 the number of characters to read,
 stdin means to read from the standard input which is the keyboard.

String Output: Print/Display a String

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);

String output is done with the fputs() and printf() functions.


#include <stdio.h>
int main() {
char str[50];
printf("Enter a string : ");
gets(str);
printf("You entered: %s", str);
return 0;
}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

INPUT AND OUTPUT STATEMENTS IN C- printf() and scanf()


C language supports two formatting functions printf() and scanf(). Printf() is used to convert data
stored in the program into a text stream for output to the monitor and scanf() is used to convert the text
stream coming from keyboard to data values and stores them in program variables.
A program that uses standard input/output functions must contain the statement #include<stdio.h>

printf()

The syntax for printf() function can be given as

printf (‘control string’, variable list);

 The function accepts two parameters---control string and variable list.


 In some printf() statements you may find only a text string that has to be displayed on screen.
ex- printf(“welcome”);
 The control characters can also be included in the prinf() statement. These control characters
include /n, /t, /r, /a, etc.
 After the control string, the function can have as many additional arguments as specified in
the control string.
 The parameter control string in the printf() function is nothing but C string that
contains the text that has to be written on to the standard output device.

The general form of printf statement is


printf(“control string”, arg1, arg2,….argn);
 The arguments arg1, arg2, ….., argn are the variabels whose values are formatted and printed
according to the specifications of control string.
 The arguments should match in number, order and type with the format specifications.

A simple format specification has the following form.

%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()

%c For single character


%d For integer values
For floating point number
%f
%E, %e Floating point number in exponential format
%o Octal number
%X,%oX Hexadecimal number
Unsigned integer values
%u

Look at the website : https://www.javatpoint.com/c-format-specifier

Some examples of formatted printf staatment are

Printf(“ x = %d”, x)

Output of integer numbers

The format specification for printing an integer number is :


%wd
 Where w specifies the minimum field width for the output.
 However if the number is greater than the specified field, it will be printed in full, overriding
the minimum specification d specifies that the value to be printed is an integer.
 The number is written right-justified in the given field width. Leading blanks will appear as
necessary.

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

Output of real numbers


%w.p f

 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

Printing of single character


A single character can be displayed in a desired position using the format %wc
 The character will be displayed right-justified in the field of w columns.
 We can make left-justified by placing a minus sign before the integer w.
 The default value for w is 1.

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.

control string contains field specification, include


 Field specifications, consist of conversion character %, a data type character and optional
number which specifies field width
 Blanks, tabs or newlines.

Inputing integer numbers


The field specification for reading an integer number is : %wd
 The percentage sign % indicates that a conversion specification follows:
 w is an integer number that specifies the field width of the number to be read and
 d, known as the data character, indicates that the number to be read is in integer mode.

Consider the following example.
scanf(%2d %5d”, &num1, &num2);
Data line: 50 31426
the value 50 is assigned to num1 and 31426 to num2.
 Suppose the input data is as follows : 31426 50 then the variable num1 will be assigned
31(because of %2d) and num2 will be assigned 426. The value 50 that is unread will be
assigned to the first variable in the next scanf call.
That is the statement
Suppose the input data is as follows: 31426 50
Scanf(“%d %d”, &num1, &num2) will read data 31426 50 and assigns num1=31426 and num2=50.
an input field may be skipped by specifying * in the place of field width. For example the
statement
Scanf(“%d %*d %d”, &a, &b) will assign the data 123 456 789 as follows:
123 to a , 456 skipped, 789 to b.
The data type characer d may be preceded by “l” to read long integer and h to read short integers.
#include<stdio.h>
void main()
{
int a,b,c,x,y,z;
int p,q,r;
printf("enter 3 integer numbers \n");
scanf("%d %d %d",&a,&b,&c);
printf("%d %d %d \n\n", a,b,c);
printf("Enter two 4-digit numbers\n");
scanf("%4d %4d", &x, &y);
printf("%d %d", x, y);
printf("\n enter two integers\n");
scanf("%d %d", &a,&x);
printf("%d %d\n\n",a,x);
printf("enter a ten digit number \n");
scanf("%3d%4d%3d",&p,&q,&r);
printf("%d %d %d\n\n",p,q,r);}

Output
enter 3 integer numbers
34 56 78
34 56 78

Enter two 4-digit numbers


1234 5678
1234 5678
enter two integers
12 45
12 45

enter a ten digit number


1234567890
123 4567 890

Inputing real numbers


scanf reads real number using the simple specifiation %f for both the notations, namely decimal point
notation and exponential notation.
For example the statement
Scanf(“%f %f %f “, &x,&y, &z);
With the input data : 475.89 43.21E-1 678
Will assign the value 475.89 to x, 4.321 to y and 678.0 to z. A number may be skipped using %*f
specification.
Example
float salary;
Scanf(“%f”, $salary);
Printf(“.2%f”,salary);

Inputting character strings


We have seen how a single characer can be read from the terminal using getchar function. The same
can be achieved using scanf() function alsos. The scanf fucntion can input strings containing more than
one character.
The specification is %ws or %wc.
Program
#include<stdio.h>
main()
{
int no;
char name[15];
printf("enter serial number and name one\n");
scanf("%d %15s",&no,name);
printf("%d %15s \n\n", no, name);
}

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

3x2 +2x + 1 3*x*x+2*x+1

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

Example of evaluation statements are

x=a*b–c
y=b/c*a
z = a – b / c + d;

The following program illustrates the effect of presence of parenthesis in expressions.

#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 + -

Rules for evaluation of expression


• First parenthesized sub expression left to right are evaluated.
• If parenthesis are nested, the evaluation begins with the innermost sub expression.
• The precedence rule is applied in determining the order of application of operators in evaluating sub
expressions.
• The associability rule is applied when two or more operators of the same precedence level appear in
the sub expression.
• Arithmetic expressions are evaluated from left to right using the rules of precedence.
• When Parenthesis are used, the expressions within parenthesis assume highest 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 −

 Inside a function or a block which is called local variables.


 Outside of all functions which is called global variables.
 In the definition of function parameters which are called formal parameters.

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;
}

/* function to add two integers */


int sum(int a, int b) {

printf ("value of a in sum() = %d\n", a);


printf ("value of b in sum() = %d\n", b);
return a + b;
}

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.

 Automatic variables are allocated memory automatically at runtime.


 The visibility of the automatic variables is limited to the block in which they are defined.
 The scope of the automatic variables is limited to the block in which they are defined.
 The automatic variables are initialized to garbage by default.
 The memory assigned to automatic variables gets freed upon exiting from the block.
 The keyword used for defining automatic variables is auto.
 Every local variable is automatic in C by default.

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:

garbage garbage garbage

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.

Example : Static Variable


#include <stdio.h>
void display();

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

What Is Comma Operator?


The comma operator is used to separate two or more expression. Where first expression1 is
evaluated, then expression2 is evaluated, and the value of expression2 is returned for the
whole expression.

comma.c

#include <stdio.h> //header file section


int main() //main section
{
int a=5, b=10;
if(a>b,a<b)
printf("if condition executes");
else
printf("else condition executes");
return 0;
}
 if condition executes
Note:
In the above program if condition checks only the right most codition as comma
operator sperates two conditions.

Comma Operator Priority


Comma operator has the lowest priority among all the operators.

Comma Operator In printf


Here is an example program where comma operator get used in printf statement.

commaprintf.c

#include <stdio.h> //header file section


int main() //main section
{
printf("Addition of 4 + 4 is %d ", 4+4);
return 0;
}
 Addition of 4 + 4 is 8
Comma Operator In scanf
Here is an example program where comma operator get used in scanf statement.

commascanf.c

#include <stdio.h> //header file section


int main() //main section
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
printf("you entered %d",num);
return 0;
}
 Enter a number: 2
 you entered 2

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.

In for loops: for (n=1, n=10, n<=m,n++, m++)

example
#include <stdio.h>
int main()
{
int x = 10;
int y = 15;

printf("%d", (x, y));


getchar();
return 0;
}

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.

Some applications of comma operator are:

In for some loops:


(n = 1, m = 10, n <=m; n++, m++)
In while loops:
while (c = getchar(), c != ‘10’)

Exchanging values :
t = x, x =y, y =t;

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

INCREMENT AND DECREMENT OPERATORS

 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 – – ;

EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C:


In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator and output
is displayed as “1 2 3 4 5 6 7 8 9”.

//Example for increment operators

#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
OUTPUT:
123456789

EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C:


In this program, value of “I” is decremented one by one from 20 up to 11 using “i–” operator and
output is displayed as “20 19 18 17 16 15 14 13 12 11”.

//Example for decrement operators

#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

DIFFERENCE BETWEEN PRE/POST INCREMENT & DECREMENT OPERATORS IN C:


Below table will explain the difference between pre/post increment and decrement operators in C
programming language.
Operator Operator/Description
value of i is incremented before assigning
Pre increment operator (++i) it to the variable i
value of i is incremented after assigning it
Post increment operator (i++) to the variable i
value of i is decremented before assigning
Pre decrement operator (–i) it to the variable i
value of i is decremented after assigning it
Post decrement operator (i–) to variable i

EXAMPLE PROGRAM FOR PRE – INCREMENT OPERATORS IN C:


C

//Example for increment operators

#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”.

EXAMPLE PROGRAM FOR POST – INCREMENT OPERATORS IN C:

#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”.

EXAMPLE PROGRAM FOR PRE –DECREMENT OPERATORS IN C:

#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”.

EXAMPLE PROGRAM FOR POST –DECREMENT OPERATORS IN C:

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

Different types of assignment operators are shown below:


 “=”: This is the simplest assignment operator. This operator is used to assign the value on the
right to the variable on the left.

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)

If initially value stored in a is 5. Then (a += 6) = 11.


 “-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the
current value of the variable on left from 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)

If initially value stored in a is 8. Then (a -= 6) = 2.


 “*=”This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies 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)
If initially value stored in a is 5. Then (a *= 6) = 30.
 “/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current
value of the variable on left by 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)

If initially value stored in a is 6. Then (a /= 2) = 3.

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);

// Assigning value by adding 10 to a


// using "+=" operator
a += 10;
printf("Value of a is %d\n", a);

// Assigning value by subtracting 10 from a


// using "-=" operator
a -= 10;
printf("Value of a is %d\n", a);

// Assigning value by multiplying 10 to a


// using "*=" operator
a *= 10;
printf("Value of a is %d\n", a);

// Assigning value by dividing 10 from a


// using "/=" operator
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 SIZEOF OPERATOR.


C provides operators that let you perform logical operations on the individual bits of integer values,
and shift the bits right or left.

The bitwise operators are:

& (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.

The following program demonstrates bitwise operators:

#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

The bitwise operators are discussed in detail in upcoming tutorials.

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

An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication,


division etc on numerical values (constants and variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* Multiplication

/ Division

% remainder after division (modulo division)

Example 1: Arithmetic Operators


// 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;
}

Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2

Remainder when a divided by b=1

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,

// Either one of the operands is a floating-point number


a/b = 2.5
a/d = 2.5
c/b = 2.5

// Both operands are integers


c/d = 2

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

Example: Assignment Operators


// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);

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.

Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators


// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

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.

Operator Meaning Example

Logical AND. True only if all If c = 5 and d = 2 then, expression


&&
operands are true ((c==5) && (d>5)) equals to 0.

Logical OR. True only if either If c = 5 and d = 2 then, expression


||
one operand is true ((c==5) || (d>5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression !(c==5)


!
operand is 0 equals to 0.

Example : Logical Operators


// Working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", 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

Explanation of logical operator program


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

THE SIZEOF OPERATOR


The sizeof operator is the most common operator in C. It is a compile-time unary operator and used to
compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float
type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of
memory allocated to that data type. The output can be different on different machines like a 32-bit
system can show different output while a 64-bit system can show different of same data types.

Example: sizeof Operator


#include <stdio.h>
int main() {
int a = 16;
printf("Size of variable a : %d\n",sizeof(a));
printf("Size of int data type : %d\n",sizeof(int));
printf("Size of char data type : %d\n",sizeof(char));
printf("Size of float data type : %d\n",sizeof(float));
printf("Size of double data type : %d\n",sizeof(double));
return 0;
}
Output
Size of variable a : 4
Size of int data type : 4
Size of char data type : 1
Size of float data type : 4
Size of double data type : 8
When the sizeof() is used with an expression, it returns the size of the expression. Here is an example.

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.

Syntax of a conditional operator


1. Expression1? expression2: expression3;

The pictorial representation of the above syntax is shown below:

Meaning of the above syntax.


o In the above syntax, the expression1 is a Boolean condition that can be either true or false
value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.

Let's understand the ternary or conditional operator through an example.


#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional oper
ator
return 0;
}

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.

Let's understand this scenario through an example.


#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}
In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to the 'a' variable.
After the declaration, we are assigning value to the 'b' variable by using the conditional operator. If the
value of 'a' is equal to 5 then 'b' is assigned with a 3 value otherwise 2.

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");

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

You might also like