0% found this document useful (0 votes)
38 views32 pages

Fe FPL Unit1

Uploaded by

ihavecrush55
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)
38 views32 pages

Fe FPL Unit1

Uploaded by

ihavecrush55
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/ 32

First Year of Engineering (2024 Pattern) Course Code: ESC-105-

COM Course Name: Fundamentals of Programming Languages


Teaching Scheme Credit Examination Scheme
Theory : 2 Hours/Week Practical : 2 Hours/Week

CCE : 30 Marks End – Semester : 70 Marks Term Work : 25 Marks

Unit -I

Introduction to Program Planning & C Programming :(06 Hours)


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.

Program Design Tools: Art of Programming through Algorithms,


Flowcharts

The algorithm and flowchart are two types of tools to explain the process of a program. Algorithms
and flowcharts are two different tools that are helpful for creating new programs, especially in
computer programming. An algorithm is a step-by-step analysis of the process, while a flowchart
explains the steps of a program in a graphical way.

Definition of Algorithm
Writing a logical step-by-step method to solve the problem is called the algorithm. In other
words, an algorithm is a procedure for solving problems. In order to solve a mathematical or
computer problem, this is the first step in the process.
An algorithm includes calculations, reasoning, and data processing.

A flowchart is the graphical or pictorial representation of an algorithm with the help of


different symbols, shapes, and arrows to demonstrate a process or a program. With
algorithms, we can easily understand a program. The main purpose of using a flowchart is to
analyze different methods. Several standard symbols are applied in a flowchart:
Common Abbreviations Used :
Terminal Box - Start / End

Input / Output

Process / Instruction

Decision

Connector / Arrow

The symbols above represent different parts of a flowchart. The process in a flowchart can
be expressed through boxes and arrows with different sizes and colors. In a flowchart, we
can easily highlight certain elements and the relationships between each part.

Difference between Algorithm and Flowchart


If you compare a flowchart to a movie, then an algorithm is the story of that movie. In other
words, an algorithm is the core of a flowchart. Actually, in the field of computer
programming, there are many differences between algorithm and flowchart regarding
various aspects, such as the accuracy, the way they display, and the way people feel about
them. Below is a table illustrating the differences between them in detail.
Algorithm
• It is a procedure for solving problems.
• The process is shown in step-by-step instruction.
• It is complex and difficult to understand.
• It is convenient to debug errors.
• The solution is showcased in natural language.
• It is somewhat easier to solve complex problem.
• It costs more time to create an algorithm.
Flowchart
• It is a graphic representation of a process.
• The process is shown in block-by-block information diagram.
• It is intuitive and easy to understand.
• It is hard to debug errors.
• The solution is showcased in pictorial format.
• It is hard to solve complex problem.
• It costs less time to create a flowchart.

Types of Algorithm(just for extra knowledge not the syllabus topic):


Despite the complexity of algorithms, we can generally divide algorithms into six fundamental types
based on their function.

#1 Recursive Algorithm

It refers to a way to solve problems by repeatedly breaking down the problem into sub-problems of
the same kind. The classic example of using a recursive algorithm to solve problems is the Tower of
Hanoi.

#2 Divide and Conquer Algorithm

Traditionally, the divide and conquer algorithm consists of two parts: 1. breaking down a problem
into some smaller independent sub-problems of the same type; 2. finding the final solution of the
original issues after solving these more minor problems separately.

#3 Dynamic Programming Algorithm

Developed by Richard Bellman in the 1950s, the dynamic programming algorithm is generally used
for optimization problems. In this type of algorithm, past results are collected for future use. Like the
divide and conquer algorithm, a dynamic programming algorithm simplifies a complex problem by
breaking it down into some simple sub-problems. However, the most significant difference between
them is that the latter requires overlapping sub-problems, while the former doesn’t need to.

#4 Greedy Algorithm

This is another way of solving optimization problems – greedy algorithm. It refers to always finding
the best solution in every step instead of considering the overall optimality. That is to say, what he
has done is just at a local optimum. Due to the limitations of the greedy algorithm, it has to be noted
that the key to choosing a greedy algorithm is whether to consider any consequences in the future.

#5 Brute Force Algorithm

The brute force algorithm is a simple and straightforward solution to the problem, generally based
on the description of the problem and the definition of the concept involved. You can also use "just
do it!" to describe the strategy of brute force. In short, a brute force algorithm is considered as one
of the simplest algorithms, which iterates all possibilities and ends up with a satisfactory solution.

#6 Backtracking Algorithm
Based on a depth-first recursive search, the backtracking algorithm focusing on finding the solution
to the problem during the enumeration-like searching process. When it cannot satisfy the condition,
it will return "backtracking" and tries another path. It is suitable for solving large and complicated
problems, which gains the reputation of the "general solution method". One of the most famous
backtracking algorithm example it the eight queens puzzle.)

Use Flowcharts to Represent Algorithms

Example.1 ADDITION OF TWO NUMBERS

Aim:

To write a C Program for addition of two numbers.

Algorithm:

STEP 1: Start the program.

STEP 2: Read the values of ‘a’&’b’.

STEP 3: Compute the sum of the entered numbers ‘a’,’b’,c=a+b.

STEP 4: Print the value of ‘c’.

STEP 5: Stop the program.

Pseudo code:

BEGIN

READ ‘a’&’b’

COMPUTE c=a+b

WRITE ‘c’

END

Flow chart:
Example 2: Print 1 to 20:

Algorithm:

• Step 1: Initialize X as 0,

• Step 2: Increment X by 1,

• Step 3: Print X,

• Step 4: If X is less than 20 then go back to step 2.

Flowchart:
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)

Algorithm:

• Step 1: Read temperature in Fahrenheit,

• Step 2: Calculate temperature with formula C=5/9*(F-32),

• Step 3: Print C.
Flowchart:

Example 3: Determine Whether A Student Passed the Exam or Not:

Algorithm:

• Step 1: Input grades of 4 courses M1, M2, M3 and M4,

• Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4"

• Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".
Flowchart:

➢ Overview of C:
What is the C Language?

The C programming language is a general-purpose middle level language developed by Dennis


Ritchie at Bell Labs in the 1970s. It was intended to be a low-level language that provided direct
access to hardware and system resources, making it highly efficient and flexible. Due to its simplicity
and elegance, C has become the building block for many other programming languages.

History of C Language

The C programming language’s history can be traced to Dennis Ritchie, who developed it at Bell Labs
in the early 1970s. It evolved from an earlier language called B, which was developed by Ken
Thompson. B itself was based on the BCPL language.

C gained popularity due to its portability and efficiency. In 1978, Brian Kernighan and Dennis Ritchie
published “The C Programming Language,” which became the go-to reference for C programmers.
Since then, C has been widely used and has influenced the development of other programming
languages.

Application of C Programming Language

C programming language finds its application in various domains, including:

o Operating systems: C is extensively used in developing operating systems like Windows,


Linux, and macOS.

o Embedded systems: C is the language of choice for developing firmware and software for
various embedded systems, such as microcontrollers and IoT devices.

o System Utilities: Many system utilities, such as text editors, compilers, and interpreters, are
written in C.

o Game development: C is used to develop games due to its ability to handle complex
calculations and graphics.

o Database systems: The core components of databases and their management systems are
often built using C.

o Networking: C is used for developing network protocols and applications.

Importance of C programming language over other languages

C programming language offers several advantages over other programming languages, including:

o Efficiency: C allows for direct memory manipulation and low-level access to system
resources. This results in highly efficient code execution.

o Portability: C code can be easily ported to different platforms without major modifications,
thanks to its wide availability of compilers and libraries.

o Speed: C is known for its fast execution speed, making it suitable for developing
performance-critical applications.

o Control: C gives programmers fine-grained control over memory management and system
resources.

o Compatibility: C code can be easily integrated with code written in other languages like C++,
Java, and Python.

Advantages of C Programming Language

Apart from the benefits mentioned above, there are several advantages of using C programming
language, including:

o Modularity: C supports modular programming, allowing developers to break down complex


programs into smaller, manageable modules for easier development and maintenance.

o Wide community support: C has a large and active development community, making it easy
to find resources, libraries, and support online.

o Skill transferability: Once you learn C, it becomes easier to learn other programming
languages since many languages, including C++, are based on C.
Disadvantages of C Programming Language

While C programming language offers many advantages, it also has some disadvantages, including:

o Complexity: C can be difficult to learn for beginners due to its low-level nature and the need
to understand concepts like pointers and memory management.

o Lack of safety features: C does not have built-in features like garbage collection, which can
lead to memory leaks and other runtime errors if not managed properly.

o Vulnerabilities: The low-level nature of C makes it prone to security vulnerabilities like buffer
overflows if not correctly handled by the programmer.

Tokens in C :
Tokens in C is the most important element to be used in creating a program in C. We can define the
token as the smallest individual element in C. For `example, we cannot create a sentence without
using words; similarly, we cannot create a program in C without using tokens in C. Therefore, we can
say that tokens in C is the building block or the basic component for creating a program in C
language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

o Keywords in C

o Identifiers in C

o Strings in C

o Operators in C

o Constant in C

o Special Characters in C

Keywords in C :
Keywords in C can be defined as the pre-defined or the reserved words having its own importance,
and each keyword has its own functionality. Since keywords are the pre-defined words used by the
compiler, so they cannot be used as the variable names. If the keywords are used as the variable
names, it means that we are assigning a different meaning to the keyword, which is not allowed. C
language supports 32 keywords given below:
Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the
user-defined words. It can be composed of uppercase letters, lowercase letters, underscore, or digits,
but the starting letter should be either an underscore or an alphabet. Identifiers cannot be used as
keywords. Rules for constructing identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an underscore, and then it
can be followed by any of the character, digit, or underscore.

o It should not begin with any numerical digit.

o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.

o Commas or blank spaces cannot be specified within an identifier.

o Keywords cannot be represented as an identifier.

o The length of the identifiers should not be more than 31 characters.

o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Strings in C
Strings in C are always represented as an array of characters having null character '\0' at the end of
the string. This null character denotes the end of the string. Strings in C are enclosed within double
quotes, while characters are enclosed within single characters. The size of a string is a number of
characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "programming"; // The compiler allocates the 11 bytes to the 'a' array.

char a[] = "programming";

char a[10] = {'p,'r','o','g',r','a','m','m',’i’,'n','g','\0'}; // String is represented in the form of characters.


➢ Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type Enum

Void Data Type Void

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

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

float 4 byte

double 8 byte

long double 10 byte


• int:
Integers are entire numbers without any fractional or decimal parts, and the int data type is
used to represent them.
It is frequently applied to variables that include values, such as counts, indices, or other
numerical numbers. The int data type may represent both positive and negative
numbers because it is signed by default.
An int takes up 4 bytes of memory on most devices, allowing it to store values between
around -2 billion and +2 billion.

• Char:
Individual characters are represented by the char data type. Typically used to
hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols,
or commas. There are 256 characters that can be represented by a single char, which takes
up one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.

• Float:
To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not be
very precise. It can store values with an accuracy of about 6 decimal places and a range of
about 3.4 x 1038 in 4 bytes of memory.

• Double:
Use two data types to represent two floating integers. When additional precision is needed,
such as in scientific calculations or financial applications, it provides greater accuracy
compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal
places, yields larger values. C treats floating point numbers as doubles by default if no
explicit type is supplied.
1. int age = 25;
2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;
In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two
variables for the number pi.

Derived Data Type


Beyond the fundamental data types, C also supports derived data types, including arrays, pointers,
structures, and unions. These data types give programmers the ability to handle heterogeneous data,
directly modify memory, and build complicated data structures.

• Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the same type. It
provides a mechanism for joining multiple targets of the same data under the same name.

The index is used to access the elements of the array, with a 0 index for the first entry. The size of the
array is fixed at declaration time and cannot be changed during program execution. The array
components are placed in adjacent memory regions.

Here is an example of declaring and utilizing an array:

1. #include <stdio.h>

2.

3. int main() {

4. int numbers[5]; // Declares an integer array with a size of 5 elements

5.

6. // Assign values to the array elements

7. numbers[0] = 10;

8. numbers[1] = 20;

9. numbers[2] = 30;

10. numbers[3] = 40;

11. numbers[4] = 50;

12.

13. // Display the values stored in the array

14. printf("Values in the array: ");

15. for (int i = 0; i < 5; i++) {

16. printf("%d ", numbers[i]);


17. }

18. printf("\n");

19.

20. return 0;

21. }

Output:

Values in the array: 10 20 30 40 50

• Pointer:
A pointer is a derived data type that keeps track of another data type's memory address. When
a pointer is declared, the data type it refers to is stated first, and then the variable name is
preceded by an asterisk (*).

You can have incorrect access and change the value of variable using pointers by specifying the
memory address of the variable. Pointers are commonly used in tasks such as function pointers,
data structures, and dynamic memory allocation.

Here is an example of declaring and employing a pointer:

1. #include <stdio.h>

2.

3. int main() {

4. int num = 42; // An integer variable

5. int *ptr; // Declares a pointer to an integer

6.

7. ptr = # // Assigns the address of 'num' to the pointer

8.

9. // Accessing the value of 'num' using the pointer

10. printf("Value of num: %d\n", *ptr);

11.

12. return 0;

13. }

Test it Now

Advertisement

Output:
Value of num: 42

• Structure:
A structure is a derived data type that enables the creation of composite data types by allowing the
grouping of many data types under a single name. It gives you the ability to create your own unique
data structures by fusing together variables of various sorts.

1. A structure's members or fields are used to refer to each variable within it.

2. Any data type, including different structures, can be a member of a structure.

3. A structure's members can be accessed by using the dot (.) operator.

A declaration and use of a structure is demonstrated here:

1. #include <stdio.h>

2. #include <string.h>

3. // Define a structure representing a person

4. struct Person {

5. char name[50];

6. int age;

7. float height;

8. };

9.

10. int main() {

11. // Declare a variable of type struct Person

12. struct Person person1;

13.

14. // Assign values to the structure members

15. strcpy(person1.name, "John Doe");

16. person1.age = 30;

17. person1.height = 1.8;

18.
19. // Accessing the structure members

20. printf("Name: %s\n", person1.name);

21. printf("Age: %d\n", person1.age);

22. printf("Height: %.2f\n", person1.height);

23. return 0;

24. }

Output:

Name: John Doe

Age: 30

Height: 1.80

• Union:
A derived data type called a union enables you to store various data types in the same memory
address. In contrast to structures, where each member has a separate memory space, members of a
union all share a single memory space. A value can only be held by one member of a union at any
given moment. When you need to represent many data types interchangeably, unions come in
handy. Like structures, you can access the members of a union by using the dot (.) operator.

Here is an example of a union being declared and used:

1. #include <stdio.h>

2. // Define a union representing a numeric value

3. union NumericValue {

4. int intValue;

5. float floatValue;

6. char stringValue[20];

7. };

8. int main() {

9. // Declare a variable of type union NumericValue

10. union NumericValue value;

11. // Assign a value to the union

12. value.intValue = 42;

13. // Accessing the union members

14. printf("Integer Value: %d\n", value.intValue);

15. // Assigning a different value to the union


16. value.floatValue = 3.14;

17. // Accessing the union members

18. printf("Float Value: %.2f\n", value.floatValue);

19.

20. return 0;

21. }

Output:

Integer Value: 42

Float Value: 3.14

• Enumeration Data Type


A set of named constants or enumerators that represent a collection of connected values can be
defined in C using the enumeration data type (enum). Enumerations give you the means to give
names that make sense to a group of integral values, which makes your code easier to read and
maintain.

Here is an example of how to define and use an enumeration in C:

1. #include <stdio.h>

2.

3. // Define an enumeration for days of the week

4. enum DaysOfWeek {

5. Monday,

6. Tuesday,

7. Wednesday,

8. Thursday,

9. Friday,

10. Saturday,

11. Sunday

12. };

13.

14. int main() {

15. // Declare a variable of type enum DaysOfWeek

16. enum DaysOfWeek today;

17.
18. // Assign a value from the enumeration

19. today = Wednesday;

20.

21. // Accessing the enumeration value

22. printf("Today is %d\n", today);

23.

24. return 0;

25. }

Output:

Today is 2

• Void Data Type


The void data type in the C language is used to denote the lack of a particular type. Function return
types, function parameters, and pointers are situations where it is frequently utilized.

Function Return Type:


A void return type function does not produce a value. A void function executes a task or action and
ends rather than returning a value.

Example:

1. void printHello() { printf("Hello, world!\n"); }

Function Parameters:

The parameter void can be used to indicate that a function accepts no arguments.

Example:

1. void processInput(void) { /* Function logic */ }

➢ Variable
A variable is like a container containing the values or data of a particular data type that helps
to execute the program. The value of a variable can change depending on the conditions or
information given at the program's run time. A variable can be defined in both ways, like the
uppercase and lowercase letters, digits and the underscores. A variable can store the value
of the different data types like integer, float, character, enum.
Rules for defining the variable name in C programming language:
1. The variables are case sensitive.
2. The variable name must start with an alphabet letter or underscore.
3. It includes the letter, digits and underscore.
4. There should not be a white space in a variable name.
5. The name of a variable should not be any reserved keywords like int, float, str, char, etc.
Declaration of Variables
It is simple to declare the variables in the C program.
1. // declare the variable in C.
2. Datatype variable_name;
3. Datatype variable_name1, variable_name2, vriable_name3;
4. int a, b, d;
5. int _c;
6. char letter;
7. float z ;
8. har str[] = "welcome";
Initialization of Variables
It is the simple initialization of variable in C program:
1. Datatype variable_name; // declaration of variable
2. Variable_name = 10; // define value;
3.
4. Declaration and initialization (Assigning value to var)of variable:
5. Datatype variable_name = value;
The equal sign is used to assign a value to the variable.
So, to create a variable that should store a number, look at the following example:
Example:
Create a variable called myNum of type int and assign the value 15 to it:
int myNum = 15;
6. int a = 10;
7. float x = 5.5;
8. char letter = 'A';
9. int z = 1, a = 5, c = 2;
➢ Constants
A constant is a fixed value whose value cannot be changed during program's execution or
once the value is defined. It is also known as literal. For example, 5, 20, 'a', 'Radius', 5.2,
"Welcome back", etc.
A constant can be defined in two ways, like #define pre-processor and by const keyword. The
constants can be different data types, such as integer constants, floating constants, character
constants, string constants and enumeration constants. Let's understand briefly about them:
1. Integer constant: An integer constant is a whole number and can be large without
including any decimal points. For example, 0, 1, 2, 123, 5767, 05, 0X23, 0xFFF, etc.
2. Float constant :The float constants are the part of an integer constant that containing a
decimal point, fractional form and exponential form. Here are some example of floating
point constants: 0.5, 35.05, 2.3e6, 3.52f or 3.52F, PI = 3.14, etc.
3. Character Constants : It is a single character constant enclosed within a single quotation
mark (like 'a', 'A'), called a character constants. There are some valid constants as: 'g', 'D', ' ',
'#'.
4. String Constant : It is the character set of string constants that are enclosed in a double
quote. The
character may be letters, numbers, special symbols and some blank space. Furthermore, a
string constant contains zero, one or more continuous character in double quotation marks.
For example, "Hello Friends", "Computer", "5987", " " , "A".
Note: "A" and 'A' are different; the first one is a string constant consisting of character A and
\0. While the second 'A' represents is a character constant whose integer value is 65.
Example 1: Let's create a program to use the #define pre-processor in C constants.
1. /* create a program to display the use of #define processor in C.
2. #include<stdio.h>
3. #include<conio.h>
4. #define PI 3.14
5. void main()
6. {
7. int radius, area;
8. printf(" Please enter the radius of circle\n");
9. scanf("%d", &radius);
10. area = PI * radius * radius;
11. printf(" Area of circle is : %d", area);
12. getch();
13. }
Example 2: Write create a program to display the use of const keyword in C.
1. /* create a program to display the use of const keyword in C. */
2. #include<stdio.h>
3. #include<conio.h>
4. void main()
5. {
6. const int Len = 5;
7. const int Width = 5;
8. int area;
9. area = Len * Width;
10. printf(" Ares of Rectangle is : %d", area);
11.
12. }

Difference between Variables and Constant in C Program:

Variables Constants

It is a variable that stores data type value in a It is similar to a variable and cannot be changed
program. during program execution.

It is a variable that can be changed after defining It is a fixed variable that cannot be changed after
the variable in a program defining the variable in a program.

The value of a variable can change depending on


In constants, the value cannot be changed.
the conditions.
Typically, it uses int, float, char, string, double, It can be express in two ways: #define pre-
etc. data types in a program. processor and the const keyword.

Example: const int Len = 5;


Example: int a = 5; float radius = 5.2; char 'A';
#define PI 3.14

➢ Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register

Storage Classes Storage Place Default Value Scope Lifetime

Auto RAM Garbage Value Local Within function

Till the end of the


main program
Extern RAM Zero Global Maybe declared
anywhere in the
program

Till the end of the


main program,
Static RAM Zero Local Retains value
between multiple
functions call

Within the
Register Register Garbage Value Local
function
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are
defined.
The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, a
nd c.
8. return 0;
9. }
Output:
garbage garbage garbage
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int a = 10,i;
5. printf("%d ",++a);
6. {
7. int a = 20;
8. for (i=0;i<3;i++)
9. {
10. printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
11. }
12. }
13. printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14. }
Output:
11 20 20 20 11

Static
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one
time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }
Output:
0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }
Output:
10 24
11 25
12 26

Register
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler?s choice whether or not; the variables can be stored
in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
5. printf("%d",a);
6. }
Output:
0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the add
ress of a register variable.
6. }
Output:
main.c:5:5: error: address of register variable ?a? requested
printf("%u",&a)

External
o The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then
the compiler will show an error.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
Output
main.c:(.text+0x6): undefined reference to `a'
collect2: error: ld returned 1 exit status
Example 2
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a; // variable a is defined globally, the memory will not be allocated to a
6. printf("%d",a);
7. }
Output
0
Example 3
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and ini
tializer at same time
6. printf("%d",a);
7. }

Output
compile time error
main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
Example 4
1. #include <stdio.h>
2. int main()
3. {
4. extern int a; // Compiler will search here for a variable a defined and initialized some
where in the pogram or not.
5. printf("%d",a);
6. }
7. int a = 20;
Output
20
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line
Output
compile time error

➢ Volatile Keyword in C:
The volatile keyword prevents the compiler from applying any optimizations on the variable that
could assume the value does not change. Without volatile, the compiler might optimize out certain
reads or writes to the variable, considering them redundant. This is particularly problematic for
multi-threaded applications or embedded systems where the value can be updated outside the
normal execution flow, such as interrupts or hardware signals.

Example of Volatile Keyword in C

Consider a hardware timer that increments a counter:

volatile int timer_ticks = 0;

void timer_interrupt() {

timer_ticks++;

int main() {

setup_timer(); // hypothetical function to set up the timer interrupt

while (timer_ticks < 1000) {

// Wait for the timer to reach 1000 ticks

// Perform action after 1000 ticks

return 0;

In this example, if timer_ticks were not declared as volatile, the compiler might optimize out the
while loop check, leading to an infinite loop.

Explanation of Output

In the given example, the output isn't directly visible as it's a background increment. However, once
timer_ticks reaches 1000, the program will exit the while loop. Without volatile, the program might
never exit the loop because the compiler could assume the value of timer_ticks never changes within
the loop.
Advantages of Using Volatile Keyword in C

• Prevents Optimization Errors: It ensures that the value of the variable is always read from
memory.

• Hardware Communication: It is essential for reading and writing to hardware registers.

• Multithreading: Ensures that multiple threads have the most current value of a variable.

Disadvantages of Using Volatile Keyword in C

• Performance: It can reduce optimization, potentially leading to slower code execution.

• Overuse: Incorrect use can lead to confusing code and bugs if the programmer assumes it
provides thread safety, which it does not.

You might also like