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

FC Unit I & II

Fc

Uploaded by

priya vajram
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

FC Unit I & II

Fc

Uploaded by

priya vajram
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

FUNDAMENTALS OF COMPUTER PROGRAMMING

KAVERY ARTS AND SCIENCE COLLEGE - MECHERI


DEPARTMENT OF COMPUTER SCIENCE (AI & DS)

STUDY MATERIAL

PAPER NAME: FUNDAMENDALS OF COMPUTER


PROGRAMMING

CORE I
CLASS: I AI & DS

SEMESTER-I

1
FUNDAMENTALS OF COMPUTER PROGRAMMING

SYLLABUS
UNIT I: Introduction to C - Introduction to C 12 Hours Overview of C -
Introduction - Character set - C tokens - keyword & Identifiers - Constants -
Variables - Data types - Declaration of variables - Assigning values to
variables - Defining Symbolic Constants - Arithmetic, Relational, Logical,
Assignment, Conditional, Bitwise, Special, Increment and Decrement
operators - Arithmetic Expressions - Evaluation of expression - precedence
of arithmetic operators - Type conversion in expression – operator
precedence & as sociativity - Mathematical functions - Reading & Writing a
character - Formatted input and output.

UNIT II: Decision Making , Looping and Arrays-Decision Making and


Branching: Introduction – if, if….else, nesting of if …else statementselse if
ladder – The switch statement, The ?: Operator – The go to Statement.
Decision Making and Looping: Introduction- The while statement- the do
statement – the for statement-jumps in loops. Arrays – Character Arrays and
Strings

UNIT III : C++-Introduction toC++-key concept s of Object-oriented


Programming–Advantages–ObjectOriented Languages–I/O in C++- C+
+Declarations. Functions in C++-inline functions– Function Overloading.
Classesand Objects: Declaring Objects–Defining MemberFunctions– Static
Member variablesand functions–array of objects–friend functions–
Overloading member functions– Bitfields and classes –Constructor and
destructor with static members

UNIT IV: Inheritance - Operator Overloading: Overloading unary, binary


operators – Overloading Friend functions – type conversion – Inheritance:
Types of Inheritance – Single, Multilevel, Multiple, Hierarchal,
Hybrid ,Multipath inheritance –Virtual base Classes–Abstract Classes.

UNIT V: Pointers & Files - Pointers–Declaration–Pointer to Class,Object–


this pointer–Pointers to derived classes and Base classes–Arrays–
Characteristics–array of classes. Files–File stream classes–file modes–
Sequential Read/Write operations–Binary and ASCII Files –Random Access
Operation–Templates–Exception Handling– Miscellaneous functions.

2
FUNDAMENTALS OF COMPUTER PROGRAMMING

UNIT -I

UNIT I : Introduction to C - Introduction to C 12 Hours


Overview of C - Introduction - Character set - C tokens -
keyword & Identifiers - Constants - Variables - Data types -
Declaration of variables - Assigning values to variables -
Defining Symbolic Constants - Arithmetic, Relational, Logical,
Assignment, Conditional, Bitwise, Special, Increment and
Decrement operators - Arithmetic Expressions - Evaluation of
expression - precedence of arithmetic operators - Type
conversion in expression – operator precedence & as
sociativity - Mathematical functions - Reading & Writing a
character - Formatted input and output.

1.1 Introduction to C Programming


C programming is a general-purpose programming
language that was developed in the early 1970s by Dennis
Ritchie at Bell Labs as a successor to the B programming
language. Initially, C was used for developing the UNIX
operating system, which is still widely used today. Over time,
C has become a popular language for developing system-level
software, embedded systems, and other applications.
C is a compiled language, which means that the source
code is first compiled into machine code, which can then be
executed directly by the computer. This makes C programs
fast and efficient, which is one of the reasons it is still popular
today.

Introduction
Constants and Variables
C is a programming language that allows the use of
constants and variables. Constants are values that cannot be
changed during program execution, while variables are values
that can be changed during program execution. Let's know
more about them.
Constants in C:
Constants are values that are fixed and cannot be
changed during program execution. In C, constants can be of
different types, including integer, floating-point, and character
constants. We use the “const” keyword to declare constants in
C.
There are two types of constants in C:
Numeric Constants: Numeric constants represent a
fixed value and can be either integers or floating-point
numbers.

3
FUNDAMENTALS OF COMPUTER PROGRAMMING

Character Constants: Character constants represent a single character


enclosed single quotes (' ').
Syntax to declare a constant in C:
const data_type constant_name = value;
Variables in C:
Variables are values that can be changed during
program execution. In C, variables can be of different types,
including integers, floating-point numbers, characters, and
arrays.
Syntax to declare a variable in C:
Variables in C are declared using a data type keyword,
followed by the variable name.
data_type variable_name;

Variables in C can also be initialized with a value at the time of


declaration. To assign value to a variable, we use the assignment operator
(=).
data_type variable_name = value;
Data Types and Initialization
C is a programming language that supports different
data types, which are used to specify the type of data that a
variable can hold. Initialization is the process of assigning an
initial value to a variable when it is declared. Let's know more
about them.
Data Types in C:
Data types in C specify the type of data that a variable
can hold. C supports several data types, including integers,
floating-point numbers, characters, and arrays. Here we have
given a table of data types and their usage.
Datatype Usage

int Used to represent integers.

float Used to represent floating-point numbers.

char Used to represent characters.

double Used to represent double-precision floating-


point numbers.

long Used to represent long integers.

short Used to represent short integers.

unsigned Used to represent positive integers.

void Used to indicate no type.

Initialization in C:

4
FUNDAMENTALS OF COMPUTER PROGRAMMING

Initialization is the process of assigning an initial value


to a variable when it is declared. We can do initialization in
two ways. They are as follows,

Using an assignment operator:


int num = 10;
Here, we initialized the num variable with a value of 10.
Using a compound literal:
int arr[3] = {1, 2, 3};

Here, we initialized the arr variable with three values using a compound
literal.
Note: It is also possible to initialize variables with default
values. When a variable is declared without an initial value, it
is automatically initialized with a default value.
Comments and Header Files
C is a programming language that supports comments
and header files. Comments are used to add information to a
program, while header files are used to include external code
in a program. Let's know more about them.

There are two types of comments in the C programming language. They


are as follows,

Single-line comments:

Single-line comments start with two forward slashes (//) and extend to
the end of the line.
Let's see an example.

// This is a single-line comment

Multi-line comments:
Multi-line comments start with /* and end with */.
They can span multiple lines.
Let's see an example.
/*
This is a
multi-line
comment
*/

Header Files in C:
Header files in C are used to include external code in a
program. They contain function prototypes, variable
declarations, and other definitions that can be used in the
program.
To include a header file in a C program, we use the “#include”
directive.

5
FUNDAMENTALS OF COMPUTER PROGRAMMING

C provides several built-in header files, including


stdio.h, math.h, and string.h. Lets see an example of a header
file.

#include <stdio.h>
int main() {
printf("Hello, world!");
return 0;

Here is the stdio.h header file is included using the


#include directive. This allows the program to use the “printf”
function, which is defined in the “stdio.h” header file. In this
way, to use predefined functions, we need to use header files
as per our needs.

The Basic Structure of the C Program


C is a programming language that follows a specific
structure. A C program is made up of different components
that work together to produce the desired output. C
programing language also has a syntax to write code similar
to other programming languages. Let's discuss it more.
Components of a C Program
We construct a C program using different components.
The components are discussed below.
Comp Description
onent

Prepr It is used to provide instructions to the preprocessor


ocess They start with a pound sign (#) and are not terminated
or by a semicolon.
direct
ives Example: “ #include”, “#define”.

Funct A function declaration specifies the function's name


ion return type, and parameter list.
declar Function declarations are usually placed at th
ation beginning of a program.

Note: It is not required to declare functions in C, but i


is good practice to do so.

Main The main function is the entry point of a C program. I


functi is the first function that is executed when the program
on is run. The main function is required in all C programs.

Note: The main function must return an integer value.

6
FUNDAMENTALS OF COMPUTER PROGRAMMING

Funct A function definition provides the implementation of a


ion function. It specifies the function's name, return type
defini parameter list, and body.
tion
Note: Functions can be defined either before or after the
main function.
Basic Structure of a C Program:
Here, we have given an example code. Refer to this to
understand the basic structure of a C program.
// Preprocessor directive
#include <stdio.h>

// Function declaration
int add(int a, int b);

// Main function
int main() {
// Function call
int result = add(2, 3);

// Output
printf("The result is %d\n", result);

return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}

Output
The result is 5

1.2 CHARACTER SET


In the C programming language, the character set refers
to a set of all the valid characters that we can use in the
source program for forming words, expressions, and numbers.
The source character set contains all the characters
that we want to use for the source program text. On the other
hand, the execution character set consists of the set of those
characters that we might use during the execution of any
program.
Use of Character Set in C
Just like we use a set of various words, numbers,
statements, etc., in any language for communication, the C
programming language also consists of a set of various
different types of characters. These are known as the

7
FUNDAMENTALS OF COMPUTER PROGRAMMING

characters in C. They include digits, alphabets, special


symbols, etc. The C language provides support for about 256
characters.
Types of Characters in C
The C programming language provides support for the
following types of characters. In other words, these are
the valid characters that we can use in the C language:
Digits
Alphabets
Main Characters
Alphabets
The C programming language provides support for all
the alphabets that we use in the English language. Thus, in
simpler words, a C program would easily support a total of 52
different characters- 26 uppercase and 26 lowercase.
Type Descriptio Characters
of n
Cha
ract
er

Low a to z a, b, c, d, e, f, g, h, i, j, k, l, m,
erca n, o, p, q, r, s, t, u, v, w, x, y, z
se
Alph
abet
s

Upp A to Z A, B, C, D, E, F, G, H, I, J, K, L,
erca M, N, O, P, Q, R, S, T, U, V, W,
se X, Y, Z
Alph
abet
s
Digits
The C programming language provides the support for
all the digits that help in constructing/ supporting the
numeric values or expressions in a program. These range
from 0 to 9, and also help in defining an identifier.
Type of Descr Characters
Charact iption
er

Digits 0 to 9 0, 1, 2, 3, 4, 5, 6,
7, 8, 9
Special Characters
We use some special characters in the C language for
some special purposes, such as logical operations,

8
FUNDAMENTALS OF COMPUTER PROGRAMMING

mathematical operations, checking of conditions, backspaces,


white spaces, etc.
The C programming language provides support for the
following types of special characters:
Examples

`~@!$#^*%&()[]{}<>+=_–
|/\;:‘“,.?

White Spaces
The white spaces in the C programming language
contain the following:
Blank Spaces
Carriage Return
Tab
New Line

1.3 C tokens:
Tokens are some of the most important elements used
in the C language for creating a program. One can define
tokens in C as the smallest individual elements in a program
that is meaningful to the functioning of a compiler.
Classification and Types of Tokens in C
Here are the categories in which we can divide the
token in C language:
Identifiers in C
Keywords in C
Operators in C
Strings in C
Special Characters in C
Constant in C
1. Identifiers in C
These are used to name the arrays, functions,
structures, variables, etc. The identifiers are user-defined
words in the C language. These can consist of lowercase
letters, uppercase letters, digits, or underscores, but the

9
FUNDAMENTALS OF COMPUTER PROGRAMMING

starting letter should always be either an alphabet or an


underscore.
The identifiers must not begin with a numerical digit.
The first character used in an identifier should be either an
underscore or an alphabet. After that, any of the characters,
underscores, or digits can follow it.
Both- the lowercase and uppercase letters are distinct in an
identifier. Thus, we can safely say that an identifier is case-
sensitive.
2. Keywords in C
We can define the keywords as the reserved or pre-
defined words that hold their own importance. It means that
every keyword has a functionality of its own. Since the
keywords are basically predefined words that the compilers
use, thus we cannot use them as the names of variables.
The C language provides a support for 32 keywords, as
mentioned below:
auto const

dou float
ble

stru unsign
ct ed

int short

brea continu
k e

10
FUNDAMENTALS OF COMPUTER PROGRAMMING

else for

swit void
ch

long signed

3. Operators in C
The operators in C are the special symbols that we use
for performing various functions. Operands are those data
items on which we apply the operators. We apply the
operators in between various operands. On the basis of the
total number of operands, here is how we classify the
operators:
Unary Operator
Binary Operator
Ternary Operator

1. Unary Operator
The unary operator in c is a type of operator that gets
applied to one single operand, for example: (–) decrement
operator, (++) increment operator, (type)*, sizeof, etc.
2. Binary Operator
Binary operators are the types of operators that we
apply between two of the operands. Here is a list of all the
binary operators that we have in the C language:
Relational Operators
Arithmetic Operators
Logical Operators
Shift Operators
Conditional Operators
Bitwise Operators
Misc Operator
Assignment Operator
3. Ternary Operator

11
FUNDAMENTALS OF COMPUTER PROGRAMMING

Using this operator would require a total of three


operands. For instance, we can use the ?: in place of the if-
else conditions.
4. Strings in C
The strings in C always get represented in the form of
an array of characters. We have a ‘\0′ null character at the
end of any string- thus, this null character represents the end
of that string. In C language, double quotes enclose the
strings, while the characters get enclosed typically within
various single characters.
char x[9] = “chocolate’; // Here, the compiler allocates a
total of 9 bytes to the ‘x’ array.
char x[] = ‘chocolate’; // Here, the compiler performs
allocation of memory during the run time.
char x[9] = {‘c’,’h’,’o’,’c’,’o’,’l’,’a’,’t’,’e’,’\0′}; // Here, we are
representing the string in the form of the individual
characters that it has.

Special Characters in C
We also use some of the special characters in the C language
 () Simple brackets – We use these during function calling as well as during
function declaration. For instance, the function printf() is pre-defined.
 [ ] Square brackets – The closing and opening brackets represent the
multidimensional and single subscripts.
 (,) Comma – We use the comma for separating more than one statement,
separating the function parameters used in a function call, and for separating
various variables when we print the value of multiple variables using only one
printf statement.
 { } Curly braces – We use it during the closing as well as opening of any
code. We also use the curly braces during the closing and opening of the loops.
 (*) Asterisk – We use this symbol for representing the pointers and we also
use this symbol as a type of operator for multiplication.
 (#) Hash/preprocessor – We use it for the preprocessor directive. This
processor basically denotes that the user is utilizing the header file.
 (.) Period – We use the period symbol for accessing a member of a union or
a structure.
 (~) Tilde – We use this special character in the form of a destructor for free
memory.

5. Constant in C
Constant is basically a value of a variable that does not
change throughout a program. The constants remain the
same, and we cannot change their value whatsoever. Here are
two of the ways in which we can declare a constant:
By using a #define pre-processor
By using a const keyword
Here is a list of the types of constants that we use in the C
language:

12
FUNDAMENTALS OF COMPUTER PROGRAMMING

Type of Constant Example

Floating-point 25.7, 87.4, 13.9, etc.


constant

Integer constant 20, 41, 94, etc.

Hexadecimal 0x5x, 0x3y, 0x8z,


constant etc.

Octal constant 033, 099, 077, 011,


etc.

String constant “c++”, “.net”, “java”,


etc.

Character constant ‘p’, ‘q’, ‘r’, etc.

1.4 KEYWORD & IDENTIFIERS


Keywords and Identifiers
C is a programming language that uses keywords and
identifiers. Keywords are reserved words that have a specific
meaning and are used by the compiler to understand the
structure of the program. Identifiers, on the other hand, are
names given to variables, functions, and other program
elements. Let's know more about them.
Keywords in C:
Keywords are reserved words in C that have a specific
meaning and cannot be used as identifiers. C has a set of
predefined keywords, and these keywords are reserved for
specific purposes in the program.
The following table contains some important and widely used
keywords in C.
aut dou
o ble

bre else
ak

cas enu
e m

13
FUNDAMENTALS OF COMPUTER PROGRAMMING

ch exte
ar rn

co float
nst

co for
nti
nu
e

def goto
aul
t

do if

Identifiers in C:
Identifiers are names given to variables, functions, and
other program elements.
We use letters, digits, and underscore (_) to compose
identifiers.

Example:
int age;
float average_grade;
void print_student_info();

Character set
A character set is a set of alphabets, letters and some
special characters that are valid in C language.
Alphabets

14
FUNDAMENTALS OF COMPUTER PROGRAMMING

Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
C accepts both lowercase and uppercase alphabets as
variables and functions.
Digits
0123456789
Special Characters
Special Characters in C Programming

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "

^ ! * / |

- \ ~ +
White space Characters
Blank space, newline, horizontal tab, carriage return
and form feed.
C Keywords
Keywords are predefined, reserved words used in
programming that have special meanings to the compiler.
Keywords are part of the syntax and they cannot be used as
an identifier. For example:
int money;
Here, int is a keyword that indicates money is
a variable of type int (integer).
As C is a case sensitive language, all keywords must be
written in lowercase. Here is a list of all keywords allowed in
ANSI C.
C Keywords

a
doubl str
ut int
e uct
o

br
swi
ea else long
tch
k

ca enum regis typ


se ter ed

15
FUNDAMENTALS OF COMPUTER PROGRAMMING

ef

c
retu un
h extern
rn ion
ar

co
nt
sign voi
in for
ed d
u
e

d stati wh
if
o c ile

d
ef vol
sizeo
a goto atil
f
ul e
t

un
co
shor sig
n float
t ne
st
d
All these keywords, their syntax, and application will be
discussed in their respective topics. However, if you want a
brief overview of these keywords without going further,
visit List of all keywords in C programming.
C Identifiers
Identifier refers to name given to entities such as
variables, functions, structures etc.
Identifiers must be unique. They are created to give a
unique name to an entity to identify it during the execution of
the program. For example:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
Also remember, identifier names must be different from
keywords. You cannot use int as an identifier because int is a
keyword.

1.5 CONSTANTS
A constant is a name given to the variable whose values
can’t be altered or changed. A constant is very similar to
variables in the C programming language, but it can hold only
a single variable during the execution of a program.
Types of Constants in C

16
FUNDAMENTALS OF COMPUTER PROGRAMMING

Type of Example of
Constants Data type

Integer
constants
int 2000u,
23, 738, - 5000U, etc.
1278, etc.

325,647
1,245,473,
940

Floating-

17
FUNDAMENTALS OF COMPUTER PROGRAMMING

point or 20.987654
Real
constants
doule
500.987654
321

Octal Example:
constant 013
/*starts
with 0 */

Hexadecimal Example:
constant 0x90
/*starts
with 0x*/

character Example:
constants ‘X’, ‘Y’, ‘Z’

string Example:
constants “PQRS”,
“ABCD”

Types of Constants in C
Integer Constants
It can be an octal integer or a decimal integer or even a
hexadecimal integer. We specify a decimal integer value as a
direct integer value, while we prefix the octal integer values
with ‘o’. We also prefix the hexadecimal integer values with
‘0x’.
The integer constant used in a program can also be of
an unsigned type or a long type. We suffix the unsigned
constant value with ‘u’ and we suffix the long integer constant
value with ‘l’. Also, we suffix the unsigned long integer
constant value using ‘ul’.
Examples,
55 —> Decimal Integer Constant
0x5B —> Hexa Decimal Integer Constant
O23 —> Octal Integer Constant
68ul —> Unsigned Long Integer Constant
50l —> Long Integer Constant
30u —> Unsigned Integer Constant
Floating Point Constants / Real Constants
This type of constant must contain both the parts-
decimal as well as integers. Sometimes, the floating-point

18
FUNDAMENTALS OF COMPUTER PROGRAMMING

constant may also contain the exponential part. In such a


case when the floating-point constant gets represented in an
exponential form, its value must be suffixed using ‘E’ or ‘e’.
Example,
We represent the floating-point value 3.14 as 3E-14 in
its exponent form.
Character Constants
The character constants are symbols that are enclosed
in one single quotation. The maximum length of a character
quotation is of one character only.
Example,
‘B’
‘5’
‘+’
Some predefined character constants exist in the C
programming language, known as escape sequences. Each
escape sequence consists of a special functionality of its own,
and each of these sequences gets prefixed with a ‘/’ symbol.
We use these escape sequences in output functions known as
‘printf()’.
String Constants
The string constants are a collection of various special
symbols, digits, characters, and escape sequences that get
enclosed in double quotations.
The definition of a string constant occurs in a single
line:
“This is Cookie”
We can define this with the use of constant multiple
lines as well:
” This\
is\
Cookie”
The definition of the same string constant can also
occur using white spaces:
“This” “is” “Cookie”
All the three mentioned above define the very same
string constant.

Rules of Constructing Constants in C


Here is how we construct these constants in a given
program:
Integer Constants
 It must have at least one digit.
 There must be no decimal point.
 It does not allow any blanks or commas.
 An integer constant can be both negative or positive.
 We assume an integer constant to be positive if there is no sign in front of
that constant.
 The allowable range for this type of constant is from -32768 to 32767.

19
FUNDAMENTALS OF COMPUTER PROGRAMMING

Real Constants
 This type of constant must consist of one digit at least.
 There must not be any decimal point.
 This type of constant can be both negative or positive.
 It does not allow any blanks or commas within.
 We assume an integer constant to be positive if there is no sign in front of
that constant.
String and Character Constants
 This type of constant can be a single digit, a single alphabet, or even a
single special symbol that stays enclosed within single quotes.
 The string constants get enclosed within double quotes.
 The maximum length of this type of constant is a single character.
Backslash Character Constants
 These are some types of characters that have a special type of meaning in
the C language.
 These types of constants must be preceded by a backslash symbol so that
the program can use the special function in them.
 Here is a list of all the special characters used in the C language and their
purpose:
Meaning of Character Backs
lash
Chara
cter

Backspace \b

New line \n

Form feed \f

Horizontal tab \t

Carriage return \r

Single quote \’

Double quote \”

Vertical tab \v

Backslash \\

Question mark \?

Alert or bell \a

Hexadecimal constant (Here, N – \XN


hex.dcml cnst)

Octal constant (Here, N is an octal \N


constant)

20
FUNDAMENTALS OF COMPUTER PROGRAMMING

1.6 VARIABLES
Variables are containers for storing data values, like numbers
and characters.
In C, there are different types of variables (defined with
different keywords), for example:
 int - stores integers (whole numbers), without decimals, such as 123 or -
123
 float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes

Declaring (Creating) Variables


To create a variable, specify the type and assign it
a value:
Syntax
type variableName = value;
Variables in C:
Variables are values that can be changed during
program execution. In C, variables can be of different types,
including integers, floating-point numbers, characters, and
arrays.
Syntax to declare a variable in C:
Variables in C are declared using a data type keyword,
followed by the variable name.
data_type variable_name;
Variables in C can also be initialized with a value at the
time of declaration. To assign value to a variable, we use the
assignment operator (=).
data_type variable_name = value;

1.7 Data Types


A variable in C must be a specified data type, and you
must use a format specifier inside the printf() function to
display it:

21
FUNDAMENTALS OF COMPUTER PROGRAMMING

Da Size Description
ta
Ty
pe

int 2 or 4 Stores whole


bytes numbers, without
decimals

flo 4 bytes Stores fractional


at numbers,
containing one or
more decimals.
Sufficient for
storing 6-7
decimal digits

do 8 bytes Stores fractional


ubl numbers,
e containing one or
more decimals.
Sufficient for
storing 15 decimal
digits

ch 1 byte Stores a single


ar character/letter/n
umber, or ASCII
values

For Data
ma Type
t
Sp
eci
fier

%d int
or
%i

%f float

%lf double

%c char

%s Used
for string
s (text),
which
you will
learn
more 22
about in
a later
chapter
FUNDAMENTALS OF COMPUTER PROGRAMMING

Example
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character

// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

OUTPUT:
5
5.990000
D

1.7 ASSIGNING VALUES TO VARIABLES


“Assigning a value to a variable” means writing a value
to the variable. This process involves four entities:
A data type
A variable
The simple assignment operator (=)
The value that will be copied to the variable
A typical example of assigning a value to a variable is
the statement “int a = 4.” Here:
“int” is the data type
“a” is the variable
"=" is the operator
“4” is the value
Assigning a value is a process that defines the value of
a variable or a constant.
A constant is a data item whose value remains constant
throughout the execution of the program.
A variable is a data item whose value can vary. The
value of a variable changes according to the instructions
executed. During the execution of a program, the value of a
variable might keep changing.
To see what constants and variables are, let’s start from the
bottom up:
A token is the smallest unit of a program that means
something to the compiler. Words, punctuation marks and
operators are all tokens.
An identifier is a token that has a unique name. In a
program, the name is assigned to the token by the
programmer. Names can be assigned to variables, constants,
functions, arrays, structures, and other constructs.
Seen this way, variables and constants are both examples of
identifiers.

23
FUNDAMENTALS OF COMPUTER PROGRAMMING

1.8 DEFINING SYMBOLIC CONSTANTS


A symbolic constant is a name given to any constant. In
C, the preprocessor directive
#define
is used for defining symbolic constants.
#define
instructions are usually placed at the beginning of the
program. By convention, the names of symbolic constants are
written in uppercase, but this is not compulsory. The syntax
for creating a symbolic constant is as follows:
#define constant_name value
For example:
#define PI 3.14
#include <stdio.h>
#define PI 3.1415
int main()
{
float radius=10, area;
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}

1.9 ARITHMETIC, RELATIONAL, LOGICAL, ASSIGNMENT,


CONDITIONAL, BITWISE, SPECIAL, INCREMENT AND
DECREMENT OPERATORS
1.ARITHMETIC
An arithmetic operator performs mathematical
operations such as addition, subtraction, multiplication,
division etc on numerical values (constants and variables).
Operato
Meaning of Operator
r

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)


// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

24
FUNDAMENTALS OF COMPUTER PROGRAMMING

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

2. RELATIONAL
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.
Meaning of
Operator Example
Operator

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

5 > 3 is
> Greater than
evaluated to 1

5 < 3 is
< Less than
evaluated to 0

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

Greater than or 5 >= 3 is


>=
equal to evaluated to 1

Less than or 5 <= 3 is


<=
equal to evaluated to 0
Example :Relational Operators
// Working of relational operators

25
FUNDAMENTALS OF COMPUTER PROGRAMMING

#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

3.LOGICAL
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
If c = 5 and d = 2
AND. True
then, expression
&& only if all
((c==5) && (d>5))
operands
equals to 0.
are true

|| Logical OR. If c = 5 and d = 2

26
FUNDAMENTALS OF COMPUTER PROGRAMMING

Operator Meaning Example

True only if
then, expression
either one
((c==5) || (d>5))
operand is
equals to 1.
true

Llogical
NOT. True If c = 5 then,
! only if the expression !(c==5)
operand is equals to 0.
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

27
FUNDAMENTALS OF COMPUTER PROGRAMMING

4.ASSIGNMENT
The assignment operators are used to assign right-hand
side value (Rvalue) to the left-hand side variable (Lvalue). The
assignment operator is used in different variants along with
arithmetic operators.

5.CONDITIONAL
The conditional operator is also called a ternary
operator because it requires three operands. This operator is
used for decision making. In this operator, first we verify a
condition, then we perform one operation out of the two
operations based on the condition result. If the condition is
TRUE the first option is performed, if the condition is FALSE
the second option is performed. The conditional operator is
used with the following syntax.
Condition ? TRUE Part : FALSE Part;
Example
A = (10<15)?100:200; ⇒ A value is 100

6.Bitwise Operators (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level
operations in the c programming language. When we use the
bitwise operators, the operations are performed based on the
binary values. The following table describes all the bitwise
operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and
B = 20 (10100).

Operator Meaning Example

& the result of Bitwise AND is 1 if all the bits A &


are 1 otherwise it is 0 ⇒ 16 (10000)

| the result of Bitwise OR is 0 if all the bits A |

28
FUNDAMENTALS OF COMPUTER PROGRAMMING

are 0 otherwise it is 1 ⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits A ^


are same otherwise it is 1 ⇒ 13 (01101)

~ the result of Bitwise once complement is ~A


negation of the bit (Flipping) ⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the A <<
bits to the left by the specified number ⇒ of 100 (1100100)
positions

>> the Bitwise right shift operator shifts all A >>


the bits to the right by the specified ⇒ 6 (00110)
number of positions

7. Special Operators (sizeof, pointer, comma, dot, etc.)


The following are the special operators in c programming
language.
sizeof operator
This operator is used to find the size of the memory (in bytes)
allocated for a variable. This operator is used with the
following syntax.
sizeof(variableName);
Example
sizeof(A); ⇒ the result is 2 if A is an integer
Pointer operator (*)
This operator is used to define pointer variables in c
programming language.

Comma operator (,)


This operator is used to separate variables while they
are declaring, separate the expressions in function calls, etc.
Dot operator (.)
This operator is used to access members of structure or
union.

8.Increment & Decrement Operators (++ & --)


The increment and decrement operators are called
unary operators because both need only one operand. The
increment operators adds one to the existing value of the
operand and the decrement operator subtracts one from the
existing value of the operand. The following table provides
information about increment and decrement operators.

29
FUNDAMENTALS OF COMPUTER PROGRAMMING

Operat
or Meaning Example

++ Increment - Adds one to int a = 5;


existing value a++; ⇒ a =
6

-- Decrement - Subtracts int a = 5;


one from existing value a--; ⇒ a =
4

The increment and decrement operators are used


infront of the operand (++a) or after the operand (a++). If it is
used infront of the operand, we call it as pre-
increment or pre-decrement and if it is used after the
operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is
increased by one before the expression evaluation. In the case
of pre-decrement, the value of the variable is decreased by one
before the expression evaluation. That means, when we use
pre-increment or pre-decrement, first the value of the variable
is incremented or decremented by one, then the modified
value is used in the expression evaluation.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment

printf("i = %d, j = %d",i,j);


}
Output:

1.10 EXPRESSION
EVALUATION OF EXPRESSION

30
FUNDAMENTALS OF COMPUTER PROGRAMMING

In c language expression evaluation is mainly depends


on priority and associativity.
An expression is a sequence of operands and operators that
reduces to a single value.
For example, the expression, 10+15 reduces to the value of 25.
An expression is a combination of variables constants and operators
written according to the syntax of C language. every expression results in
some value of a certain type that can be assigned to a variable.

Priority
This represents the evaluation of expression starts from
"what" operator.
Associativity
It represents which operator should be evaluated first if
an expression is containing more than one operator with
same priority.
Operat Prio
Associativity
or rity

{}, (), [] 1 Left to right

++, --, ! 2 Right to left

*, /, % 3 Left to right

+, - 4 Left to right

<, <=, >,


>=, ==, ! 5 Left to right
=

&& 6 Left to right

|| 7 Left to right

?: 8 Right to left

=, +=, -
=, *=, 9 Right to left
/=, %=
Example 1:

31
FUNDAMENTALS OF COMPUTER PROGRAMMING

Example 2:

Types of Expression Evaluation in C


Based on the operators and operators used in the
expression, they are divided into several types. Types of
Expression Evaluation in C are:
Integer expressions – expressions which contains integers
and operators
Real expressions – expressions which contains floating point
values and operators
Arithmetic expressions – expressions which contain
operands and arithmetic operators
Mixed mode arithmetic expressions – expressions which
contain both integer and real operands
Relational expressions – expressions which contain
relational operators and operands
Logical expressions – expressions which contain logical
operators and operands

1.11 PRECEDENCE OF ARITHMETIC OPERATORS


An arithmetic expression is a combination of variables,
constants, and arithmetic operators. Arithmetic operators
supported in C are
Arithmetic expressions are evaluated using an assignment
statement of the form
variable = expression

32
FUNDAMENTALS OF COMPUTER PROGRAMMING

The expression is evaluated first and the value is


assigned to the variable. An example of an evaluation
statement is,
c=a-b/d+e
Arithmetic expressions without parentheses are
evaluated from left to right using the rules of operator
precedence. In C, arithmetic operators have two different
priority levels.

Hight priority
*/%
Low priority
+-
For example, the statement x = 8 – 15 / 5 + 2 * 5 – 7 is evaluated as
follows,
First pass
x = 8 - 5 + 2 * 5 -7
x = 8 - 5 + 10 - 7
Second pass
x = 3 + 10 - 7
x = 13 - 7
x=6

These steps are illustrated in the following figure.

For example, the statement x = 8 – 14 / (5 + 2) * (8 – 7)


is evaluated as follows,
First pass
x = 8 - 14 / 7 * (8 -7)
x = 8 - 14 / 7 * 1
Second pass
x=8-2*1
x=8-2
Third pass
x=6

1.12 TYPE CONVERSION IN EXPRESSION


To convert the value of one data type to another type.
This is known as type conversion.
int x = 5;
int y = 2;
int sum = 5 / 2;

printf("%d", sum); // Outputs 2

33
FUNDAMENTALS OF COMPUTER PROGRAMMING

There are two types of conversion in C:


Implicit Conversion (automatically)
Explicit Conversion (manually)
Implicit Conversion
Implicit conversion is done automatically by the
compiler when you assign a value of one type to another.
For example, if you assign an int value to a float type:
#include <stdio.h>

int main() {
// Manual conversion: int to float
float sum = (float) 5 / 2;

printf("%f", sum);
return 0;
}
Explicit Conversion
Explicit conversion is done manually by placing the
type in parentheses () in front of the value.
Considering our problem from the example above, we can now
get the right result:
#include <stdio.h>

int main() {
// Manual conversion: int to float
float sum = (float) 5 / 2;

printf("%f", sum);
return 0;
}
Output:
2.500000

1.13 OPERATOR PRECEDENCE & AS SOCIATIVITY


The concept of operator precedence and
associativity in C helps in determining which operators will
be given priority when there are multiple operators in the
expression.
Operator precedence, operator associativity, and
precedence table according to which the priority of the
operators in expression is decided in C language.
Example of Operator Precedence
Let’s try to evaluate the following expression,
10 + 20 * 30
The expression contains two operators, + (plus), and *
(multiply). According to the given table, the * has higher
precedence than + so, the first evaluation will be
10 + (20 * 30)

34
FUNDAMENTALS OF COMPUTER PROGRAMMING

After evaluating the higher precedence operator, the


expression is
10 + 600
Now, the + operator will be evaluated.
610

#include <stdio.h>
int main()
{
// printing the value of same expression
printf("10 + 20 * 30 = %d", 10 + 20 * 30);

return 0;
}
Output
10 + 20 * 30 = 610
As we can see, the expression is evaluated as,10 + (20
* 30) but not as (10 + 20) * 30 due to * operator having
higher precedence.
// C Program to illustrate operator Associativity
#include <stdio.h>
int main()
{
// Verifying the result of the same expression
printf("100 / 5 % 2 = %d", 100 / 5 % 2);

return 0;
}
Output
100 / 5 % 2 = 0

35
FUNDAMENTALS OF COMPUTER PROGRAMMING

1.14 MATHEMATICAL FUNCTIONS


1. floor (double a)
This function returns the largest integer value not
greater than ‘a’ value. It rounds a value and returns a double
as a result.
To include math.h header file in our program.
1. abs() Function
The abs() function returns the absolute value of an
integer number.
The absolute value of a number is always positive.
Syntax of abs() function
int abs(int num);
Example
#include <stdio.h>
#include <conio.h>
#include <math.h>

int main()
{
int n,x;
printf("Enter an integer number ");
scanf("%d",&n);
x=abs(n);
printf("Absolute value of %d is %d",n,x);
return 0;
}
Output
Enter an integer number -18
Absolute value of -18 is 18

2.sqrt() Function
The sqrt() function returns the square root of a positive
number. Remember that square root of a negative can not be
calculated.

36
FUNDAMENTALS OF COMPUTER PROGRAMMING

Syntax of sqrt() function


double sqrt(double num);

A sqrt() function takes input in double data type and


return the result in double data type.
Example
C program to input an integer and print its square root.
#include <stdio.h>
#include <conio.h>
#include <math.h>

int main()
{
int n,x;
printf("Enter an integer number ");
scanf("%d",&n);
x=sqrt(n);
printf("Square root of %d is %d",n,x);
return 0;
}
Output
Enter an integer number 25
Square root of 25 is 5

3.ceil() Function
The ceil() function returns the nearest integer number
greater than the number passed as argument.
Syntax of ceil() function
double ceil(double num);
A ceil() function takes input in double data type and
return the result in double data type.

Example
C program to input a floating point number and print its ceil value.
#include <stdio.h>
#include <conio.h>
#include <math.h>

int main()
{
float n,x;
printf("Enter a floating point (decimal) number ");
scanf("%f",&n);
x=ceil(n);
printf("Ceil value of %f is %f",n,x);
return 0;
}

Output

37
FUNDAMENTALS OF COMPUTER PROGRAMMING

Enter a floating point (decimal) number 12.4


Ceil value of 12.400000 is 13.000000

1.15 READING & WRITING A CHARACTER

We can read and write a character on screen using


printf() and scanf() function but this is not applicable in all
situations. In C programming language some function are
available which is directly read a character or number of
character from keyboard.
Getchar;
This is a predefined function in C language which is
available in stdio.h header file. Using this function we can
read a single character from keyboard and store in character
variable.
Example
char ch;
ch=getch();

gets
This is a predefined function in C language which is available
in stdio.h header file. This function is used to read a single
string from keyboard.
Example
gets(string);

putchar
putchar function is a same as getchar but is function is used
for display a character value of screen or console. This
function must be take one parameters.

Example
char ch='A';
putchar (ch);
putchar is equivalent to printf("%c",ch);

puts
puts is same as gets function but this is used to display a
string on screen or console. This function takes single
arguments.

Example
puts(str);

1.16 FORMATTED INPUT AND OUTPUT


Formatted I/O Functions.
Unformatted I/O Functions.
Formatted I/O Functions vs Unformatted I/O Functions.

38
FUNDAMENTALS OF COMPUTER PROGRAMMING

Formatted I/O Functions


Formatted I/O functions are used to take various
inputs from the user and display multiple outputs to the
user. These types of I/O functions can help to display the
output to the user in different formats using the format
specifiers. These I/O supports all data types like int, float,
char, and many more.
Why they are called formatted I/O?
These functions are called formatted I/O functions
because we can use format specifiers in these functions

The following formatted I/O functions will be discussed in this


section-
printf()
scanf()
sprintf()
sscanf()
1. printf():
printf() function is used in a C program to display any
value like float, integer, character, string, etc on the console
screen. It is a pre-defined function that is already declared in
the stdio.h(header file).
Syntax 1:
To display any variable value.
printf(“Format Specifier”, var1, var2, …., varn);

Example:
// C program to implement
// printf() function
#include <stdio.h>

// Driver code

39
FUNDAMENTALS OF COMPUTER PROGRAMMING

int main()
{
// Declaring an int type variable
int a;

// Assigning a value in a variable


a = 20;

// Printing the value of a variable


printf("%d", a);

return 0;
}

Output
20

2. scanf():
scanf() function is used in the C program for reading or
taking any value from the keyboard by the user, these values
can be of any data type like integer, float, character, string,
and many more. This function is declared in stdio.h(header
file), that’s why it is also a pre-defined function.
In scanf() function we use &(address-of operator) which is
used to store the variable value on the memory location of
that variable.
Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);
Example:
// C program to implement
// scanf() function
#include <stdio.h>

// Driver code
int main()
{
int num1;

// Printing a message on
// the output screen
printf("Enter a integer number: ");

// Taking an integer value


// from keyboard
scanf("%d", &num1);

// Displaying the entered value


printf("You have entered %d", num1);

40
FUNDAMENTALS OF COMPUTER PROGRAMMING

return 0;
}
Output
Enter a integer number: You have entered 0
Output:
Enter a integer number: 56
You have entered 56

3. sprintf():
sprintf stands for “string print”. This function is
similar to printf() function but this function prints the string
into a character array instead of printing it on the console
screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);
Example:
// C program to implement
// the sprintf() function
#include <stdio.h>

// Driver code
int main()
{
char str[50];
int a = 2, b = 8;

// The string "2 and 8 are even number"


// is now stored into str
sprintf(str, "%d and %d are even number",
a, b);

// Displays the string


printf("%s", str);
return 0;
}
Output
2 and 8 are even number

4. sscanf():
sscanf stands for “string scanf”. This function is
similar to scanf() function but this function reads data from
the string or character array instead of the console screen.
Syntax:
sscanf(array_name, “format specifier”, &variable_name);
Example:
// C program to implement
// sscanf() function
#include <stdio.h>

41
FUNDAMENTALS OF COMPUTER PROGRAMMING

// Driver code
int main()
{
char str[50];
int a = 2, b = 8, c, d;

// The string "a = 2 and b = 8"


// is now stored into str
// character array
sprintf(str, "a = %d and b = %d",
a, b);

// The value of a and b is now in


// c and d
sscanf(str, "a = %d and b = %d",
&c, &d);

// Displays the value of c and d


printf("c = %d and d = %d", c, d);
return 0;
}
Output
c = 2 and d = 8

Unformatted Input/Output functions


Unformatted I/O functions are used only for character
data type or character array/string and cannot be used for
any other datatype. These functions are used to read single
input from the user at the console and it allows to display the
value at the console.
Why they are called unformatted I/O?
These functions are called unformatted I/O functions
because we cannot use format specifiers in these functions
and hence, cannot format these functions according to our
needs.
The following unformatted I/O functions will be discussed in
this section-
getch()
getche()
getchar()
putchar()
gets()
puts()
putch()

1. getch():
getch() function reads a single character from the
keyboard by the user but doesn’t display that character on
the console screen and immediately returned without pressing

42
FUNDAMENTALS OF COMPUTER PROGRAMMING

enter key. This function is declared in conio.h(header file).


getch() is also used for hold the screen.
Syntax:
getch();
or
variable-name = getch();
Example:
// C program to implement
// getch() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
printf("Enter any character: ");

// Reads a character but


// not displays
getch();

return 0;
}
Output:
Enter any character:

2. getche():
getche() function reads a single character from the
keyboard by the user and displays it on the console screen
and immediately returns without pressing the enter key. This
function is declared in conio.h(header file).
Syntax:
getche();
or
variable_name = getche();
Example:
// C program to implement
// the getche() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
printf("Enter any character: ");

// Reads a character and


// displays immediately
getche();

43
FUNDAMENTALS OF COMPUTER PROGRAMMING

return 0;
}
Output:
Enter any character: g

3. getchar():
The getchar() function is used to read only a first single
character from the keyboard whether multiple characters is
typed by the user and this function reads one character at
one time until and unless the enter key is pressed. This
function is declared in stdio.h(header file)
Syntax:
Variable-name = getchar();
Example:
// C program to implement
// the getchar() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
// Declaring a char type variable
char ch;

printf("Enter the character: ");

// Taking a character from keyboard


ch = getchar();

// Displays the value of ch


printf("%c", ch);
return 0;
}
Output:
Enter the character: a
A

4. putchar():
The putchar() function is used to display a single
character at a time by passing that character directly to it or
by passing a variable that has already stored a character. This
function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);
Example:
// C program to implement
// the putchar() function
#include <conio.h>

44
FUNDAMENTALS OF COMPUTER PROGRAMMING

#include <stdio.h>

// Driver code
int main()
{
char ch;
printf("Enter any character: ");

// Reads a character
ch = getchar();

// Displays that character


putchar(ch);
return 0;
}
Output:
Enter any character: Z
Z
5. gets():
gets() function reads a group of characters or strings
from the keyboard by the user and these characters get stored
in a character array.
This function allows us to write space-separated texts or
strings. This function is declared in stdio.h(header file).
Syntax:
char str[length of string in number]; //Declare a char type
variable of any length
gets(str);
Example:
// C program to implement
// the gets() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
// Declaring a char type array
// of length 50 characters
char name[50];

printf("Please enter some texts: ");

// Reading a line of character or


// a string
gets(name);

// Displaying this line of character


// or a string

45
FUNDAMENTALS OF COMPUTER PROGRAMMING

printf("You have entered: %s",


name);
return 0;
}
Output:
Please enter some texts: geeks for geeks
You have entered: geeks for geeks

6. puts():
In C programming puts() function is used to display a
group of characters or strings which is already stored in a
character array.
This function is declared in stdio.h(header file).
Syntax:
puts(identifier_name );
Example:
// C program to implement
// the puts() function
#include <stdio.h>

// Driver code
int main()
{
char name[50];
printf("Enter your text: ");

// Reads string from user


gets(name);

printf("Your text is: ");

// Displays string
puts(name);

return 0;
}
Output:
Enter your text: GeeksforGeeks
Your text is: GeeksforGeeks

7. putch():
putch() function is used to display a single character
which is given by the user and that character prints at the
current cursor location. This function is declared in
conio.h(header file)
Syntax:
putch(variable_name);
Example:
#include <conio.h>

46
FUNDAMENTALS OF COMPUTER PROGRAMMING

#include <stdio.h>
int main()
{
char ch;
printf("Enter any character:\n ");
ch = getch();

printf("\nEntered character is: ");


putch(ch);
return 0;
}
Output:
Enter any character:
Entered character is: d

---------------------------------------UNIT I
COMPLETED--------------------------------

UNIT II

UNIT II: Decision Making , Looping and Arrays-Decision


Making and Branching: Introduction – if, if….else, nesting of if
…else statementselse if ladder – The switch statement, The ?:
Operator – The go to Statement. Decision Making and
Looping: Introduction- The while statement- the do statement
– the for statement-jumps in loops. Arrays – Character Arrays
and Strings

2.1 DECISION MAKING BRANCHING:


In C programming it support sequential program
statements which execute one statement immediately after
another. Here the flow is sequential it never change the flow of
control from the next line. The compiler executes the program
sequentially in the order which they appear.
This happens when there are no options and if the repeated
steps are not needed. But there are another option when we
need the options and when we want to use the selective steps
repeatedly.

Introduction If Statement
‘If’ is the most powerful decision making statement in C
language. Thus it is used to control the execution of
statements. ‘If’ is used along with an expression. It is a two
way branching or decision making statement.

47
FUNDAMENTALS OF COMPUTER PROGRAMMING

Syntax :
if(test expression)
{
Body of if;
}

Using an ‘if’ a computer first evaluate the expression


and if it is true the body of if is executed which means the
flow of control passes to the if’s body, or if the test condition
is false then the flow of control passes to the immediate step
next to if’s body.
If there are more than one step in the body of ‘if’ they
are normally written with in brackets ‘{ }’ to denote it is the
body of ‘if’.
The test expression will return a Boolean value which is a’0’
or ‘1’. Here 1 is ‘true’ and 0 denotes it is ‘false’.

Two way branching


The figure explain the two way branching of ‘if’
statement.

48
FUNDAMENTALS OF COMPUTER PROGRAMMING

Example:
if(age>55){
printf(“ Retired”);
}
Depending upon the complexity and conditions to be tested if can be
further subdivided.
Simple if
if…..else
nested if…else
if…else…if ladder

simple if statement
The general syntax of a simple if statement is
if(test expression)
{
Body of if;
}
Statement X;

The body of ‘if’ may be a single statement or group of


statements. When the test expression returns a true value
these body of if is executed. If the condition is false the flow of
control passes to the statement X. The statement X will be
executed in both cases.

2.2 If Else If Statement


An extension to simple if is called if.. else statement.
Syntax:
if(test expression)
{
Body of if;
}
else
{
Body of else;
}
Statement x;
As a simple if statement first tests the condition. If it is
true then executes the body of if and then skips the next part
and then passes the control in to the statement x. Here we
added another block which is the set of statements to do
when the condition is false and it is named as else.
The flow passes to else part after skipping the body of if
whenever the condition fails. The condition may return ‘true’
or ‘false’ in both cases the statement x is executed.
Example :
if( code==1)
boy=boy+1;

49
FUNDAMENTALS OF COMPUTER PROGRAMMING

else
girl=girl+1;

2.3 Nested if statement


It is used when a series of decisions are involved and
have to use more than one if…else statement.
Syntax :
if(condition 1)
{
if(condition 2)
{
body of if;
}
else
{
Body of else;
}
}
else
{
Body of else;
}

50
FUNDAMENTALS OF COMPUTER PROGRAMMING

Statement x;
Example :

if( a>b)
{
if(a>c)
printf(“ a is greater”);
else
printf(“ c is greater”);
}
else
{
if(b>c)
{
Printf(“b is greater”);
}
else
{
Printf(“c is greater”);
}
}
Here it explains the greatest among three numbers.

2.4 The if… else… if ladder


To take multipath decisions or chain of ifs then we use
the if …else…if ladder. It is in the following general form
if(condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;

51
FUNDAMENTALS OF COMPUTER PROGRAMMING

else
statement 4;
statement x;

The conditions are evaluated from the top of the ladder


down words as soon as a true condition is found. The
compiler executes the ladder till a true condition is found, and
when found a true condition execute the statements
associated with it. After executing the statements the control
passes to the statement x.
Example :
if(percentage >==80)
printf(“ Distinction”);
else if(percentage >==60)
printf(“ first class ”);
else if(percentage >==50)
printf(“ second class ”);
else
printf(“ failed “);

2.5 The switch statement


If is a conditional statement where ‘switch’ is a
selection statement which means if we want to select one
from many alternatives we use ‘switch’. The selective
statement ‘switch’ is a multi way decision statement, that is
using a single expression we can direct the flow of control to
multiple paths. ‘Switch ‘ statement tests the value of given
expression or variable against a list of case values and when a

52
FUNDAMENTALS OF COMPUTER PROGRAMMING

match is found that block of statements associated with that


case is executed.

Syntax :
switch(expression)
{
case constant1 :
block1;
break;
case constant2 :
block2;
break;
case constant n:
block n;

53
FUNDAMENTALS OF COMPUTER PROGRAMMING

break;
.
.
.
default:
default block;
break;
}
statement x;
When the ‘switch’ is executed the value of the
expression is successfully compared against the case’s
constants. When a case constant is found the block of codes
associated with it is executed, and if till the last case
constant no match is found the block associated with the
default case is executed. The default is an optional case .
If it is not present and no matches are found then control
passes to the statement x.
Example :
int num;
printf(“enter a number”);
scanf(‘%d”,&num);
switch(num)
{
case 1:
printf(“Sunday”);
break;
case 2:
printf(“Monday”);
break;
case 3:
printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5:
printf(“Thursday”);
break;
case 6:
printf(“Friday”);
break;
case 7:
printf(“Saturday”);
break;
default:
printf(“wrong choice”);
break;
}

54
FUNDAMENTALS OF COMPUTER PROGRAMMING

Here according to numbers from 1 to 7 the


corresponding day is displayed. If we input any number other
than 1 to 7 then the default case is executed.

2.6 Conditional or Ternary Operator (?:)


The conditional operator in C is kind of similar to
the if-else statement as it follows the same algorithm as
of if-else statement but the conditional operator takes less
space and helps to write the if-else statements in the
shortest way possible. It is also known as the ternary
operator in C as it operates on three operands.

Syntax of Conditional/Ternary Operator in C


The conditional operator can be in the form
variable = Expression1 ? Expression2 : Expression3;
Or the syntax can also be in this form
variable = (condition) ? Expression2 : Expression3;

2.7 Goto Statement


The goto statement allows us to transfer control of the
program to the specified label.
The syntax of goto statement in C can be broken into two
parts:
1. Defining the Label
label_name:
The label_name is used to give a name to a block of
code, hence it acts as an identifier for that block. When a goto
statement is encountered, the program's execution control
goes to the label_name: and specifies that the code will be
executed from there.

We need to always use : (colon) after the label_name


Each label_name has to be unique in the scope where it has
been defined and cannot be a reserved word, just like in
variables.

2. Transferring the Execution Control


goto label_name;

55
FUNDAMENTALS OF COMPUTER PROGRAMMING

The above statement jumps the execution control of the


program to the line where label_name is used.
Style 1: Transferring the Control From Down to the Top
label_name:
.
.
.
goto label_name;

Style 2: Transferring the control from top to down


goto label_name;
.
.
.
label_name:

2.8 Decision Making and Looping

Execution of a statement or set of statement repeatedly


is called as looping.
The loop may be executed a specified number of times
and this depends on the satisfaction of a test condition.
A program loop is made up of two parts one part is
known as body of the loop and the other is known as control
condition.

Entry Controlled Loop:


When the control statement is placed before the body of
the loop then such loops are called as entry controlled loops.

56
FUNDAMENTALS OF COMPUTER PROGRAMMING

If the test condition in the control statement is true then only


the body of the loop is executed.
If the test condition in the control statement is not true
then the body of the loop will not be executed. If the test
condition fails in the first checking itself the body of the loop
will never be executed.

Exit Controlled Loop:

When the control statement is placed after the body of


the loop then such loops are called as exit controlled loop.
In this the body of the loop is executed first then the test
condition in the control statement is checked.
If it is true then the body of the loop is executed again.
If the test condition is false, the body of the loop will not
be executed again. In exit controlled loops even if the test
condition fails in the first attempt itself the body of the loop is
executed at least once.

57
FUNDAMENTALS OF COMPUTER PROGRAMMING

Following are the steps in a looping process:

Initialization of loop control variable. Test of a specific


condition for the execution of the loop. Execution of the
statements in the body of the loop
Altering the value of the loop control variable. whether a
particular condition has been met. The C language provides 3

loop structures:

while loop.
do loop.
for loop.

Control Variables:
These are the variables which control the number of times a
loop will be executed.

2.9 The while statement:


The basic format of the while statement is as given below
while (test condition)
{
body of the loop;
}
This is an entry controlled loop. In this the test
condition is placed before the body of the loop. The test
condition is evaluated first and if it is true, then only the body
of the loop will be executed.
In the body of the loop there will be statement, which
will alter the value of the loop control variable. After the
execution of the body of the loop the test condition is again
evaluated and if it is true then only the body of the loop will

58
FUNDAMENTALS OF COMPUTER PROGRAMMING

be executed. Then the body of the loop will be executed till the
test condition becomes false.
Segment of a program is given below:
i = 0;
while (i<=10)
{
printf ("%d\n", i);
i++;
}

In the above example, the body of while loop is executed


11 times. Since the test of a condition is carried out before the
loop is executed, the body of the loop may not be executed at
all if the condition is not satisfied at the very first instance.

2.10 The do statement:


In some occasions it might be necessary to execute the
body of the loop before the test is performed. Such situations
can be handled with the help of do statement.
Syntax:

do
{
body of the loop;
}
while (test condition);
Example:

i=0;
do
{
printf ("%d\n", i);
i++;
} while (i< 10);

The above loop is executed 11 times because the value of


I is initialized to zero. Consider the following case where i is
initialized to 11, still the body of the loop is executed at least
once although the test condition fails at the first attempt
itself.

i=11;
do
{
printf ("%d\n",i);
i++;
} while (i< 10);

2.11 for loop:

59
FUNDAMENTALS OF COMPUTER PROGRAMMING

This is an entry controlled loop which provides compact


loop control structure. In this, the initialization of loop control
variable, the test condition and change in the value of loop
control variable is done in the single statement separated by
semicolon.

Syntax:

for (initialization; test condition; increment)


{
body of the loop;
}
Example 1:>
Output of this loop construct

for (i=0; i<5; i++) 0


{1
printf ("%d\n", i); 2
}3
4
for (i=4; i>=0; i--) 4
{3
printf ("%d\n", i); 2
}1
0

Example:
for (i=6; i>7; i++)
{
printf ("%d\n", i);
}

2.12 Jumps in loops:


Transferring the execution control from one statement to another
statement within the loop or from within the loop to outside the loop is
possible in C. This kind of jumps can be achieved by break, goto and
continue statements.

break:
Using this statement an early exit from a loop can be achieved. That is
when the break statement is encountered within a loop then the loop is
exited immediately and the statements following the loop will be executed.
When a break is encountered within a nested loop, the loop in which this
statement is present only that loop will be exited. That means the break
will exit only one loop.

Syntax:
break;

60
FUNDAMENTALS OF COMPUTER PROGRAMMING

(a) i=0;
while (i<10>
{
:
:
if (condition)
break;
:
:
}
n=7;
(b) i=0;
do
{
:
:
if (condition)
break;
:
:
} while (i<10);
n=7;
(c) while (i<15)
{
:
for (j=0; j<10; j++)
{
:
if (condition)
break;
:
}
n=7; (d) for (i=0; i<10; i++)
{
:
if(condition)
break;
}
n=7;
In all the above cases the break statement will make the control exit
the loop in which it is residing. Thus it executes the statement n=7
in all the cases.

2.13 Arrays
Following are some usecases where using an array will
make things simpler: to store list of Employee or Student
names, to store marks of students, or to store list of numbers
or characters etc.

61
FUNDAMENTALS OF COMPUTER PROGRAMMING

Since arrays provide an easy way to represent data, it is


classified amongst the data structures in C. Other data
structures in c are structure, lists, queues, trees etc.
Array is a linear data structure which means that the
elements in an array are stored in a continuous manner in
the memory. This makes accessing the elements easier. Array
elements are indexed in an order, starting from 0 to n-1,
where n is the size of the array.
Arrays can be single or multi dimensional. The number
of dimensions in an array is equal to the number of indexing.
A 2-D array (also called a matrix) has two indexes(one for row
and other for column) and so on.
Arrays make our work easy because instead of declaring
100 variables, we can declare an array of size 100.

Advantages of Arrays
In one go, we can initialise storage for more than one
value. Because you can create an array of 10, 100 or 1000
values.
They make accessing elements easier by providing
random access. By random access we mean you can directly
access any element in an array if you know its index.
Sorting and searching operations are easy on arrays.

Disadvantages of Arrays
Due to its fixed size, we cannot increase the size of an
array during runtime. That means once you have created an
array, then it's size cannot be changed.
Insertion and deletion of elements can be costly, in
terms of time taken.

Declaring Arrays in C
Like any other variable, arrays must be
declared(created) before they are used. General form of array
declaration is,

Data-type variable-name[size];
Char a[5];
Float ar[9];
Int arr[10];

In the code above, in the first line, char is the data


type, a is the name of array and 5 is the size. In the next
line, float is the data type, ar is the name of the array and size
of array is 9.

62
FUNDAMENTALS OF COMPUTER PROGRAMMING

And in the last line of code, int is the data types, and arr is
the name of the array and 10 is the size of array. It means
array arr can only contain 10 elements of int type.
The index of an array starts from 0 to size-1 i.e first
element of any array will be stored at arr[0] address and the
last element will be at arr[size - 1].

Initialization of Array in C
After an array is declared it must be initialized.
Otherwise, it will contain garbage value(any random value).
An array can be initialized at either compile time or
at runtime. That means, either we can provide values to the
array in the code itself, or we can add user input value into
the array.
Compile time Array initialization in C
Compile time initialization of array means we provide the
value for the array in the code, when we create the array,

data-type array-name[size] = { list of values };

Let's see a few simple examples,


#include<stdio.h>

void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}

A Character array is a derived data type in C that is


used to store a collection of characters or strings. A char data
type takes 1 byte of memory, so a character array has the
memory of the number of elements in the array. (1*
number_of_elements_in_array).
Each character in a character array has an index that
shows the position of the character in the string.
The first character will be indexed 0 and the successive
characters are indexed 1,2,3 etc...
The null character \0 is used to find the end of
characters in the array and is always stored in the index after
the last character or in the last index.
Consider a string "character", it is indexed as the following
image in a character array.

63
FUNDAMENTALS OF COMPUTER PROGRAMMING

Syntax
There are many syntaxes for creating a character array
in c. The most basic syntax is,
char name[size];

The name depicts the name of the character array


and size is the length of the character array.

Example
Before seeing the example, let us understand the
method of dynamic memory allocation which is used to create
the dynamic array.
Dynamic memory allocation is an efficient way to allocate
memory for a variable in c.
The memory is allocated in the runtime after getting the
number of characters from the user.
It uses pointers, which are structures that point to an
address where the real value of the variable is stored.

The malloc() function is used for dynamic memory


allocation. Its syntax is,

dataType *ptr = (dataType*) malloc(size);

The malloc function returns a void pointer which is cast


(converted) to the required data type.
The sizeof() function gives the size of data types and has the
syntax,

sizeof(datatype)

Initialization of Character Array in C


There are different ways to initialize a character array in
c. Let us understand them with examples.

Using {} Curly Braces


We can use {} brackets to initialize a character array by
specifying the characters in the array.
The advantage of using this method is we don't have to specify
the length of the array as the compiler can find it for us.
Let us see a example where we initialize an array using {} and
print it.
#include <stdio.h>

64
FUNDAMENTALS OF COMPUTER PROGRAMMING

#include<string.h>
int main(){
//initialization
char char_array[] = {'c', 'h', 'a', 'r', '$','*'};
int a=puts(char_array); //print array
if(a>0){
printf("printed successfully\n");
}
printf("length of character array = %d",strlen(char_array));
//prints length of the character array.
return 0;
}
Output
char$*
printed successfully
length of character array = 6

2.14 STRING:
A String in C programming is a sequence of characters
terminated with a null character ‘\0’. The C String is stored
as an array of characters. The difference between a
character array and a C string is the string is terminated
with a unique character ‘\0’.

C String Declaration Syntax


Declaring a string in C is as simple as declaring a one-
dimensional array. Below is the basic syntax for declaring a
string.
char string_name[size];
In the above syntax str_name is any name given to the
string variable and size is used to define the length of the
string, i.e the number of characters strings will store.

65
FUNDAMENTALS OF COMPUTER PROGRAMMING

There is an extra terminating character which is


the Null character (‘\0’) used to indicate the termination of a
string that differs strings from normal character arrays.

C String Initialization
A string in C can be initialized in different ways. We
will explain this with the help of an example. Below are the
examples to declare a string with the name str and initialize
it with “GeeksforGeeks”.
Ways to Initialize a String in C

We can initialize a C string in 4 different ways which are


as follows:
1. Assigning a string literal without size
String literals can be assigned without size. Here, the
name of the string str acts as a pointer because it is an
array.
char str[] = "GeeksforGeeks";
2. Assigning a string literal with a predefined size
String literals can be assigned with a predefined size.
But we should always account for one extra space which will
be assigned to the null character. If we want to store a string
of size n then we should always declare a string with a size
equal to or greater than n+1.
char str[50] = "GeeksforGeeks";
3. Assigning character by character with size
We can also assign a string character by character.
But we should remember to set the end character as ‘\0’
which is a null character.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning character by character without size
We can assign character by character without size
with the NULL character at the end. The size of the string is
determined by the compiler automatically.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

------------------------------------UNIT II
COMPLETED---------------------------------

66

You might also like