0% found this document useful (0 votes)
2K views38 pages

Unit 1 FPL

Uploaded by

uzair63210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views38 pages

Unit 1 FPL

Uploaded by

uzair63210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

FPL:Unit-1 DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-18


Department of First Year Engineering
Fundamentals of Programming Languages
Unit- 1: Introduction to Program Planning & C Programming

Syllabus:

Program Design Tools: Art of Programming through Algorithms, Flowcharts.


Overview of C:History and importance C, Character Set, C Tokens, Keywords and Identifiers,
Constants, Variables, Data types, Declaration of variables, Storage Class, Assigning Values to
variables, Defining Symbolic Constants, declaring a Variable as Constant, Declaring a Variable as
Volatile.

1. Program Design Tools:

Program design is the process of creating a plan or a set of instructions for a


computer program that will enable it to solve a particular problem. This process involves a
number of tools that are used to help developers organize their thoughts and ideas, and to
make the process of writing code more efficient.

1.1 Art of Programming through Algorithm, Flowcharts:

The algorithm and flowchart are two types of tools to explain the process of a program.

1.1.1 Algorithm:

Definition of algorithm:

 An algorithm is precise, step-by-step set of instructions for solving a computational


problem.
 It is a set of ordered instructions which are written in simple English language.
 Algorithms help the programmer to write actual logic of a program on paper and
validate it with the help of paper and pencil, and correct it if any fault is noticed.
1
FPL:Unit-1 DIT,Pimpri

Characteristics of algorithms:

i) Finiteness : An algorithm should terminate in a finite number of steps.

ii) Definiteness : Each step of the algorithm must be precisely stated.

iii) Effectiveness : Each step must be effective, in the sense that it should be easily
convertible into program statement and can be performed exactly in a finite amount of time.

iv) Generality : The algorithm should be complete in itself so that it can be used to solve all
problems of a given type for any input data.

v) Input/Output : Each algorithm must take zero, one or more quantities as input data and
yield one or more output values.

Algorithm 1: Add two numbers entered by the user

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

Sum = num1+num2

Step 5: Display sum

Step 6: Stop

Algorithm 2: Calculate area of circle

Step 1:BEGIN

Step 2: Accept the R

Step3: Find the square of R and store it in

A = R*R

Step4: Multiply R with 3.14 and store the result in A

Step5 :Display the value of A

2
FPL:Unit-1 DIT,Pimpri

Step6: END

Algorithm 3: Swap two numbers

Step 1 : Start

Step 2 : READ num1, num2

Step 3 : temp = num1

Step 4 : num1 = num2

Step 5 : num2 = temp

Step 6 : PRINT num1, num2

Step 7 : Stop

Algorithm 4: Find largest number amongst three numbers

Step 1:BEGIN

Step2: Read values for NUM 1, NUM2 and NUM3

Step3: if NUM1>NUM2

Check if Num1>NUM3, if true then display NUM 1 is Largest no.

Else check if NUM2>NUM1

Check if Num2>NUM3 display NUM 2 is Largest no.

Else check if NUM3>NUM1

Check if Num3>NUM2 display NUM 3 is Largest no.

Step4: END

1.1.2 Flowchart:
 A Flowchart is a graphical representation of a Algorithm.
 The sequence of steps in algorithm is maintained and represented in the flowchart by
using some standard symbols such as rectangles and directed lines.
3
FPL:Unit-1 DIT,Pimpri

 As flowchart uses the pictorial representation of an algorithm, it becomes easier to


understand what is going on.
 One of the most common ways to express algorithm with writing a program is a
flowchart.

Symbols used in flowchart:

Start/stop/begin/end
Oval Terminal
symbol.
Making data available for
processing (input) or
Parallelogram Input/Output recording of the processed
information(output).

Any processing to be
performed. An assignment
Rectangle Process operation normally
represented by
this symbol.
Decision or switching type of
operations that determines

Diamond Decision which of the alternative paths


is to be
followed.
Used for connecting
Circle Connecter different parts of flow chart.

Joins two symbols and also


Arrow Flow represents executions flow.

4
FPL:Unit-1 DIT,Pimpri

Flowchart 1: Calculate area of circle.

Flowchart 2: Check whether a given number is even or odd.

2. Overview of C:

2.1 History and importance of C:

2.1.1 History:

C is a programming language developed at AT& T’s Bell Laboratories of USA


in 1972.It was designed and written by Dennis Ritchie. C has the features of both
BASIC and PASCAL. As a middle language, C allows the manipulation of bits, bytes

5
FPL:Unit-1 DIT,Pimpri

and addresses the basic elements with which computer functions.


Evolution of C:

 An International Committee Developed ALGOL 60 Language.

 Which Is Used To Program All Type Of Applications Such As Commercial


Applications, Scientific Applications, And System Applications And So On.

 ALGOL 60 Never Became Popular Because It Was Too Abstract And Too General.

 To Reduce This Abstractness And Generality, A New Language Called Combined


Programming Language (CPL) Was Developed At Cambridge University.

 CPL Turned Out To Be So Big, Having So Many Features, This It Was Hard To
Learn And Difficult To Implement.

 Basic Combined Programming Language (BCPL), developed by Martin Richards at


Cambridge University to solve the problems of CPL.

 It is less powerful and too specific.

 Around same time a language called “B” was written by Ken Thompson.

 But like BCPL, B is also too specific.

 Finally Dennis Ritchie inherited the features of B and BCPL, added some of his own
stuff and developed “C”.

Fig. 2.1 History of ANSI C

6
FPL:Unit-1 DIT,Pimpri

2.1.2 Importance of C:
1) It is a robust language, whose rich set of built-in functions and operators can
be used to write any complex program.
2) Programs written in C are efficient and fast. This is due to its variety of data
types and powerful operators.
3) C’s code is very portable, in the sense that it is easy to adapt software
written for one type of computer or operating system to another type.
4) C has very small key words (only 32). Its strength lies in its built-in
functions. These built-in functions can be used for developing programs.
5) C language is well suited for structured programming, thus requiring the
user to think of a problem in terms of functions (or) blocks.
6) A proper collection of these functions would make a complete program.
This modular structure makes program debugging, testing and maintenance
easier.
7) Another important feature of C is its ability to extend itself.

Basically a C program is a collection of functions that are supported by the C library. We


can add our own functions to the C library. With the availability of a large number of
functions, the programming task becomes simple.

2.1.3 Simple ‘C’ Program:

Before discussing any features of C, we shall look at some sample C program and analyze
and understand how they work.

Ex 1: C program to print a message.

#include <stdio.h>

int main() {

printf("Welcome to DIT\n");

return 0;

Explanation:
i) #include <stdio.h>: This line includes the Standard Input Output header file,
7
FPL:Unit-1 DIT,Pimpri

which is necessary for using all important functions like printf.


ii) main():
• main()’ is a special function used by the C system to tell the computer
where the program starts.
• Every program must have exactly one main function.
• Opening brace ‘{‘ and closing brace ‘}’ are the delimiters of any function.
• All the statements between these two braces are called as function body.
• The lines beginning with /* and ending with */ are known as comment
lines. These lines are not executable statements and therefore anything
between /* and */ is ignored by the compiler.
iii) printf() function:
• printf is a predefined, standard C function for printing output.
• ‘Predefined’ means that it is a function that has already been written and
compiled, and linked together with our program at the time of linking.
• The printf function causes everything between the starting and the ending
quotation marks to be printed out.
In the above example, the output will be

Welcome to DIT

iv) return 0 : This statement terminates the main function and returns the value 0 to
the operating system, indicating that the program ended successfully.
v) Every statement in C should end with a semicolon(;) mark.

Format of a simple C program:

main() -------------------  function name

{---------------------------  starting of the program

- ------------------------  program statements

-------

}  ending of the program

8
FPL:Unit-1 DIT,Pimpri

Program development steps:

The following steps are used in sequence for developing an efficient program:

 Specifying the problem statement

 Designing an algorithm

 Coding

 Debugging

 Testing and validating

 Documentation and maintenance

Program execution steps:

 Creating the program (or) typing the program.

 Compiling the program (short-cut key- Alt+F9)

 Linking the program with functions that are needed from the C library.

 Running the program (short-cut key-- Ctrl +F9)

2.1.4 Features of C languages:

1. Efficiency: C is designed to be efficient in terms of both execution time and memory


usage. It provides low-level access to memory and system resources, which allows for
fine-tuned optimization.

2. Portability: C programs can be compiled and run on various platforms with little or no
modification, making it a highly portable language. The standard library functions ensure
consistency across different environments.

3. Speed: C is known for its high execution speed. Because it is a compiled language and
offers low-level access to memory, it is often used in performance-critical applications.

4. Control: C provides a high level of control over system resources, such as memory
management, file handling, and I/O operations. This allows programmers to write highly
efficient code and directly manage the hardware.

9
FPL:Unit-1 DIT,Pimpri

5. Capability: C is a powerful language that can be used to write operating systems,


compilers, and complex applications. Its ability to directly interact with hardware and
system resources makes it a versatile choice for many types of software development.

2.1.5 Applications of the C programming language:

1. Operating Systems:

C is the backbone of many operating systems like UNIX and Linux. Its ability to work
closely with hardware makes it ideal for building and maintaining operating systems.

2. Embedded Systems:

C is commonly used in embedded systems, which are found in everyday devices like
microwaves, TVs, and car engines. It’s chosen for its efficiency and direct hardware
control.

3. Game Development:

C is used to develop game engines and performance-critical parts of video games. Its
speed allows for smooth gameplay and complex graphics handling.

4. Compilers and Interpreters:

Many compilers and interpreters, including those for the C language itself, are written in
C. This is because C allows precise control over memory and processing.

5. Databases:

C is used to create database management systems like MySQL. Its efficiency helps
manage large amounts of data effectively.

6. Network Programming:

C is used to develop network drivers, protocols, and tools. It’s well-suited for network
programming because it allows fine control over data and memory management.

2.2 Character Set:

Character set refers to a set of all the valid characters that we can use in the source

10
FPL:Unit-1 DIT,Pimpri

program for forming words, exepressions and numbers. The characters in C are grouped
into four categories.
1. Letters a, b, c, ……………z

2. Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

3. Special characters ~ , . ; : ? ‘ “ ! () [ ] { } / \ < > = + - $ # @ & * % ^

4. white spaces

With these characters are combined to form data types, constants, variables and key words.

Table 2.1 C Character Set


1)Letters 2)Digits
Uppercase All decimal
A…….Z digits 0…9
Lowercase
a……z

4)White Spaces

11
FPL:Unit-1 DIT,Pimpri

Blank space
Horizontal tab
Carriage return
New line
Form feed

2.3 C Tokens:

 A token is an atomic unit (smallest indivisible units) in a program.


 The most basic elements in a C program recognized by the compiler are a single
character or a group of characters called C tokens.
 The compiler cannot breakdown the token any further.
 For example, the words main, ‘{‘ (brace), ‘(‘ (parenthesis) are all tokens of C
program.

Types of tokens:

Fig. 2.2 C tokens and examples

12
FPL:Unit-1 DIT,Pimpri

2.4 Keywords and Identifiers:

In ‘C’ every word is classified into either a key word or an identifier. All key
word have fixed meaning cannot be changed. Keywords serve as a basic building block
for program statements. All the keywords must be written in lower case.
2.4.1 Keywords:
 Keywords are predefined tokens in C. These are also called reserved words.
 Key words have special meaning to the C compiler. These key words can be used
only for their intended action; they cannot be used for any other purpose.
 C has 32 keywords.
 Standard key words:

Table 2.1 ANSI C Keywords


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for Signed void
default goto sizeof volatile
do if static while

2.4.2 Identifiers:

Identifiers refer to the names of the variable, function and arrays. These are user
defined names and consists of sequence of letters and digits.

Rules for giving name to an identifier:

1. First character must be an alphabet (or Underscore).


2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.

4. Cannot use a keyword.

13
FPL:Unit-1 DIT,Pimpri

5. Must not contain white space.

Q. Diffrence between Keyword and Identifier

Keywords Identifires
An Identifier is a unique name
1. Keywords are related words with a
created by the programmer to
definite, predetermined meaning .
define a variable, structure, class,
Any programme statement may be
or function.
defined with the aid of keywords.
The initial character in the
2. A keyword always starts in
Identifier can be capitalized,
lowercase.
lowercase or starts with
underscore.
It can have numbers, alphabetical
3. It can only have alphabetical
characters and underscores.
characters.
5. Examples of IDs are test, count1,
4. Examples of keywords are double,
high speed etc.
int, auto, char, break and many
others.

2.5 Constants:

 Constants are fixed values that do not change during the execution of program.

 For example in the equations 5x+2y=45 since 5, 2 and 45 cannot change , these are called
constants, where as the quantity X&Y can vary or change hence these are called variables .

Several types of constants are:

14
FPL:Unit-1 DIT,Pimpri

Fig. 2.3 C Basic types of C constants

Numeric constants:

Integer constants: It refers to a sequence of digits, it has to fallow the below rules:

1. Integer constants must have at least one digit.

2. It must not have a decimal point.

3. It could be either positive or negative.

4. If no sign precedes an integer constant it is assumed to be positive.

5. No commas, blank space are allowed.

6. The allowable range for integer constants is -32768 to +32767 (16-bit machine).

7. Integer constants are further divided into three types as:

i) decimal

ii) octal

iii) hexadecimal

15
FPL:Unit-1 DIT,Pimpri

i) A decimal integer constant:

It consists of sequence of one or more decimal digit 0 through 9 preceded by an


optional – (or) + sign. The first digit of the sequence cannot be 0 unless the decimal
integer constant is 0.
Ex: 0 276 3412 31467 -7123

Note: Embedded spaces, commas, and non-digit characters are not permitted between
digits.
Ex: 12 727 23,879 $1772 are illegal numbers.

ii) An Octal Integer constant: It consists of any combination of digits from the set 0
through 7,with a leading 0.
Ex: 012 07134 07777

iii) A hexadecimal integer constants:

It consists of the digit 0, followed by one of the letter x (or) X, followed by a


sequence of one more hexadecimal digits 0 through 9 or letter a through f (or) A
through F represent the numbers 10 through 15.
Ex: 0X1F
Note: we rarely use octal and hexa decimal numbers in programming.

Real Constants:
• A real constants are sequence of digits with a decimal point(fractional part) like
45.382.Such numbers are called real(or floating point) constants.
• Integer numbers are inadequate to represent quantities that vary continuously
,such as distances, heights, temperatures, prices etc.

Rules for constructing Real Constants:


 An integer constant must have at least one digit.
 It should not contain either a decimal point or exponent.
 If a constant is positive, it may or may not be preceded by a
 plus sign. If it is a negative, it must be preceded by a minus sign.
 Commas, blanks and non-digit characters are not allowed in
integer constants.

16
FPL:Unit-1 DIT,Pimpri

 The value of integer constant cannot exceed specified limits.


 The valid range is –32768 to +32767.
Ex: 1.0 1. 0.712 34.576 - 7.123
These numbers are shown in decimal notation, having a whole number fallowed
by a decimal point. It is possible to omit digits before the decimal point or digits after
the decimal point.
Ex: 215. .39 -.92 +5. are valid real numbers.

The real numbers may also be expressed in exponential (or, scientific)


notation. For example, the value 215.65 may be written as 2.1565e2 in exponential
notation. e2 means multiply by 10

The general form:

mantissa e exponent

 The mantissa is either a real number expressed in decimal notation or an


integer.
 The exponent is an integer number with an optional + or – sign.

 The letter e separating the mantissa and the exponent can be written
in either lowercase or uppercase
The scientific notation is often used to express numbers that are either very small or
very large.
Ex: 7500000000 may be written as 7.5e9 or 75e8.

Similarly, -0.000000368 is equivalent to -3.68e-7.


(Coefficient) e (integer) = (coefficient) * 10(integer)

Character constant:

Single character constants:

 A single character constant is a single alphabet, a single digit or a single special


symbol enclosed with in a pair of single quote marks.

 Ex: ‘5’ ‘X’ ‘;’ ‘’

17
FPL:Unit-1 DIT,Pimpri

 The maximum length of a character constant can be one character constant.

 Character constants have integer values known as ASCII values.

 Lets take an example,

printf(“%d”, ‘a’);

would print the number 97, the ASCII value of the letter a.
 Similarly,
printf(“%c”, ‘97’)
would output the letter ‘a’.

String constant:
 A string constant is a sequence of characters enclosed in double quotes.
 The characters may be letters, numbers, blank space or special characters.
 Note that “ ” is null string or empty string. And the single string constant “A” is
not equivalent to the single character constant ‘A’.
 Each string constant must end with a special character ‘\o’. This character is called
null character and used to terminate the string. The compiler automatically places a
null character ‘\o’ at the end of every string constant.
Ex: ”hello” “1999” “5+4+6” “good bye”

Backslash character constants:

C supports some special backslash character constants that are used in output
functions. Each one of them represents one character, although they consist of two
characters. These character combinations are known as escape sequences.

Table 2.2 Backslash Character Constants

18
FPL:Unit-1 DIT,Pimpri

2.6 Variables:
 A variable is a data name which can be used to store a data value.
 A variable may take different values at different times, during execution.
 Syntax:

Data_type variable_name = value

Ex. int var; // Integer variable


char a // Character variable
float f // Float variable

 Let’s take an example in the equation, 7x+4y=30 since 7, 4 and 30 cannot


change , these are called constants, whereas the quantity X&Y can vary or
change hence these are called variables.
 A variable name can be chosen by programmer in a meaningful way to reflect
function or nature of program. Such as
Average
height
Total
class_strength
19
FPL:Unit-1 DIT,Pimpri

Rules for constructing variable names:

1. Variable name must begin with a letter.

2. A variable name is any combination of alphabets, digits and the


underscore character.

3. ANSI standard recognizes a length of 31 characters. However, the length


should not be normally more than 8 characters, since only the first 8
characters are treated as significant by many compilers.
4. The first character in the variable name must be an alphabet.

5. No commas or blank spaces allowed.

6. No special symbol other than an underscore can be


used

Ex: bas_pay, net_salary, month etc.


7. Uppercase and lowercase are significant. That is, the variable Amount
is not the same as amount or AMOUNT.
8. Variables name should not be a keyword.

Table 2.2 Backslash Character Constants


Variable name Valid??? Remark
First_tag Valid
char Invalid char is a keyword
Price$ Invalid Dollar sign is illegal
Group one Invalid Blank space is not permitted
average_number Valid First eight characters are significant
Int_type Valid Keyword may be a part of name

20
FPL:Unit-1 DIT,Pimpri

Q. Difference between constants and variables.


Constants Variables
1. A constant does not change its value A variable , on the other hand,
as the equation is solved. changes its value depending on the
equation.
2. Constants are usually written in Variables are written as letters or
numbers(whether fractions, Integers, symbols.
Decimals or Real numbers).
3. Constants usually represent the Variables, on the other hand,
known values in an equation or represent unknown values.
expression.
4. Constants have fixed face values. Variables do not a fixed face value.

2.7 Data Types:

• A Data type is a Type of Data.

• Data type is a data storage format that can contain a specific type or range of
values.

• Data types in C refer to an extensive system used for declaring variable for
function of different types.

• Each data type has predetermined memory requirement and an associated range of
legal values.
ANSI C supports three classes of data types.

1. Primary (or fundamental) data types

2. Derived data types/Secondary data types

3. User-defined data types

21
FPL:Unit-1 DIT,Pimpri

Fig. 2.4 C Data types in C

1. Primary data types:

All C compilers support four fundamental data types, namely


integer(int), character(char),floating point(float), and double-precision floating
point(double) and void. Various data types and their terminology used to describe
them are given in below fig 2.4.

22
FPL:Unit-1 DIT,Pimpri

Fig. 2.4 Primary data types in C

Integer Types

 Integers are the whole numbers with a range of values supported by a particular
machine.

 Integers occupy one word of storage, but as the word sizes of machine vary(16 bits
or 32 bits) the size of an integer depends on the computer.

 For 16 bit word length, the size of integer value range between -32768 to +32767

(-215 to +215 -1) and for a 32 bit word length range is -2,147,468 to 2,147,468,647.

 A signed integer uses one bit for sign and 15 bits for magnitude of a number.

 C provides three different types of integers they are int, short int and long int in
both signed and unsigned forms. The difference between these three integers is

23
FPL:Unit-1 DIT,Pimpri

the number of bytes.

short int

int

long int
Fig. 2.5 Integer Types

 short int represents fairly small integer values and requires half the amount of
storage than regular int number uses.

 To increase the range of values we have to declare long and unsigned integers.

Table 2.4 Size and range of Data Types on a 16 bit machine


Type Size(bits) Range
char or signed char 8 -128 to 127
unsigned char 8 0 to 255

int or signed int 16 -32,768 to 32,767

unsigned int 16 0 to 65535


short int or signed short 8 -128 to 127
int
unsigned short int 8 0 to 255

long int or signed long 32 -2,147,468 to 2,147,468,647


int
unsigned long int 32 0 to 4,294,967,295

float 32 3.4E – 38 to 3.4E + 38

double 64 1.7E – 308 to 1.7E + 308

long double 80 3.4E – 4932 to 1.1E + 4932

24
FPL:Unit-1 DIT,Pimpri

Floating Point Types:

 Like integers floats are divided into three types. They are float, double and long
double.

 The difference between these three floats are the number of bytes, the variable of
these types occupy and subsequently the range of values.

 A floating point (or real ) numbers are stored in 32 bits(on both 16bit and 32 bit
machine) with 6 digits of precision.

short
floatint

double

long double

Fig. 2.6 Floating-point Types

Table 2.5 Size and range:


Type Description Size(bytes) Range
Float Single precession 4 3.4E-38 to 3.4E+38

Double Double precession 8 1.7E-308 to 1.7E+308

Long double Extended precession 10 3.4E-4932 to 3.4E+4932

Character Types:

 A char is a data type which can store an element of machine character set.

 A single character can be defined as a character (char) type data.

 Characters are usually stored in 8 bits (1 byte) of internal storage. The


character set is usually the ASCII.

 These are two types, they are signed and unsigned characters. The

25
FPL:Unit-1 DIT,Pimpri

differences between these two types are the range of values. Both will occupy
one byte.

 Signed chars have values between -128 to 127 and unsigned chars have
values 0 to 255.

Void Types:

 The void type has no values.

 This data type is usually used to specify the type of functions.

 It does not return any value to the calling function.

2.User-defined data type:

 The users can define an identifier that represent an existing data type by a feature
known as “type definition”.

 The user defined data type identifier can later be used to declare variables.

General form:

typedef type identifier;

where type refers to an existing data type and identifier refers to the new name given
to the data type.

Ex:
typedef int Sno;
typedef float salary;
Here Sno symbolizes int and salary symbolizes float. These can be used to
declare variables as follows:
Sno c1,c2;
salary e1,e2;
Note: The main advantage of typedef is that we can create meaningful data type names for
increasing the readability of the program.

26
FPL:Unit-1 DIT,Pimpri

Another user defined data type is enumerated data type provided by ANSI .
General form:

enum identifier {value 1, value 2, ……, value n};

The “identifier” is a user-defined enumerated data type which can be used to


declare variables that can have one of the values enclosed within the braces. After that
we can declare variables to be of this new type.
enum identifier v1, v2, ….vn;

the enumerated variables v1, v2, …..vn can only have one of the value 1, value 2, ……
value n.
Ex 1:

enum month {January, February,….December};

enum month month_st, month_end;


(or)

enum month {january, february, …., December} month_st, month_end;

Here the declaration and definition of enumerated variables can be combined in


one statement.
Ex 2:

enumday{Monday,Tuesday……Sunda};
enumday week_st, week_end;
week_st=Monday;
week_end=Friday;
if(week_st==Tuesday)
week_end=Saturday;

The compiler automatically assigns integer digits beginning with 0 to all the
enumeration constants. That is, the enumeration constant Monday is assigned with 0,
Tuesday is assigned with 1 and so on. However, the automatic assignments can be
overridden by assigning values explicitly to the enumeration constants.

For example,

27
FPL:Unit-1 DIT,Pimpri

enum day {Monday=1,Tuesday, ……., Saturday};

here, the constant Monday is assigned the value 1.The remaining constants
are assigned values that increases successively by 1.

3.Derived data types


There are some derived data types which are supported by C such as arrays,
functions, structures, and pointers.

2.8 Declaration of variables:

Declaration does two things:

1. It tells the compiler what the variable name is.

2. It specifies what type of data the variable will hold.

The declaration of variables must be done before they are used in the program.

Primary Type Declaration:

 A variable can be used to store a value of any data type.


 The syntax for declaring a variable is as follows:

data-type v1,v2,…….,vn;

 v1,v2,…,vn are the names of variables. Variables are separated by commas.

 A declaration statement must end with a semicolon.

For example , valid declarations are:

int count;

int number, total;

double ratio;

28
FPL:Unit-1 DIT,Pimpri

Here, int and double are the keywords to represent integer type and real type data
values respectively.

The program statement given infollowing fig 2.7 illustrates declaration of variables.

main() /*…………….Program Name……………..*/


{
/*……………….Declaration…………………………..*/
float x,y;
int code;
short int count;
long int amount;
double deviation;
unsigned n;
char c;
/*…………………………Computation…………………………*/
. . .
. . .
. . .
} /*…………………………Program ends…………………..*/

Fig. 2.7 Declaration of variables


Here,
 main() is the beginning of the program.
 The opening brace { signals the execution of program.
 Declaration of variables is done immediately after opening brace of program.

2.9 Storage Class:

 Every variable that we declare in a C program has its scope and lifetime.
 Storage class in C provides information about the location and visibility of variables.
 It determines the portion of the program within which the variables are recognized.

29
FPL:Unit-1 DIT,Pimpri

Lets take an example:

/* Example of storsge classes */


int m; // Global variable
main()
{
int i; // Local variable
float balance; // Local variable
. . . .
. . . .
function1();
}
function1()
{
int i; // Local variable
float sum; // Local variable
. . . .
. . . .
}

Fig. 2.8 Declaration of storage class


Here,
 The variable m which has been declared before main function is called global
variable.
 It is accessible in all functions within the program.
 A global variable is also known as an external variable.
 The variables i, balance, sum are called as local variables because they are declared
inside functions.
 The variable i has been declared in both functions but are independent of each other.
 Any change in value of i in one function does not affect its value in other function.

30
FPL:Unit-1 DIT,Pimpri

Q. Difference between Local variable and global variable:

Global Variable Local Variable

1. Global variables are declared Local Variables are declared within a


outside all the function blocks. function block.

2. The scope remains throughout The scope is limited and remains within
the program. the function only in which they are
declared.

3. Any change in global variable Any change in the local variable does not
affects the whole program, affect other functions of the program.
wherever it is being used.

4. A global variable exists in the A local variable is created when the


program for the entire time the function is executed, and once the
program is executed. execution is finished, the variable is
destroyed.

5. It can be accessed throughout the It can only be accessed by the function


program by all the functions statements in which it is declared and not
present in the program. by the other functions.

6. If the global variable is not If the local variable is not initialized, it


initialized, it takes zero by takes the garbage value by default.
default.

7. Global variables are stored in the Local variables are stored in a stack in
data segment of memory. memory.

8. We cannot declare many We can declare various variables with the


variables with the same name. same name but in other functions.

31
FPL:Unit-1 DIT,Pimpri

Storage Class Specifiers:


C provides four storage class specifiers to explicitly declare the scope and lifetime of
variables.

Table 2.6 Storage Classes and their Meaning:

Storage Scope,
Name Memory Lifetime
Class Default Value

Within the same function


Internal Local Scope,
auto Automatic or block in which they are
Memory Garbage Value
declared.

Within the same function


register Register Register Local Scope, 0 or block in which they are
declared.

Within the program i.e., as


Internal
static Static Local Scope, 0 long as program is
Memory
running.

Within the program i.e., as


Internal
extern External Global Scope, 0 long as program is
Memory
running.

2.10 Assigning values to variables:

Basic Assignment

 Values can be assigned to variables using the assignment operator ‘=’ as follows:
Syntax:

variable_name = constant;

32
FPL:Unit-1 DIT,Pimpri

 Examples of Simple Assignments


o initial_value = 0;
o final_value = 100;
o balance = 75.84;
o yes = 'x';
 C permits multiple assignments on one line also:
o For example:
initial_value = 0; final_value = 100;
 An assignment statement implies that the value of the variable on the left of the 'equal
sign' is set equal to the value of the quantity (or the expression) on the right. The
statement
year = year + 1;
means that the 'new value' of year is equal to the 'old value' of year plus 1.
 During assignment operation, C converts the type of value on the right-hand side to
the type on the left.
 It is also possible to assign a value to a variable at the time variable is declared.
This takes following form:

data-type variable_name = constant:

For example:
int final_value = 100;
char x = 'x';
double balance = 75.84;
 The process of giving initial values to variables is called initialization.
C permits the initialization of more than one variable in one statement using
multiple assignment operators.
For example:
p=q=s=0

x = y =z = MAX

33
FPL:Unit-1 DIT,Pimpri

Reading Data from Keyboard:

 Another way of giving values to variables is to input data through keyboard using
function “scanf”.
 The scanf function is used to input data from the keyboard in C.

scanf("control string", &variable1, &variable2,...);

 The control string specifies the format of the data being received.
 The & symbol before each variable name specifies the variable's address.
 For example: scanf("%d", &number);
 When the scanf statement is executed, it waits for input.

main()

int number;

printf(“Enter an integer number”)

scanf(“%d”, & number);

if (number < 100 )

printf (“Your number is smaller than 100\n\n”);

else

printf (“Your number contains more than two digits\n”);

Output

Enter an integer number

54

Your number is smaller than 100

Fig. 2.9 Use of scanf function for interactive computing

34
FPL:Unit-1 DIT,Pimpri

2.11 Defining Symbolic Constants:

 Unique constants refer to specific, unchanging values that are consistently used
throughout a program, such as the value of pi (3.142) or the number of students (50).
 These constants ensure that important values remain consistent and accurate wherever
they appear in the code.
 Using unique constants helps in maintaining clarity and simplifying the process of
updating values, thereby improving code reliability and maintenance.

Problems Addressed by Symbolic Constants

1. Modifiability:

 When constants are used directly in multiple places within a program,


modifying them later becomes error-prone.
 Changing a constant value like pi from 3.142 to 3.14159 or the number of
students from 50 to 100 requires searching through the entire codebase and
updating each occurrence.
 Missing even a single instance can lead to incorrect program behavior.

2. Understandability:

 Numeric values in code can be ambiguous, making the code difficult to


understand and maintain.
 The same numeric value might have different meanings in different contexts
(e.g., 50 as the number of students and 50 as the pass marks).
 Revisiting code after some time may lead to confusion regarding the purpose
of specific numeric values.

Using #define to Define Symbolic Constants

The #define pre-processor directive is used to create symbolic constants. This makes the code
more readable and easier to maintain. Here are the rules and conventions for using #define:

1. Naming Conventions:
 Symbolic names should follow the same rules as variable names but are
typically written in uppercase letters to distinguish them from regular variables.
2. Syntax Rules:

35
FPL:Unit-1 DIT,Pimpri

 The # character must be the first character on the line.


 No blank space is allowed between # and define.
 A blank space is required between #define, the symbolic name, and the
constant value.
 #define statements should not end with a semicolon.
 After a symbolic name is defined, it should not be reassigned using an
assignment statement within the program.
 Symbolic names are not declared with data types; their type is inferred from
the constant value.
 #define statements should appear before they are referenced in the program,
usually at the beginning of the program.

Invalid #define Statements

Here are examples of invalid #define statements and explanations for their invalidity:

Statement Validity Remark


#define X=2.5 Invalid '=' sign is not allowed
# define MAX 10 Invalid No white space between # and define
#define N 25; Invalid No semicolon at the end
#define N 5, M 10 Invalid A statement can define only one name
#Define ARRAY 11 Invalid define should be in lowercase letters
#define PRICES $100 Invalid $ symbol is not permitted in name

Valid Examples

Here are some valid examples of defining symbolic constants using #define:

#define STRENGTH 100


#define PASS_MARK 50
#define MAX 200
#define PI 3.14159

36
FPL:Unit-1 DIT,Pimpri

2.12 Declaring a Variable as Constant:

 We may like the value of certain variables to remain constant during the execution of
a program. We can achieve this by declaring the variable with the qualifier `const` at
the time of initialization.
 Syntax for `const` declaration:

const data_type variable_name = value;

 Example: `const int class_size = 40;`


 `const` is a new data type qualifier defined by the ANSI standard. This tells the
compiler that the value of the `int` variable `class_size` must not be modified by the
program.
 However, it can be used on the right-hand side of an assignment statement like any
other variable.

Advantages

1. Prevents Modification: Ensures the value remains constant, preventing accidental


changes.
2. Improves Clarity: Makes the code more readable and maintainable.
3. Optimizations: Allows the compiler to optimize the code better.

2.13 Declaring a Variable as Volatile:

 The `volatile` qualifier informs the compiler that a variable's value may be
changed at any time by external sources (outside the program).
 Syntax :

volatile data_type variable_name;

Example: `volatile int date;`


 When a variable is declared as `volatile`, the compiler will re-evaluate its
value each time it is encountered to check for any external alterations.
 A variable declared as `volatile` can still be modified by the program itself.
 Syntax for constant and volatile declaration:

volatile const data_type variable_name = value;


37
FPL:Unit-1 DIT,Pimpri

Example: `volatile const int location = 100;`

This ensures that the variable's value cannot be modified by the program but
may be altered by some other process.

Here,

• volatile Keyword: Ensures the compiler checks the variable's value each time it is
accessed, accounting for possible external modifications.
• Combination with const: Prevents the program from modifying the variable, while
still allowing external changes.

38

You might also like