PPSC Unit-1
PPSC Unit-1
Introduction to Computer
The full form of the computer is Common Operating Machine Purposely Used for Technological
and Educational Research.
"A computer is a programmable electronic device that takes data, perform instructed arithmetic and
logical operations, and gives the output."
• The term computer has been derived from the word “Compute”.
• Charles Babbage is called father of computer.
Whatever is given to the computer as input is called 'data', while the output received after
processing is called 'information'.
Generations Of Computers
Over the years, computer languages have been evolved from Low-Level to High-Level Languages.
In the earliest days of computers, only Binary Language was used to write programs. The computer
languages are classified as follows...
Generally, the programs created using programming languages like C, C++, Java, etc., are written
using a high-level language like English. But, the computer cannot understand the high-level
language. It can understand only low-level language. So, the program written in the high-level
language needs to be converted into the low-level language to make it understandable for the
computer. This conversion is performed using either Interpreter or Compiler.
To create and execute C programs in the Windows Operating System, we need to install Turbo C
software. We use the following steps to create and execute C programs in Windows OS…
After completing compilation successfully, an executable file is created with a .exe extension. The
processor can understand this .exe file content so that it can perform the task specified in the source
file.
We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the .exe file is
submitted to the CPU. On receiving .exe file, CPU performs the task according to the instruction
written in the file. The result generated from the execution is placed in a window called User
Screen.
After running the program, the result is placed into User Screen. Just we need to open the User
Screen to check the result of the program execution. We use the shortcut key Alt + F5 to open the
User Screen and check the result.
The file which contains c program instructions in a high-level language is said to be source code.
Every c program source file is saved with .c extension, for example, Sample.c.
3
Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks for the
errors, if there are any errors, it returns a list of errors, otherwise generates object code in a file with
name Sample.obj and submit it to the linker.
Now, we need to run the executable file (Sample.exe). To run a program, we press Ctrl + F9. When
we press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs the task
according to the instructions written in that program and place the result into UserScreen.
Then we press Alt + F5 to open User Screen and check the result of the program.
Numbering system are the technique to represent numbers in the computer system
architecture,every value thet you are saving or getting into/from computer memory has a defined
number system
Decimal number system is a base 10 number system having 10 digits from 0 to 9. This means that
any numerical quantity can be represented using these 10 digits. Decimal number system is also
a positional value system. This means that the value of digits will depend on its position. Let us
take an example to understand this.
Say we have three numbers – 734, 971 and 207. The value of 7 in all three numbers is different−
The easiest way to vary instructions through electric signals is two-state system – on and off. On is
represented as 1 and off as 0, though 0 is not actually no signal but signal at a lower voltage. The
number system having just these two digits – 0 and 1 – is called binary number system.
4
Each binary digit is also called a bit. Binary number system is also positional value system, where
each digit has a value expressed in powers of 2, as displayed here.
In any binary number, the rightmost digit is called least significant bit (LSB) and leftmost digit is
called most significant bit (MSB).
And decimal equivalent of this number is sum of product of each digit with its positional value.
= 16 + 8 + 0 + 2 + 0
= 2610
5
Decimal equivalent of any hexadecimal number is sum of product of each digit with its positional
value.
27FB16 = 2×163 + 7×162 + 15×161 + 11×160
= 8192 + 1792 + 240 +11
= 1023510
Conversions
Example – 1010111100
= (1010111100)2
= (1 2 7 4)8
= (1274)8
6
Storing Integers
computer is a electronic device where data is stored in the form of electronic signals.
• Bit is the basic unit of memory. At a time, it can be either on or off. Generally, bits are represented
using electrical voltage.
• Voltage presence indicates that the bit is in ON state. Voltage absence indicates that the bit is in
OFF state.
• Here, OFF state is considered as 0. ON state is considered as 1.
• Computer memory is the collection of several bits. Group of 8 bits are called byte.
Computer memory is measured in terms of how many bits it can store. Here is a chart for memory
capacity conversion.
7
Unsigned Numbers
• There is no sign bit in unsigned binary numbers so it can only represent its magnitude.
• In zero and one, zero is an unsigned binary number. There is only one zero (0) in this
representation, which is always positive. Because of one unique binary equivalent form of a number
in unsigned number representation, it is known as unambiguous representation technique.
• The range of the unsigned binary numbers starts from 0 to (2n-1).
Signed Numbers
The signed numbers have a sign bit so that it can differentiate positive and negative integer
numbers. The signed binary number technique has both the sign bit and the magnitude of the
number. For representing the negative decimal number, the corresponding symbol in front of the
binary number will be added.
The signed numbers are represented in three ways.
Sign-Magnitude form
In the signed integer representation method the following rules are followed:
1. The MSB (Most Significant Bit) represents the sign of the Integer.
2. Magnitude is represented by other bits other than MSB i.e. (n-1) bits where n is the no. of bits.
3. If the number is positive, MSB is 0 else 1.
4. The range of signed integer representation of an n-bit number is given as –(2^{n-1}-1) to (2)^{n-
1}-1.
Example:
Let n = 4
Range:
–(2^{4-1}-1) to 2^{4-1}-1
= -(2^{3}-1) to 2^{3}-1
= -(7) to+7
For 4 bit representation, minimum value=-7 and maximum value=+7
→Drawbacks:
1. For 0, there are two representations: -0 and +0 which should not be the case as 0 is neither –ve
nor +ve.
2. Out of 2^n bits for representation, we are able to utilize only 2^{n-1} bits.
3. Numbers are not in cyclic order i.e. After the largest number (in this, for example, +7) the next
number is not the least number (in this, for example, +0).
4. For negative numbers signed extension does not work.
Example:
Signed extension for +5
8
5. As we can see above, for +ve representation, if 4 bits are extended to 5 bits there is a need to
just append 0 in MSB.
6. But if the same is done in –ve representation we won’t get the same number. i.e. 10101 ≠ 11101.
2. 1’s Complement representation of a signed integer
9
Drawbacks:
1. For 0, there are two representations: -0 and +0 which should not be the case as 0 is neither –ve nor
+ve.
2. Out of 2^n bits for representation, we are able to utilize only 2^{n-1} bits.
Merits over Signed bit representation:
1. Numbers are in cyclic order i.e. after the largest number (in this, for example, +7) the next
number is the least number (in this, for example, -7).
2. For negative number signed extension works.
Example: Signed extension for +5
3. As it can be seen above, for +ve as well as -ve representation, if 4 bits are extended to 5 bits
there is a need to just append 0/1 respectively in MSB.
2’s Complement representation
In 2’s Complement representation the following rules are used:
1. For +ve numbers, the representation rules are the same as signed integer representation.
2. For –ve numbers, there are two different ways we can represent the number.
• Write an unsigned representation of 2^n-X for –X in n-bit representation.
Example:
(-5) in 4-bit representation
2^4-5=11 -→1011(unsigned)
• Write a representation of +X and take 2’s Complement.
To take 2’s complement simply take 1’s complement and add 1 to it.
Example:
(-5) in 2’s complement
(+5) = 0101
1’s complement of (+5) = 1010
Add 1 in 1010: 1010+1 = 1011
Therefore (-5) = 1011
3. Range of representation of n-bit is –(2^{n-1} ) to (2)^{(n-1)-1}.
2’s Complement representation (4 bits)
10
Merits:
1. No ambiguity in the representation of 0.
2. Numbers are in cyclic order i.e. after +7 comes -8.
3. Signed Extension works.
4. The range of numbers that can be represented using 2’s complement is very high.
Due to all of the above merits of 2’s complement representation of a signed integer, binary
numbers are represented using 2’s complement method instead of signed bit and 1’s complement.
Storing Real Numbers
Real numbers are numbers that include fraction values after the decimal point.
EX:123.75 is a real number
To store a floating-point number, 4-byte (32 bit) memory will be allocated in computer.
• 1 bit for sign
• 8 bits for exponent part
• 23 bits for significant part
Procedure
1.Floating number will be converted to binary number
2.Make the converted binary number to normalize form
For floating point numbers, we always normalize it like 1. significant bit * 2 exponent
So, 1010.11 will be normalized as,
1.01011 * 2 3. Since I have shifted 3 bits to left side.
Pictorial Explanation
11
3.Add bias to exponent
In floating number, no concept called 2’s complement to store negative numbers. To overcame
that, they came up with bias concept where we add some positive value to negative exponent and
make it positive.
In general, whether it negative or positive they add bias value to exponent value to reduce
implementation complexity.
Formula to calculate bias value is
Bias n = 2n-1- 1;
Here, we have allocated 8 bits for exponent. So n will be 8
So, 2 7 - 1 = 127
Hence the normalized exponent value will be,
Actual exponent + bias value which is 130 (3 + 127)
Binary form of 130 is (10000010) 2
Representation
Now we have,
• Sign bit 0 because 10.75 is positive number
• Exponent value is 130 which is (10000010) 2
• Significant value is 1.01011, here we can eliminate 1 before the dot (.) because whatever be the
number we always going to normalize as 1.something. So, no need to store the 1. Just take bits
after the dot (.) which is 01011.
Pictorial Explanation
12
Introduction to C
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
In a C program, the comment lines are optional. Based on the requirement, we write comments. All
the comment lines in a C program just provide the guidelines to understand the program and its
code.
Line 2: Preprocessing Commands
Preprocessing commands are used to include header files and to define constants. We use
the #include statement to include the header file into our program. We use a #define statement to
define a constant. The preprocessing statements are used according to the requirements. If we don't
need any header file, then no need to write #include statement. If we don't need any constant, then
no need to write a #define statement.
Line 3: Global Declaration
The global declaration is used to define the global variables, which are common for all the
functions after its declaration. We also use the global declaration to declare functions. This global
declaration is used based on the requirement.
Line 4: int main ()
Every C program must write this statement. This statement (main) specifies the starting point of the
C program execution. Here, main is a user-defined method which tells the compiler that this is the
starting point of the program execution. Here, int is a data type of a value that is going to return to
the Operating System after completing the main method execution. If we don't want to return any
value, we can use it as void.
Line 5: Open Brace ( { )
The open brace indicates the beginning of the block which belongs to the main method. In C
program, every block begins with a '{' symbol.
Line 6: Local Declaration
In this section, we declare the variables and functions that are local to the function or block in
which they are declared. The variables which are declared in this section are valid only within the
function or block in which they are declared.
Line 7: Executable statements
In this section, we write the statements which perform tasks like reading data, displaying the result,
calculations, etc., All the statements in this section are written according to the requirements.
Line 9: Closing Brace ( } )
The close brace indicates the end of the block which belongs to the main method. In C program
every block end with a '}' symbol.
Line 10, 11, 12, ...: User-defined function ()
This is the place where we implement the user-defined functions. The user-defined function
implementation can also be performed before the main method. In this case, the user-defined
14
function need not be declared. Directly it can be implemented, but it must be before the main
method. In a program, we can define as many user-defined functions as we want. Every user-
defined function needs a function call to execute its statements.
General rules for any C program
‘C’ Tokens
• Every C program is a collection of instructions and every instruction is a collection of some
individual units.
• Every smallest individual unit of a c program is called token. Every instruction in a c program is
a collection of tokens.
• Tokens are used to construct c programs and they are said to the basic building blocks of a’ c’
program.
In a C program, a collection of all the keywords, identifiers, operators, special symbols, constants,
strings, and data values are called Tokens
C Keywords
As every language has words to construct statements, C programming also has words with a
specific meaning which are used to construct c program instructions.
In the C programming language, there are 32 keywords. All the 32 keywords have their meaning
which is already known to the compiler.
Keywords are the reserved words with predefined meaning which already known to the compiler
15
Properties of Keywords
1. All the keywords in C programming language are defined as lowercase letters so they must be used
only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords cannot be used as user-defined names like variable, functions, arrays, pointers, etc...
4. Every keyword in C programming language represents something or specifies some kind of action
to be performed by the compiler.
The following table specifies all the 32 keywords with their meaning...
Identifiers
An identifier is a collection of characters which acts as the name of variable, function, array,
pointer, structure, etc...
In other words, an identifier can be defined as the user-defined name to identify an entity uniquely
in the c programming language that name may be of the variable name, function name, array name,
pointer name, structure name or a label.
The identifier is a user-defined name of an entity to identify it uniquely during the program
execution
16
Rules for Creating Identifiers
1. An identifier can contain letters (UPPERCASE AND lowercase), numeric & underscore symbol
only.
2. An identifier should not start with a numerical value. It can start with a letter or an underscore.
3. We should not use any special symbols in between the identifier even whitespace. However, the
only underscore symbol is allowed.
4. Keywords should not be used as identifiers.
5. There is no limit for the length of an identifier. However, the compiler considers the first 31
characters only.
6. An identifier must be unique in its scope.
Example:
Marks, Name_Tec, a1
Data types
Data used in c program is classified into different types based on its properties. In the C
programming language, a data type can be defined as a set of values with similar characteristics. All
the values in a data type have the same properties.
The Data type is a set of value with predefined characteristics. data types are used to declare
variable, constants, arrays, pointers, and functions.
17
Primary data types
The primary data types in the C programming language are the basic data types. All the primary
data types are already defined in the system. Primary data types are also called as Built-In data
types. The following are the primary data types in c programming language...
• float
• double
We use the keyword "float" to represent floating-point data type and "double" to represent double
data type in ‘c’.
The float value contains 6 decimal places whereas double value contains 15 or 19 decimal places.
The following table provides complete details about floating-point data types.
18
Character data type
The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.
ASCII :
• It is a character encoding standard for electronic communication. American Standard Code for
Information Interchange (ASCII) and was first launched in 1963. ASCII codes are used to
represent text in computers and telecom devices.
• ASCII is used for representing 128 English characters in the form of numbers, with each letter
being assigned to a specific number in the range 0 to 127. For e.g., the ASCII code for uppercase
A is 65, uppercase B is 66, and so on.
• Most computers are using ASCII encoding for text representation, which makes transferring data
from one device to another a lot easier.
Unicode :
• Unicode provides a unique way to define every character in every spoken language of the world
by assigning it a unique number. The Unicode standard is maintained by the Unicode Consortium
and defines more than 1,40,000 characters.
• Unicode can be defined with different character encoding like UTF-8, UTF-16, UTF-32, etc.
Among these UTF-8 is the most popular as it used in over 90% of websites on the World Wide
Web as well as on most modern Operating systems like Windows.
19
C Variables
Variable is a name given to a memory location where we can store different values of the
same datatype during the program execution.
In other words, a variable can be defined as a storage container to hold values of the same datatype
during the program execution.
Declaration of Variable
• Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified datatype values into that memory location.
• In C programming language, the declaration can be performed either before the function as global
variables or inside any block or function. But it must be at the beginning of block or function.
Declaration Syntax:
Example
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.
float marks;
Syntax 2:
<data type> <variable1, varaible2….>;
Example: int a, b, c;
Initialize variable
Assigning the value to the variable at the time of declaration is known as initialization
Syntax:
<datatype> <variable name=value>;
Example:
int a=56;
float b=9.7;
char d=’g’;
20
Constants
In C programming language, a constant is similar to the variable but the constant hold only one
value during the program execution. That means, once a value is assigned to the constant, that value
can't be changed during the program execution....
A constant is a named memory location which holds only one value throughout the program
execution.
Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal
integer value is specified as direct integer value whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX'.
Example
A floating-point constant must contain both integer and decimal parts. Sometimes it may also
contain the exponent part. When a floating-point constant is represented in exponent form, the
value must be suffixed with 'e' or 'E'.
Example
Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a maximum
length of one character.
Example
'A'
'2'
'+'
21
In the C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape sequence is
prefixed with '\' symbol. These escape sequences are used in output function called 'printf()'.
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that are
enclosed in double quotations.
Creating constants in C
We create a constant of any datatype using 'const' keyword. To create a constant, we prefix the
variable declaration with 'const' keyword.
The general syntax for creating constant using 'const' keyword is as follows...
const datatype constant Name;
OR
const datatype constantName = value;
Example
const int x = 10;
Here, 'x' is a integer constant with fixed value 10.
Input functions:
C programming language provides built-in functions to perform input operations. The input
operations are used to read user values (input) from the keyboard. The c programming language
provides the following built-in input functions.
1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()
22
scanf() function
• The scanf() function is used to read multiple data values of different data types from the keyboard.
• The scanf() function is built-in function defined in a header file called "stdio.h".
• When we want to use scanf() function in our program, we need to include the respective header file
(stdio.h) using #include statement.
• The scanf() function has the following syntax...
Syntax:
scanf("format strings",&variableNames);
Format specifiers in C
• Format specifiers in C are used to take inputs and print the output of a type.
• The symbol we use in every format specifier is %.
• Format specifiers tell the compiler about the type of data that must be given or input and the type
of data that must be printed on the screen.
Format Description
specifier
%d or %i It is used to print the signed integer value where signed integer means that the variable
can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer means that the
variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value always starts with
a 0 value.
%x It is used to print the hexadecimal unsigned integer where the hexadecimal integer
value always starts with a 0x value. In this, alphabetical characters are printed in small
letters such as a, b, c, etc.
%X It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical
characters in uppercase such as A, B, C, etc.
%f It is used for printing the decimal floating-point values. By default, it prints the 6 values
after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.
%g It is used to print the decimal floating-point values, and it uses the fixed precision, i.e.,
the value after the decimal in input would be exactly the same as the value in the
output.
%p It is used to print the address in a hexadecimal form.
%c It is used to print the unsigned character.
23
%s It is used to print the strings.
%ld It is used to print the long-signed integer value.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
printf("\nYou have entered %d number",i);
}
Output:
In the above example program, we used the scanf() function to read an integer value from the
keyboard and store it into variable “i.”
The scanf function also used to read multiple data values of different or the same data types.
Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value : ");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);
}
Output:
In the above example program, we used the scanf() function to read one integer value and one float
value from the keyboard. Here 'i' is an integer variable so we have used format string %d, and 'x' is
a float variable so we have used format string %f.
The scanf() function returns an integer value equal to the total number of input values read using
scanf function.
Example Program
#include<stdio.h>
#include<conio.h>
24
void main(){
int i,a,b;
float x;
printf("\nEnter two integers and one float : ");
i = scanf("%d%d%f",&a, &b, &x);
printf("\nTotal inputs read : %d",i);
}
Output:3
getchar() function
The getchar() function is used to read a character from the keyboard and return it to the program.
This function is used to read a single character. To read multiple characters we need to write
multiple times or use a looping statement. Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c\n",ch);
}
Output:B
You have entered B
getch() function
The getch() function is similar to getchar function. The getch() function is used to read a character
from the keyboard and return it to the program. This function is used to read a single character. To
read multiple characters we need to write multiple times or use a looping statement. Consider the
following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char ch;
printf("\nEnter any character : ");
ch = getch();
25
printf("\nYou have entered : %c",ch);
}
Output: Enter any character: X
You have entered X
gets() function
The gets() function is used to read a line of string and stores it into a character array. The gets()
function reads a line of string or sequence of characters till a newline symbol enters. Consider the
following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
printf("%s",name);
}
Output:
Enter your favuurite website: www.google.com
www.google.com
fscanf() function
The fscanf() function is used with the concept of files. The fscanf() function is used to read data
values from a file. When you want to use fscanf() function the file must be opened in reading mode.
OUTPUT FUNCTION
1. printf()
2. putchar()
3. puts()
4. fprintf()
printf() function
The printf() function is used to print string or data values or a combination of string and data values
on the output screen (User screen). The printf() function is built-in function defined in a header file
26
called "stdio.h". When we want to use printf() function in our program we need to include the
respective header file (stdio.h) using the #include statement. The printf() function has the following
syntax...
Syntax:
printf("message to be display!!!");
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Hello! Welcome to TIrumala Engineering college!!!");
}
The printf() function is also used to display data values. When we want to display data values we
printf("format string",variableName);
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 10;
float x = 5.5;
printf("%d %f",i, x);
}
Output:
In the above example program, we used the printf() function to print data values of variables i and x
on to the output screen. Here i is a an integer variable so we have used format string %d and x is a
The printf() function can also be used to display string along with data values.
Syntax:
Output:
In the above program, we are displaying string along with data values.
Every function in the C programming language must have a return value. The printf() function also
have an integer as a return value. The printf() function returns an integer value equivalent to the
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
i = printf("btechsmartclass");
printf(" is %d number of characters.",i);
}
Output:15
In the above program, first printf() function printing "btechsmartclass" which is of 15 characters. So
it returns integer value 15 to the variable "i". The value of "i" is printed in the second printf()
function.
putchar() function
The putchar() function is used to display a single character on the output screen. To print multiple
characters, we need to write multiple times or use a looping statement. Consider the following
example program...
Example Program
28
#include<stdio.h>
#include<conio.h>
void main(){
char ch = 'A';
putchar(ch);
}
Output: A
puts() function
The puts() function is used to display a string on the output screen. The puts() functions prints a
string or sequence of characters till the newline. Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
The fprintf() function is used with the concept of files. The fprintf() function is used to print a line
into the file. When you want to use fprintf() function the file must be opened in writting mode.
scope
A scope is a region of the program, and the scope of variables refers to the area of the program
where the variables can be accessed after its declaration.
Each identifier that appears in a C program is visible (that is, may be used) only in some possibly
discontiguous portion of the source code called its scope.
29
Block scope
A Block in C is a set of statements written within the right and left braces. A block may contain
more blocks within it, i.e., nested blocks.
{ }
Program scope
Global variables declared outside the function bodies have a program scope. The availability of
global variables stays for the entire program after its declaration. Moreover, global variables are
initialized automatically by the compiler.
#include <stdio.h>
//Declare Global Variables Output
int a = 8; The value of a is: 8
float b = 7.5; The value of b is: 7.500000
int test()
{
b = b + a;
return b;
}
Void main(){
//Access a
printf ("The value of a is: %d\n", a);
//Access b
printf ("The value of b is: %f\n", b);
File scope
• The global static variable is accessible by all the functions in the same source file as the variable.
• This variable has a File Scope, i.e., we can access the variable anywhere in the same C file.
• Therefore, the variables with File Scope do not conflict with other variables because they are
private to the source file.
Example
The code below shows the static global variable a. Since a has a File Scope, it is accessible both
within and outside the function. It is referenced in lines 7 and 13, as shown below:
#include <stdio.h>
Void main()
{
func();
a = a + 5;
printf ("The value of a is: %d\n", a);
return 0;
}
C Storage Classes
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
1. Automatic
2. External
3. Static
4. Register
In the C programming language, the memory of variables is allocated either in computer memory
(RAM) or CPU Registers. The allocation of memory depends on storage classes.
Automatic
• Automatic variables are allocated memory automatically at runtime.
• The visibility of the automatic variables is limited to the block in which they are defined.
• The scope of the automatic variables is limited to the block in which they are defined.
• The automatic variables are initialized to garbage by default.
• The memory assigned to automatic variables gets freed upon exiting from the block.
• The keyword used for defining automatic variables is auto.
• Every local variable is automatic in C by default.
Example 1
#include <stdio.h>
int main()
32
{
int a; //auto
char b;
float c;
printf("%d %c %f", a, b, c); // printing initial default value of automatic variables a, b, and c.
return 0;
}
Output:
garbage garbage garbage
Example
#include<stdio.h>
#include<conio.h>
int main(){
{
int a=20;
printf("%d",a);
}
printf(" %d",a); //a is not visible here
return 0;
}
Static
• The variables defined as static specifier can hold their value between the multiple function calls.
• Static local variables are visible only to the function or the block in which they are defined.
• A same static variable can be declared many times but can be assigned at only one time.
• Default initial value of the static integral variable is 0 otherwise null.
• The visibility of the static global variable is limited to the file in which it has declared.
The keyword used to define static variable is static.
Example 1
#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
33
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
}
Output:
0 0 0.000000 (null)
Example 2
#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}
Output:
10 24
11 25
12 26
Register
• 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.
• The access time of the register variables is faster than the automatic variables.
• The initial default value of the register local variables is 0.
• The register keyword is used for the variable which should be stored in the CPU register. However,
it is compilers choice whether or not the variables can be stored in the register.
• We can store pointers into the register, i.e., a register can store the address of a variable.
• Static variables can not be stored into the register since we can not use more than one storage
specifier for the same variable.
34
Example 1
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default value of a is
0.
printf("%d",a);
}
Output:
0
External
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.
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.
The default initial value of external integral type is 0 otherwise null.
We can only initialize the extern variable globally, i.e., we can not initialize the external variable
within any block or method.
An external variable can be declared many times but can be initialized at only once.
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
#include <stdio.h>
int main()
{
extern int a;
printf("%d",a);
}
Output
ERROR
Example 2
#include <stdio.h>
int a;
int main()
{
35
extern int a; // variable a is defined globally, the memory will not be allocated to a
printf("%d",a);
}
Output
0
Example 3
#include <stdio.h>
int a;
int main()
{
extern int a = 0; // this will show a compiler error since we can not use extern and initializer at same
time
printf("%d",a);
}
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
#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the
pogram or not.
printf("%d",a);
}
int a = 20;
Output: 20
C Expressions
What is an expression?
An expression is a collection of operators and operands that represents a specific value.
• In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
• Operands are the values on which the operators perform the task. Here operand can be a direct
value or variable or address of memory location.
36
Expressions
Expression Types in C
In the C programming language, expressions are divided into THREE types. They are as follows...
• Infix Expression
• Postfix Expression
• Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Prefix Expression
The expression in which the operator is used before operands is called prefix expression.
The prefix expression has the following general structure.
37
Operator Precedence and Associativity in C
10 + 20 * 30
For example:
‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 /
10 * 10” is treated as “(100 / 10) * 10”.
38
C Expression Evaluation
In the C programming language, an expression is evaluated based on the operator precedence and
associativity. When there are multiple operators in an expression, they are evaluated according to
their precedence and associativity. The operator with higher precedence is evaluated first and the
.
10 + 4 * 3 / 2
• In the above expression, there are three operators +, * and /. Among these three operators, both
multiplication and division have the same higher precedence and addition has lower precedence.
• So, according to the operator precedence both multiplication and division are evaluated first and
then the addition is evaluated. As multiplication and division have the same precedence they are
evaluated based on the associativity.
• Here, the associativity of multiplication and division is left to right. So, multiplication is
performed first, then division and finally addition. So, the above expression is evaluated in the
order of * / and +. It is evaluated as follows...
• 4 * 3 ====> 12
12 / 2 ===> 6
39
10 + 6 ===> 16
The expression is evaluated to 16.
Type Casting and Conversion in C
In a programming language, the expression contains data values of the same datatype or
different data types. When the expression contains similar datatype values then it is evaluated
without any problem. But if the expression contains two or more different datatype values, then
they must be converted to the single datatype of destination datatype.
Type conversion in C is the process of converting one data type of varaiable to another
datatype.
1. Type Conversion
2. Type Casting
Conversion ranking
Type Conversion
• The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler.
• Sometimes type conversion is also called implicit type conversion. The implicit type conversion is
automatically performed by the compiler.
40
• For example, in c programming language, when we assign an integer value to a float variable the
integer value automatically gets converted to float value by adding decimal value 0.
• when a float value is assigned to an integer variable the float value automatically gets converted to
an integer value by removing the decimal value.
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
Output:
In the above program, we assign i = x, i.e., float variable value is assigned to the integer variable.
Here, the compiler automatically converts the float value (90.99) into integer value (90) by
removing the decimal part of the float value (90.99) and then it is assigned to variable i. Similarly,
when we assign x = i, the integer value (90) gets converted to float value (90.000000) by adding
41
Typecasting
Typecasting is also called an explicit type conversion. Compiler converts data from one data type
to another data type implicitly. When compiler converts implicitly, there may be a data loss. In such
a case, we convert the data from one data type to another data type using explicit type conversion.
To perform this, we use the unary cast operator. To convert data from one type to another type we
specify the target data type in parenthesis as a prefix to the data value that has to be converted. The
(TargetDatatype) DataValue
Example
float average ;
In the above example code, both totalMarks and maxMarks are integer data values. When we
perform totalMarks / maxMarks the result is a float value, but the destination (average) datatype is a
float. So, we use type casting to convert totalMarks and maxMarks into float data type.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int a, b, c ;
float avg ;
printf("Enter any three integer values : ");
scanf(“%d %d %d”, &a, &b, &c);
avg = (a + b + c) / 3 ;
printf("avg before casting = %f" ,avg) ;
avg = (float)(a + b + c) / 3 ;
printf( "avg after casting =%f " , avg);
}
Type Qualifiers in C
The c programming language provides two type qualifiers and they are as follows...
❖ const
42
❖ volatile
const type qualifier in C
❖ The const type qualifier is used to create constant variables.
❖ When a variable is created with const keyword, the value of that variable can't be changed once it is
defined.
❖ That means once a value is assigned to a constant variable, that value is fixed and cannot be
changed throughout the program.
The keyword const is used at the time of variable declaration. We use the following syntax to
create constant variable using const keyword.
const datatype variableName ;
When a variable is created with const keyword it becomes a constant variable. The value of the
constant variable can't be changed once it is defined. The following program generates error
message because we try to change the value of constant variable x.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 9 ;
const int x = 10 ;
clrscr() ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\n x = %d", i, x ) ;
}
Output:
ERROR
volatile type qualifier in C
The volatile type qualifier is used to create variables whose values can't be changed in the program
explicitly but can be changed by any external device or hardware.
For example, the variable which is used to store system clock is defined as a volatile variable. The
value of this variable is not changed explicitly in the program but is changed by the clock routine of
the operating system.
• The arguments passed from command line are called command line arguments. These arguments
• To support command line argument, you need to change the structure of main() function as given
below.
43
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name always.
Example
Let's see the example of command line arguments where we are passing one argument with file
name.
#include <stdio.h>
void main(int argc, char *argv[] ) {
./program hello
program.exe hello
Output:
44