Module 1 & 2
Module 1 & 2
MODULE – I
Introduction to Programming, Algorithms and Flowcharts: Programs and
Programming, Programming languages, Compiler, Interpreter, Structured
Programming Concept, Algorithms, Flowcharts, How to Develop a Program.
Fundamental Algorithms: Exchanging the values of Two Variables, Counting,
Summation of a set of numbers, Factorial computation, Generation of the Fibonacci
Sequence, Reversing the digits of an integer.
Introduction : C language is one of structured programming languages. It was developed by Dennis
Ritchie at AT&T Bell laboratories, U.S.A in 1972. It is derived from the language BCPL (Basic Combine
Programming Language).
‘C’ language is called middle level language because ‘C’ supports both low-level language and
high-level language features. Through low-level features, C language is used for memory management,
bit manipulations and direct memory access using pointers. The high-level language features are
conditional statements, functions and files that are used for general purpose.
Features of C language:
1. General Programming Language: It is a general purpose programming language. Hence, it is used
for writing system and application programs.
2. Maintainability: It is reliable, simple and easy to use.
3. System Programming: C language is used to develop compilers, operating systems and other utility
programs for system software.
4. Portability: C language is highly portable language i.e. a C program written on one computer can be
compiled and executed on a different computer.
5. Structured Programming Language: It supports many control structures such as “if, switch, while,
do…while, for” etc. to develop well defined and easy to maintain programs.
6. Modularity: Through modularisation, we can break down a large program into small modules called
functions.
7. Limited Keywords: It has only 32 keywords and hence several standard functions are available with
‘C’ are used for developing error free programs.
1
NARN/ MCA / MODULE – I & II / C PROGRAMMING
A computer does not understand symbolic language; it must be translated to machine. A special
program called an Assembler translates symbolic code into machine language, they known as
Assembly Languages. These languages were also machine dependent.
3. High-level Languages:
High-level languages are portable to many different computers, and allow the programmer to
concentrate on problem rather than hardware of the computer.
High-level languages must be converted to machine language. The process of converting is
known as Compilation.
Some of the most widely used high-level languages are Fortran, Pascal, Cobol, C, C++ and etc.
A compiler or interpreter is itself a computer program. It accepts a program written in a high-level
language (e.g., C) as input, and generates a corresponding machine-language program as output.
The original high-level program is called the source program, and the resulting machine-language
program is called the object program. Every computer must have its own compiler or interpreter
for a particular high-level language.
Compiler: A compiler is a special type of program that transforms the source code written in a
programming language (the source language)in to the machine language , which uses only two digits 0
and 1(the target language). The resultant code is 0s and 1s is known as the object code. The object code is
used to create an executable program.
Therefore , a compiler is used to translate the source code from a high-level programming
language to a lower level language(e.g., assembly language or machine code). The work of a
compiler is only to translate human readable source code in to computer-executable machine
code.
Interpreter: like the compiler , the interpreter also executes instructions written in a high-level
language. Basically, a program written in a high-level language can be executed in any of the two ways-
by compiling the program or by passing the program through an interpreter.
2
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Algorithms: An algorithm is defined as a finite set of steps that provide a chain of actions for solving a
problem. Algorithm is a step-by-step method of solving a problem.
Characteristics of an Algorithm:
1) Finiteness: - An algorithm terminates after a finite numbers of steps.
2) Definiteness: - Each step in algorithm is unambiguous. This means that the action specified by the step
cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any
confusion.
3) Input: - An algorithm accepts zero or more inputs
4) Output:- An algorithm should produce at least one output.
5) Effectiveness: - It consists of basic instructions that are realizable. This means that the instructions can
be performed by using the given inputs in a finite amount of time.
Advantages of Algorithms:
1. It is a step-wise representation of a solution to a given problem, which makes it easy to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for anyone even without
programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps hence, it is easier for
programmer to convert it into an actual program.
Disdvantages of Algorithms:
1. Alogorithm is Time consuming.
2. Difficult to show Branching and Looping in Algorithms.
3. Big tasks are difficult to put in Algorithms.
Qualities of a good algorithm: The following are the primary factors that are often used to judge the
quality of an algorithm.
Time: The lesser is the time required to execute a program better is the algorithm
Memory: Computer takes some amount of memory to storage to execute a program. The lesser is the
memory required the better is the algorithm
Accuracy: Algorithms which provide the accurate results to a given problem should be chosen.
Sequence: The procedure of an algorithm must form in a sequence
Generability: The designed algorithm must solve the problem for a different range of input data.
Categories of Algorithm: The steps in an algorithm can be divided into three categories, namely
Sequence
Selection and
Iteration
3
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Sequence: The steps described in an algorithm are performed successively one by one without skipping
any step.
The sequence of steps defined in an algorithm should be simple and easy to understand.
Each instruction of such an algorithm is executed, because no selection procedure or conditional
branching exists in a sequence algorithm.
Example:
// adding two timings
Step 1: start
Step 2: read h1, m1, h2, m2
Step 3: m=m1+m2
Step 4: h= h1 + h2 + m/60
Step 5: m=m mod 60
Step 6: write him
Step 7: stop
Selection
We understand that the algorithms written in sequence fashion are not reliable. There must be a
procedure to handle operation failure occurring during execution.
The selection of statements can be shown as follows
if(condition)
Statement-1;
else
Statement-2;
The above syntax specifies that if the condition is true , statement-1 will be executed otherwise
statement-2 will be executed.
In case the operation is unsuccessful. Then sequence of algorithm should be changed/ corrected in
such a way that the system will re-execute until the operation is successful.
Example:
// Person eligibility for vote
Step 1 : start
Step 2 : read age
Step 3 : if age > = 18 then step_4 else step_5
Step 4 : write “person is eligible for vote”
Step 5 : write “ person is not eligible for vote”
Step 6 : stop
Multi-way:
For a single problem, three may be multiple solutions. In such a situation we have to apply multi way
(switch case) decision statements or we can extend two-way statements (example, if else) in a ladder
form.
Example:
// Roots of a quadratic Equation
Step 1 : start
Step 2 : read a,b,c
Step 3 : if (a= 0) then step 4 else step 5
Step 4 : Write “ Given equation is a linear equation “
Step 5 : d=(b * b) _ (4 *a *c)
Step 6 : if ( d>0) then step 7 else step8
Step 7 : Write “ Roots are real and Distinct”
Step 8: if(d=0) then step 9 else step 10
Step 9: Write “Roots are real and equal”
Step 10: Write “ Roots are Imaginary”
Step 11: stop
Iteration
In a program, sometimes it is very necessary to perform the same action for a number of times.
4
NARN/ MCA / MODULE – I & II / C PROGRAMMING
If the same statement is written repetitively, it will increase the program code.
To avoid this problem, iteration mechanism is applied.
The statement written in an iteration block is executed for a given number of times based on certain
condition.
Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat step 4 until n>0
Step 4 : (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop
Flow charts:
A flowchart is a pictorial representation of an algorithm. It shows the flow of operation in pictorial form
and any error in the logic of the problem can be detected very easily. A flowchart uses different boxes
and symbols to denote different types of instructions. These symbols are connected by solid lines with
arrow marks to indicate the operation flow. Normally an algorithm is represented in the form of a
flowchart and the flowchart is then expressed in some programming language to prepare a computer
program.
Flow chart symbols: A few symbols are needed to indicate the necessary operations in flowcharts.
These symbols have been standardized by the American National Standard Institute (ANSI).These
symbols are
1.Terminal: The terminal (oval)symbol as the name implies is used to indicate the
beginning(start), ending(stop) and pause in the logic flow. It is the first and last symbol
in the programming logic.
2. Input/output:
The input/output (parallelogram) symbol is used to denote any function of an
input/output device in the program. All input/output instructions in the program are
indicated with this symbol.
3. Processing: A processing(rectangle) symbol is used in a flowchart to represent
arithmetic and data movement instructions. Thus all arithmetic processes of addition
,subtraction, multiplication etc
4. Flow lines: Flow lines with arrow heads are used to indicate the flow of operations i.e. the exact
sequence in which the instructions are to be executed. The normal flow of flowchart is
from top to bottom and left to right.
5. Decision: The decision (diamond) symbol is used in a flowchart to indicate a point at
which a decision has to be made and a branch to one of two or more alternate points is
possible.
Connectors: If a flowchart becomes very long the flow chart starts criss crossing at many
places that causes confusion and reduces understandability of the flowchart. Moreover there
are instances when a flowchart becomes too long to fit in a single page and the use of flow
lines become impossible. A connector symbol is represented by a circle. A pair of identically labeled
connector symbols is commonly used to indicate a continued flow when the use of a line is confusing. So
two connectors with identical labels can be used.
Predefined process: The predefined process(double sided rectangle) symbol is used in
flowcharts to indicate that modules or subroutines are specified elsewhere. Annotation:
The annotation (bracket with broken line) symbol is used in flowcharts to indicate the
descriptive comments or explanation of the instruction.
5
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Return:nothing
Step 1:start
Step 2:read two integer numbers
Step 3:perform of sum of 2 numbers
Step 4:display the sum:
Step 5:stop
Ex2:Alogrithm to find sum of three integer numbers
Algorithm addition( )
Process:sum of three integers
Pre: read three integer values
Post:addition of three values
Return:nothing
Step 1 :start
Step2:read the three integers
Step 3:peform addition three values
Step 4: display the sum
Step 5: stop
Ex3:Algorithm to find sum of three floating point numbers
Algorithm floatsum( )
Process:addition of three floating point numbers
Pre: read three floating point numbers
Post:addition of three floating point numbers
Return:nothing
Step 1:start
Step 2:read three floating point numbers
Step 3:perform addition of three floating point values
Step 4:display the sum
Step 5:stop
Ex4:Algorithm to find average of two numbers
Algorithm average( )
Process: average of two numbers
Pre: read two values
Post :average of two values
Return:nothing
Step 1:start
Step2:read first number
Step 3: read second number
Step 4:perform sum of two numbers
Step 5:divide sum with 2
Step 6:print the average
Step 7:stop
Selection: Algorithm to find gretest among two numbers
Algorithm greatest( )
Process: greatest among two numbers
Pre: read two values
Post :large value among two
Return :nothing
Step 1:start
Step 2:read two numbers
Step 3:compare two values(ex a and b)
Step 4:if a is greater than b display a is greater otherwise b is greater
Step 5:stop
Iterative: Algorithm to find sum of n numbers
Algorithm sumofnnumbers( )
Process: cacluate sum of n numbers
Pre: read n numbers
Post: sum of n numbers
6
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Return:nothing
Step 1:start
Step 2:read numbers upto n(suppose if n=10 read 10 numbers)
Step 3: perform the addition
Step 4:repeat step 2 and step 3 upto n numbers addition
Step 5:display the result
Step 6:stop
Examples on flowcharts and algorithms:
1.Write an algorithm for finding the average of three numbers and draw the flowchart for the
same.
Step 1: read the value
Read a,b and c
Step2:compute sum=a+b+c
Avg=sum/3
Step 3:print avg
Step 4:stop
Example 2.Write an algorithm for finding greatest among two numbers
Step 1:start
Step 2:read two numbers
Step 3:compare two values(ex a and b)
Step 4:if a is greater than b display F
a is greater otherwise b is greater
Step 5:stop
Example 3: write an algorithm and flowchart for finding the sum of n numbers
Step 1:start
Step 2:read numbers upto n
Initialize count =1 sum=0
Step 3:repeat through count<=n
Step 4: x=1 sum=sum+x
Count=count+1
Step 5:print sum
Step 6:stop
7
NARN/ MCA / MODULE – I & II / C PROGRAMMING
1. Algorithm for exchanging the values of given two variables:
Algorithm 1: using a third variable
Step 1 : Start
Start 2 : READ num1, num2
Start 3 : temp = num1
Start 4 : num1 = num2
Start 5 : num2 = temp
Start 6 : PRINT num1, num2
Start 7 : Stop
Program:
/* Exchange the values of two variables */
#include<stdio.h>
#include<conio.h>
int main()
{
int first, second, temp;
clrscr();
printf("Enter first number: ");
scanf("%d", &first);
printf("Enter second number: ");
scanf("%d", &second);
temp = first;
first = second;
second = temp;
printf("\nAfter swapping, firstNumber = %d\n", first);
printf("\nAfter swapping, secondNumber = %d\n", second);
return(0);
}
2. Algorithm for counting the number of digits in an integer:
Step 1 : Start
Step 2 : Initialize ‘n’ as integer variable and ‘count’ as 0
Step 3 : READ ‘n’ value
Step 4 : check the condition (n!=0)
Step 4.1 : update n=n/10
Step 4.2 : increment count by 1(count++)
Step 5 : PRINT ‘count’ value
Step 6 : Stop
Program:
8
NARN/ MCA / MODULE – I & II / C PROGRAMMING
/* counting the number of digits */
#include<stdio.h>
#include<conio.h>
int main()
{
int n,count=0;
clrscr();
printf("Enter the number: ");
scanf("%d", &n);
while(n!=0)
{
n=n/10;
count=count+1;
}
printf("\n Number of digits = %d ", count);
return(0);
}
9
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Step 4: Read the ‘n’ value
Step 5: Check for(i=1;i<=n,i++)
Step5.1: Assign ‘f’ as f*i
Step 6: Display the factorial value ‘f’
Step 7: Stop
Program:
/* To find factorial of the given number */
#include <stdio.h>
#include <conio.h>
int main()
{
int n,i,f=1;
clrscr();
printf("\n Enter the number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n The factorial of %d is %d",n,f);
return(0);
5. Algorithm for generation of the Fibonacci sequence to the first ‘n’ terms:
Step 1: Start
Step 2: Declare i, n, f, f1, f2 as integer variables
Step 3: Read the ‘n’ value
Step 4: Initialize ‘f’ as 0 and ‘f1’ as 1
Step 5: Display ‘f’ and ‘f1’ values
Step 6: Check for(i=1;i<=n-2;i++)
Step 6.1: Find ‘f2’ as f+f1
Step 6.2: Display the value of ‘f2’
Step6.3: Assign ‘f’ as ‘f1’
Step 6.4: Assign ‘f1’ as ‘f2’
Step7: Stop
Program:
/ * c program to generate the first n terms of the fibonacci sequence */
#include<stdio.h>
void main()
{
int i,n,f,f1,f2;
clrscr();
printf("Enter Number of Fibonacci Values Needed : ");
scanf("%d",&n);
f=0;
f1=1;
printf(“%d\n%d\n”,f,f1);
for(i=1;i<=n-2;i++)
{
10
NARN/ MCA / MODULE – I & II / C PROGRAMMING
f2=f+f1;
printf(“%d\n”,f2);
f=f1;
f1=f2;
}
getch();
}
Step 1: Start
Step 2: Declare n, rev, rem as integer variables
Step 3: Initialize rev as zero
Step 4: Read ‘n’ value
Step 5: Check while (n!=0)
Step 5.1: rem=n%10
Step 5.2: rev=rev*10+rem
Step 5.3: n=n/10
Step 6: Display ‘rev’ value as output
Step 7: Stop
}
Program:
/* Reverse the digits of an given integer */
#include <stdio.h>
#include <conio.h>
int main()
{
int n, rev = 0, rem;
clrscr();
printf("\nEnter an integer: ");
scanf("%d", &n);
while (n != 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n=n/10;
}
printf("\n The Reversed number of %d = %d",n,rev);
return(0);
}
How to develop a program: When we want to develop a program by using any programming
language, we have to follow a sequence of steps. These steps are called phases in program development.
The program development life cycle is a set of steps or phases which are used to develop a
program in any programming language.
Phases of program development
Program development life cycle contains 6 phases, which are as follows −
Problem Definition.
Problem Analysis.
Algorithm Development.
Coding & Documentation.
Testing & Debugging.
Maintenance.
12
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Problem Definition: In this phase, we need to understand what the problem statement is, what our
requirement is and what the output of the problem solution is.
Problem Analysis: Here, we determine the requirements like variables, functions, etc. to solve the
problem. It means that we gather the required resources to solve the problem, which are defined in the
problem definition phase.
Algorithm Development: Here, we develop a step-by-step procedure that is used to solve the problem
by using the specification given in the previous phase.
Coding & Documentation: Here, we use a programming language to write or implement the actual
programming instructions for the steps defined in the previous phase. We write the program to solve the
given problem by using the programming languages like C, C++, Java, etc.
Testing & Debugging: Here we try to test the program whether it is solving the problem for various
input data values or not. We also test if it is providing the desired output or not.
Maintenance: In this phase, we make the enhancements. If the user gets any problem or wants any
enhancement, then we need to repeat all these phases from the starting, so that the encountered problem
is solved or enhancement is added.
These six phases are depicted in the diagram given below –
13
NARN/ MCA / MODULE – I & II / C PROGRAMMING
MODULE – 2 Basic Elements of C
Basics of C: Introduction, Character Set, Structure of a C Program, A Simple C Program,
Variables, Data Types and Sizes, Declaration, how does The Computer Store Data in
Memory, Identifiers, Keywords, Constants, Assignment, and Initialization.
Operators and Expressions: Arithmetic Operators, Relational Operators, Logical
Operators, Bitwise Operators, Conditional Operator, Comma operator, sizeof operator,
Expressions, L values and R values, Expression Evaluation- Precedence and
Associativity, Type Conversion.
‘C’ TOKENS
The ‘C’ tokens are basic elements of a program that understood by compiler. The following are
the elements of a ‘C’ program.
1. C character set
2. Keywords (Reserved Words)
3. Identifiers (User-defined Words)
4. Constants
5. Operators
1. 'C' character Set:
A character represents any alphabet, digit and symbol used to indicate the information. The
following table shows valid alphabets, digits and symbols allowed in C language.
14
NARN/ MCA / MODULE – I & II / C PROGRAMMING
2. Keywords: A keyword is a sequence of characters that has pre-defined meaning. It is also known as
reserved or pre-defined word. There are 32 keywords used in ‘C’ language. The keywords must be used
only for their specified purpose. The following are the list of keywords:
Auto break Case Char const continue default do
double else Enum Extern float for goto if
Int long Register Return short signed sizeof static
Struct switch Typedef Union unsigned void volatile while
3. Identifiers:
An identifier is a name given to a program element such as variables, constants, function names,
array names and so on. An identifier is also called user-defined word.
15
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Structure of a c program:
Every C program consists of one or more modules called functions. One of the functions must be
called main. The program will always begin by executing the main function, which may access other
functions. Any other function definitions must be defined separately, either before or after main.
A C program may contain one or more sections as given below.
The Documentation section consists a set of comment lines that gives the name of the program,
author and other details. The comments must be enclosed within the pair /* ………. */
The Link Section provides instructions to the compiler to link functions from the system library.
The Definition section defines all symbolic constants.
The Global Declaration section contains the variables such as global, to be used in more than one
function.
Every program have one main( ) section, it contains two parts, Declaration part and Executable part.
The declaration part declares all the variables used in the executable part. There is at least one
executable part in the program. These two parts must appear between the opening { and closing }
braces.
The subprogram section contains all the user-defined functions that are called in the main function.
Documentation Section
Link Section
Definition Section
Global Declaration Section
main( )
{
Declaration Part
Executable Part
}
Subprogram Section
Function1
Function2
…… …..
Function n
A Simple C Program:
Below are few commands and syntax used in C programming to write a simple C program. Let’s
see all the sections of a simple C program line by line.
int main() This is the main function from where execution of any C program begins.
whatever is given inside the command “/* */” in any C program, won’t be
/*_some_comments_*/ considered for compilation and execution.
printf(“Hello_World! “); printf command prints the output onto the screen.
getch(); This command waits for any character input from keyboard.
16
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Below C program is a very simple and basic program in C programming language. This C
program displays “Hello World!” in the output window. And, all syntax and commands in C
programming are case sensitive. Also, each statement should be ended with semicolon (;) which is a
statement terminator.
1 #include <stdio.h>
2 int main()
3{
4 /* Our first simple C basic program */
5 printf("Hello World! ");
6 getch();
7 return 0;
8}
OUTPUT:
Hello World!
1. Create
2. Compile
3. Execute or Run
4. Get the Output
Variables:
C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
17
NARN/ MCA / MODULE – I & II / C PROGRAMMING
S.No Type Syntax Example
1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;
2 Variable initialization data_type variable_name = value; int x = 50, y = 30; char flag = ‘x’, ch=’l’;
There are two types of variables in C program They are,
1. Local variable
2. Global variable
Local variable
The scope of local variables will be within the function only.
These variables are declared within the function and can’t be accessed outside the function.
Global variable
The scope of global variables will be throughout the program. These variables can be accessed
from anywhere in the program.
This variable is defined outside the main function. So that, this variable is visible to main function
and all other sub functions.
Following table gives you details about standard integer types with its storage sizes and value ranges:
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Floating-Point Types: Following table gives you details about standard floating-point types with storage
sizes and value ranges and their precision:
Type Storage size Value range Precision
Float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
Double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
Identifiers: C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an underscore.
If the identifier is not used in the external linkage, then it is called as an internal identifier. If the identifier
is used in the external linkage, then it is called as an external identifier.
18
NARN/ MCA / MODULE – I & II / C PROGRAMMING
We can say that an identifier is a collection of alphanumeric characters that begins either with an
alphabetical character or an underscore, which are used to represent various programming elements such
as variables, functions, arrays, structures, unions, labels, etc. There are 52 alphabetical characters
(uppercase and lowercase), underscore character, and ten numerical digits (0-9) that represent the
identifiers. There is a total of 63 alphanumerical characters that represent the identifiers.
Constants:
C Constants are also like normal variables. But, only difference is, their values cannot be
modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of C constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
S.no Constant type data type Example
int 53, 762, -478 etc
unsigned int 5000u, 1000U etc
1 Integer constants
long int 483,647
long long int 2,147,483,680
float 10.456789
2 Real or Floating point constants
doule 600.123456789
3 Octal constant Int 013 /* starts with 0 */
4 Hexadecimal constant Int 0×90 /* starts with 0x */
5 character constants char ‘A’ , ‘B’, ‘C’
6 string constants char “ABCD” , “Hai”
19
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Rules for constructing C constant:
1. Integer Constants in C:
An integer constant must have at least one digit.
It must not have a decimal point.
It can either be positive or negative.
No commas or blanks are allowed within an integer constant.
If no sign precedes an integer constant, it is assumed to be positive.
The allowable range for integer constants is -32768 to 32767.
2. Real constants in C:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
3. Character and string constants in C:
A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single quotes.
The maximum length of a character constant is 1 character.
String constants are enclosed within double quotes.
4. Backslash Character Constants in C:
There are some characters which have special meaning in C language.
They should be preceded by backslash symbol to make use of special function of them.
Given below is the list of special characters and their purpose.
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\o Octal constant (N is an octal constant)
\x Hexadecimal constant (N – hex.dcml cnst)
data_type variable_name;
Variable declaration Example: int x, y, z; char flat, ch;
OPERATORS
An operator is a symbol used to perform arithmetic and logical operations. It is used to
manipulate data stored in the variables.
‘C’ language has the following types of operators.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional or Ternary operator
7. Bitwise operators
8. Special operators
1. Arithmetic operators: Arithmetic operators are used to perform arithmetic calculations. The
following are the various arithmetic operators.
Operator Meaning Example Result
+ Addition 10+3 13
– Subtraction 10-3 7
* Multiplication 10*3 30
/ Division 10/3 3
10/3.0 3.3333
% Modulo division (Remainder) 10%3 1
2. Relational Operators: The relational operators are used to compare two values and give either true
(1) or false (0) result. These are used to form simple conditions.
3. Logical Operators: These are used to combine two conditions or to negate the result of a condition.
They also give the result either true or false. They are used to form compound conditions.
21
NARN/ MCA / MODULE – I & II / C PROGRAMMING
4. Assignment Operators: The assignment operators are used to assign (store) a value to a variable. An
assignment operator always consists of a variable on left hand side and a valid expression / constant /
variable on right hand side. There are two types of assignment operators. They are
1. Simple Assignment Operator
2. Compound Assignment Operators
Simple Assignment Operator: The equal sign ‘=’ is used as simple assignment operator. The general
format of this operator is as follows:
Expression
Variable = Constant
Variable
In the above syntax, the value of Expression / Constant / Variable is assigned to the variable on the left
hand side of ‘=’ sign.
Eg: x = 35: y = a + b * c: z = y: a = b = 50:
Expression
Variable Compound Constant
operator
Variable
In the above syntax, the operator can be either +=, –=, *=, /= or %=
Example, Let a=10, then
Operator Example Meaning Final Value of ‘a’
+= a+=5 a=a+5 15
–= a–=5 a=a–5 5
*= a*=5 a=a*5 50
/= a/=5 a=a/5 2
%= a%=5 a=a%5 0
5. Increment and Decrement Operators:
Increment Operator (++):
The increment operator is a unary operator. It is used to increase the value of a variable by
1. It is used in two ways. They are pre-increment and post-increment.
Pre-increment: If the ‘++’ operator precedes the variable then it is called “Pre increment”. In this
method, the pre-increment operator increments the value of variable first and then the new value is used
in the expression.
For example: c = ++a; means a = a + 1; and then
c = a;
Post-increment: If the ‘++’ operator succeeds the variable then it is called “Post increment”. In this
method, the value of the variable is used in expression and then it is incremented.
Pre-decrement: If the ‘– –’ operator precedes the variable then it is called “Pre decrement”. In this
method, the pre-decrement operator decrements the value of variable first and then the new value is used
in the expression.
For example: c = – – a; means a = a – 1; and then
c = a;
22
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Post-decrement: If the ‘– –’ operator succeeds the variable then it is called “Post decrement”. In this
method, the value of the variable is used in expression and then it is decremented.
In the above example, if a>b then the value ‘a’ is assigned otherwise the value of ‘b’ is assigned to the
variable ‘large’.
7. Bitwise Operators:
‘C’ language has the capability of manipulating the bits (0 or 1) directly stored in the memory.
These operators perform operations on bit by bit level. They must be used only with integer or character
type of values. The operators are as follows
Operator Meaning
& Bitwise AND
¦ Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ Bitwise 1’s complement
>> Bitwise Right shift
<< Bitwise Left shift
Bitwise OR ( ¦ ) operator:
If any or all the bits are “1” then it returns “1” otherwise it returns “0”.
23
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Truth table: Example: Let x=240 and y=170 then
¦ 1 0 x : 0000000011110000
1 1 1 y : 0000000010101010
0 1 0 x ¦ y: 0000000011111010
^ 1 0 x : 0000000011110000
1 0 1 y : 0000000010101010
0 1 0 x ^ y: 0000000001011010
Comma Operator:
This operator is used to separate multiple statements. It appears in the following statements:
Variable declaration
Input and output statements
Control statements
Example:
main( )
{
int a, b, c;
clrscr( );
scanf(“%d%d”,&a,&b);
c = a, a = b, b = c;
printf(“a=%d \n”, a);
printf(“b=%d”,b);
}
25
NARN/ MCA / MODULE – I & II / C PROGRAMMING
EXPRESSIONS
Definition: An expression is a collection of operands joined together by certain operator that represent
a value. There are two types of expressions. They are
1. Arithmetic or Numeric Expression
2. Relational or Boolean Expression
Arithmetic Expression:
When an expression uses arithmetic operators then it is called arithmetic or numeric expression.
An arithmetic or numeric expression always represents numeric value.
1. Two successive operators are not permitted. However, the space(s) or parenthesis can be used to
separate two successive operators.
Example: a*-25 is invalid, a*(-25) is valid
2. Arithmetic operations cannot be implied. It means, no operator is assumed to be present.
Example: a = bc+d(x+y+z) is invalid
a = b*c+d*(x+y+z) is valid.
3. The evaluation of an arithmetic expression follows the precedence order of operators.
For example: 5+2*5 gives 15 and (5+2)*5 gives 35
4. There cannot be imbalance of parenthesis. The number of left parenthesis must be equal to the
number of right parenthesis.
5. The arithmetic operation between two integers gives integer result. It is Integer mode expression.
Example: 5/2 gives 2
6. The arithmetic operation between two float values gives float result. It is real mode expression
Example: 5.0 / 2.0 gives 2.5
7. The arithmetic operation between an integer and a float value gives float result. It is mixed mode
expression.
Example: 5 / 2.0 gives 2.5
8. The arithmetic operation can be performed between integer and character datatypes.
Example: ‘A’+30 gives 95
OPERATOR PRECEDENCE
Question: Explain about operator precedence. (or) Explain about hierarchy of operators. (or) Explain
how an expression is evaluated with examples. (or) Write about operator priority in an expression with
examples.
---
In ‘c’ language, an expression is evaluated based on the precedence order of operators. The
following table shows various operators and their precedence.
Example: x=3*2/2+3/2+2–2+3*2
=6/2+3/2+2–2+3*2
=3+3/2+2–2+3*2
=3+1+2–2+3*2
=4+2–2+6
=6–2+6
=4+6
= 10
27