Unit I Notes-C Prog
Unit I Notes-C Prog
Program:
Program is the set of instructions which is run by the computer to perform specific task.
The task of developing program is called programming.
After filtering all the solution, you have the best solution only. Then choose one of the best
solution and make a decision to make it as a perfect solution.
Step 5: Implement a Solution:
After getting the best solution, implement that solution to solve a problem.
Step 6: Evaluate the result
After implementing a best solution, evaluate how much your solution solve the problem.
If your solution will not solve the problem, then you can again start with Step 2.
The following are the Problem solving Techniques used to develop solutions for a problem.
Algorithms
Flowcharts
Pseudocode
1.1.1 ALGORITHM
It is a step by step description for solving a task or a problem. The ordered sequence of
instructions is executed in the specified sequence, to get the desired results.
Characteristics of Algorithm:
In the algorithms each and every instruction should be precise and unambiguous.
(i) Time:
To execute a program, the computer system takes some amount of time. The lesser is the
time required, the better is the algorithm.
(ii) Memory:
To execute a program, computer system takes some amount of memory storage. The lesser
is the memory required, the better is the algorithm
(iii) Accuracy:
Multiple algorithms may provide suitable or correct solutions to a given problem, some of
these may provide more accurate, such algorithms may be suitable.
(iv) Sequence:
(v) Functionality:
The designed algorithm must solve a single isolated problem and algorithms are designed
to handle a range of input data.
Representation of Algorithms:
The algorithms can be represented in several ways. Generally, one of the following method
is used.
(ii) Pseudocode:
Pseudocode is also a formal design tool and It consist of short, readable instructions with
the rules of structured programming.
It is used for nested selection to help clarify the conditions to be tested and how these
conditions should be nested to do proper actions.
(iv) Program:
The algorithms can be represented as a program using any high level language that
becomes a program.
Consider an example
Algorithm for Addition of two numbers:
Step 1: Start the program
Step 2: Get two numbers as input and store it in to a and b
Step 3: Add the number a & b and store it into c
Step 4: Print c
Step 5: Stop.
(ii)Selection
Selection is the program that allows a program to choose between different actions. Choose
at most one action from several alternative conditions.
Example
Algorithm to find biggest among 2 numbers:
Step1: Start
Step 2: Get two numbers as input and store it in to A and B
Step 3: If a is greater than b then
Step 4: Print A is big
Step 5: else
Step 6: Print B is big
Step 7: Stop
(iii)Repetition
Repetition(loop) may be defined as a smaller program the can be executed several times in a main
program. Repeat a block of statements while a condition is true.
Example
(iv)Function:
Function is a small block of statements in a program. Function executes only when the function is
called.
1.1.2 PSEUDOCODE
Pseudocode is a formal design tool. It consists of short, readable instruction set with the
rules of structured programming for logically explaining an algorithm.
“pseudo” means false, “code” means the set of statements (or) instructions written in a
programming language. Pseudocode is also called ‘Program Design Language’ (PDL)
Sequential logic
Selection logic
Iteration logic
1)Sequence Logic
It is used to perform instructions in a sequence, that is one after another
Thus, for sequence logic., pseudocode instructions are written in an order in which they
are to be performed.
The logic flow of pseudocode is from top to bottom.
STOP
2) Selection Logic
It is used for making decisions and for selecting the proper path out of two or more alternative
paths in program logic.
3) Repetition Logic
It is used to produce loops when one or more instructions may be executed several times
depending on some conditions.
It uses structures called DO_WHILE, FOR and REPEAT__UNTIL
Example: Pseudocode to print first 10 natural numbers
START
INITIALIZE a->0
WHILE a<10
PRINT a
ENDWHILE
STOP
A flowchart uses different shaped symbols to denote the different appropriate instruction
and these instructions can be written within the boxes using clear statements.
Then these boxes are connected by lines having arrows to indicate the flow of operations.
Description Symbols
i) Flow lines: These are the left to right or top to bottom lines
connecting symbols. These lines show the flow of control
through the program
ii) Terminal: The oval shaped symbol always begins and ends
the flowchart. The start symbol will have only one flow line
and stop will have and entering flow line. start
stop
3. The usual direction of the flow of procedure is from top to bottom; or left to right.
4. Only one flow line should come to a process symbol and only one flow line should out
from a process symbol.
5. Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer. Should leave the decision symbol.
True False
e
Start Stop
Advantages of Flowchart:
(i) To understand logic clearly:
Before coding the program, the programmer must be known about the logic of the program.
For large application the time and cost of flowchart drawing will be more.
(iv) Not known:
Task start and finish dates, the duration of tasks, resources needed, physical locations of
tasks are not known.
Start
Read
if
Process True A>B False
A is big B is big
Output
Stop
Iteration logic
(a) Top Tested loop:
o If the condition is true, the control follows the flow line that goes into the loop.
o If it is false, control follows the flow line to the first statement after the loop.
Start
count = 0
False
while
count < 10
True
count=count+1
Stop
Display
count
Start
count = 0
Add 1 to count
Display count
while
count <
True
False
Stop
SAMPLE PROBLEMS
1) Write an algorithm, Flowchart, Pseudocode to find the area and circumference of the circle.
Algorithm:
Step 1: Start
Step 2: Input the radius of the circle
Step 3: Find the area and circumference
area 3.14 * r*r
circumference 2*3.14*r
Step 4: Print the area and circumference
Step 5: Stop
Flow chart:
Start
read r
area = 3.14*r*r
Stop
Pseudocode:
READ the radius r
Find the area and circumference
Area = 3.14*r*r
circumference = 2*3.14*r
WRITE area and circumference.
start
read a, b, c
d = b*b-4*a*c
False
If d > = 0
True
root 1 = [-b+sqrt(d)]/(2*a)
root 2 = [-b-sqrt(d)]/(2*a)
stop
Pseudocode:
READ the values of a, b, c
Find Discriminant
d b*b - 4*a*c
IF d>=0 THEN
Calculate root1 = (-b + sqrt(d))/(2*a)
Root2 = (-b + sqrt (d))/(2*a)
ELSE
Roots are imaginary
ENDIF
WRITE root1, root2
3) Program for Simple calculator
Algorithm:
Step 1: Start
Step 2: Enter the values of a, b
Step 3: Find the sum
sum = a+ b, sub=a-b, pro=a*b, quo=a/b
Step 4 : Print the sum, sub, pro, quo
Step 5:
Stop
Pseudocode:
READ a,b
Find the sum difference, product, quotient
sum = a + b
sub=a-b
pro=a*b
quo=a/b
WRITE sum, sub, pro, quo
Flowchart
Start
read a,b
Stop
Start
Read year
False
If
(year % 4 = =
0)
Stop
Algorithm:
Step1: start Pseudocode:
Step 2: READ a, b, c READ a, b, c
Step 3: IF (a >b) and (a>c) THEN IF ((a>b) &&(a>c)) THEN
Step 3.1: Print ‘a’ is big WRITE ‘a is big’
ELSE ELSE IF (b>c) THEN
Step 4: IF (b>c) THEN WRITE ‘b is big’
Step 4.1: Print ‘b’ is big ELSE
ELSE WRITE ‘c is big’
Step 4.2: Print ‘c; is big ENDIF
Step 5: Stop
Flowchart
Start
Read a,b,c
If False
(a>b) and
(a>c)
If
True (b>c)
True False
Stop
Flow chart
Start
Read n
r =0
Sum = 0
False
While
(n>0)
True
r = n%10
Sum = sum*10+r
N = n/10
Print sum
Stop
Pseudocode
Set sum = 0, r=0
READ value of n
WHILE (n>0)
r =n% 10
sum = sum *10 + r
n = n/10
ENDWHILE
WRITE Sum
Set Sum = 0,
READ the value of n
WHILE (n <= 0) While
False
Print sum
avg=sum/n
Print avg
Stop
Start
Read a, b
temp = a
a=b
b = temp
Print a, b
Stop
Algorithm
Step1: Start
Step 2: Read the value of a,b
Step 3: To swap using temp
Step 3.1: temp a
Step 3.2: a b
Step 3.3: b temp
Step 4: Print value a and b
Step5: Stop
Pseudocode
READ a, b
Swap a and b using temp
temp = a
a=b
b = temp
WRITE a and b
Pseudocode
Set f1 =0, f2 = 1, f = 0
WRITE f1, f2
f = f1 + f2
READ n
WHILE (f < n)
f = f1 + f2
f1 = f2
f2 = f
WRITE f
ENDWHILE
Flowchart :
Start
f1 =0
f2 = 1, f= 0
Print f1, f2
Read n
False
While
( f < n)
True
f = f1 + f2
f1 = f2
f2 = f
Print f
Stop
Pseudocode
s= (a+b+c)/2
READ a, b, c
CALCULATE s
area = sqrt (s*(s-a) * (s-b)*(s-c))
s = a+b+c/2
Step5: Stop
Print fahrenheit
Pseudocode
Stop
READ celcius
Find fahrenheit
fahrenheit = (1.8 * celcius ) + 32
WRITE Fahrenheit
x3 x5 x7 xn
15) To solve the series S x .......
3! 5! 7! n!
Algorithm Pseudocode
Step 1: Start Set s= 0, term = x, I =1
Step 2: Read the value of x, n READ x, n
Step3: assign s 0, term x, i1. WHILE (I < = n)
Read x, n
sum = 0
term = x
i=1
While
i<=n
sum = sum + i
Print s
Stop
Start
Read x, n
q=n
s =0
k =0
While
q>0
r = q%10
s=s+r*pow(2,k)
q=q/10
k=k+1
Print s
Stop
Flow chart:
Start
Read n
fact=1, i=1
If
i<=n
fact=fact*i Print
i=i+1
Stop
Flow chart:
Start
i=2
read n
Fals
if
i<=n-1
Tru
If False
n % i == 0
True
Print not
prime
i=i+1
A
False
if
i==n
Tru
Print prime
A
Stop
C PROGRAMMING
It supports various operators, constructors, data structures, and loop constructs. The
features of C programming make it possible to use the language for system programming,
development of interpreters, compilers, operating systems, graphics, general utilities, etc. C is also
used to write other applications, such as databases, compilers, word
processors, and spreadsheets.
Thus, the structure helps us analyse the format to write a program for the least errors. It
gives better clarity and the concept of a program.
Sections of a C program
1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions
1.Documentation section
It includes the statement specified at the beginning of a program, such as a program's name,
date, description, and title. Comment lines are used. It is represented as:
//name of a program
OR
/* Overview of the code */
Both methods work as the document section in a program. It provides an overview of the
program. Anything written as comments will be considered a part of the documentation section
and will not interfere with the specified code.
2.Preprocessor section
The preprocessor section contains all the header files used in a program. It informs the
system to link the header files to the system libraries. It is given by:
#include<stdio.h>
#include<conio.h>
The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled.
The #include<stdio.h> consists of the contents of the standard input output files, which
contains the definition of stdin, stdout, and stderr. Whenever the definitions stdin, stdout, and stderr
are used in a function, the statement #include<stdio.h> need to be used.
There are various header files available for different purposes. For example, # include
<math.h>. It is used for mathematic functions in a program.
3.Define section
The define section comprises of different constants declared using the define keyword. It is given
by:
#define a = 2
4. Global declaration
The global section comprises of all the global declarations in the program. It is given by:
int a = 5;
char ch ='z';
5. Main function
main() is the first function to be executed by the computer. It is necessary for a code to
include the main(). It is like any other function available in the C library. Parenthesis () are used
for passing parameters (if any) to a function.
We can also use int or void with the main (). The void main() specifies that the program will
not return any value. The int main() specifies that the program can return integer type data.
int main()
OR
void main()
Main function is further categorized into local declarations, statements, and expressions.
6.Local declarations
The variable that is declared inside a given function or block refers to as local declarations.
main()
{
int i = 2;
i++;
}
7.Statements
The statements refer to if, else, while, do, for, etc. used in a program within the main
function.
Expressions: An expression is a type of formula where operands are linked with each other by the
use of operators. It is given by:
a - b;
a +b;
The user defined functions specified the functions specified as per the requirements of the
user. For example, color(), sum(), division(), etc.
The program (basic or advance) follows the same sections as listed above.
Return statement is generally the last section of a code. But, it is not necessary to include. It is
used when we want to return a value. The return function returns a value when the return type
other than the void is specified with the function.
Return type ends the execution of the function. It further returns control to the specified
calling function. It is given by
return;
Or
return expression;
For example,
return 0;
int a, b, sum;
printf("Enter two numbers to be added ");
scanf("%d %d", &a, &b);
// calculating sum
sum = a + b;
printf("%d + %d = %d", a, b, sum);
return 0; // return the integer value in the sum
}
Output
/* Sum of the two It is the comment section. Any statement described in it is not considered as
numbers */ a code. It is a part of the description section in a code.
The comment line is optional. It can be in a separate line or part of an
executable line.
int main() main() is the first function to be executed in every program. We have used
int with the main() in order to return an integer value.
{… The curly braces mark the beginning and end of a function. It is mandatory
} in all the functions.
printf() The printf() prints text on the screen. It is a function for displaying constant
or variables data. Here, 'Enter two numbers to be added' is the parameter
passed to it.
scanf() It reads data from the standard input stream and writes the result into the
specified arguments.
sum = a + b The addition of the specified two numbers will be passed to the sum
parameter in the output.
return 0 A program can also run without a return 0 function. It simply states that a
program is free from error and can be successfully exited.
Sections Description
/**
*file:sum.c
* author: you It is the comment section and is part of the description section of the
* description: program code.
to find sum.
*/
int main() main() is the first function that is executed in the C program.
These curly braces mark the beginning and end of the main
{…} function.
printf(“Sum: %d”,
printf() function is used to print the sum on the screen.
sum(y));
Sections Description
int sum(int y)
{ This is the subprogram section. It includes the user-defined
return y + X; functions that are called in the main() function.
}
1.3 C TOKENS
A token in C can be defined as the smallest individual element of the C programming
language that is meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are
used to perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program.
You cannot redefine keywords. C language supports 32 keywords which are given
below:
2. Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and
arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and
digits with either a letter or the underscore (_) as a first character.
Identifier names must differ in spelling and case from any keywords. You cannot use
keywords as identifiers;
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
They must begin with a letter or underscore (_).
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
For example,
Roll_no, num1, _age, contact_number1
main: method name.
a: variable name.
3. Constants
The constants refer to the variables with fixed values. They are like normal variables but
with the difference that their values cannot be modified in the program once they are
defined. Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
const float pi=3.14
4. Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in double
quotes. Whereas, a character is enclosed in single quotes in C and C++.
Examples of String
char str1[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char str2[20] = “c Programming”;
char str3[] = “C Concepts”;
5. Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot
be used for some other purpose. Some of these are listed below:
Brackets[]: Opening and closing brackets are used as array element references. These
indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
Comma (, ): It is used to separate more than one statement like for separating parameters in
function calls.
Colon(:): It is an operator that essentially invokes something called an initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity.
That’s why each individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
Assignment operator(=): It is used to assign values and for logical operation validation.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
6. Operators
Operators are symbols that trigger an action when applied to C variables and other objects.
The data items on which operators act are called operands. Depending on the number of
operands that an operator can act upon, operators can be classified as follows:
Unary Operators: Those operators that require only a single operand to act upon are
known as unary operators. For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator.
1.4 KEYWORDS
Keywords are those predefined words that have special meaning in the compiler and they
cannot be used for any other purpose. As per the C99 standard, C language has 32 keywords.
Keywords cannot be used as identifiers.
• The following table has the list of all keywords (reserved words) available in the C
language:
The following keywords are provided for user defined data types −
struct Declares a structure type
typedef Creates a new data type
union Declares a union type
enum Declares an enumeration type
Conditionals C Keywords
The following set of keywords help you to put conditional logic in the program. The
conditional logic expressed with if and else keywords provides two alternative actions for a
condition. For multi-way branching, use switch – case construct. In C, the jump operation in an
assembler is implemented by the goto keyword.
goto Jumps to a labeled statement
if Starts an if statement
else Executes when the if condition is false
case Labels a statement within a switch
switch Starts a switch statement
default Specifies default statement in switch
Other C Keywords
The following miscellaneous keywords are also extremely important:
const Specifies a constant value
Sizeof Determines the size of a data type
Volatile compiler that the value of the variable may change at any time
Types Description
Primitive Data Primitive data types are the most basic data types that are used for
Types representing simple values such as integers, float, characters, etc.
User Defined
The user-defined data types are defined by the user himself.
Data Types
The data types that are derived from the primitive or built-in datatypes
Derived Types
are referred to as Derived Data Types.
The data type is a collection of data with values having fixed values, meaning as well as
its characteristics.
Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on the 32-bit GCC compiler.
Data Type
Size (bytes) Range Format Specifier
short int
2 -32,768 to 32,767 %hd
unsigned short
2 0 to 65,535
int %hu
-2,147,483,648 to
int 4 %d
2,147,483,647
-2,147,483,648 to
long int 4 %ld
2,147,483,647
unsigned long 0 to
8 %llu
long int 18,446,744,073,709,551,615
float 4 %f
1.2E-38 to 3.4E+38
double 8 %lf
1.7E-308 to 1.7E+308
int a = 9;
// integer value with negative data.
int b = -9;
// U or u is Used for Unsigned int in C.
int c = 89U;
// L or l is used for long int in C.
long int d = 99998L;
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n",c);
printf("Integer value with an long int data: %ld", d);
return 0;
}
Output
Integer value with positive data: 9
char var_name;
float var_name;
return 0;
}
Output
9.000000
2.500000
0.000200
Syntax of Double
The variable can be declared as double precision floating point using the double keyword:
double var_name;
Syntax:
// function return type void
void exit(int check);
// Function without any parameter can accept void.
int print(void);
// memory allocation function which returns a pointer to void.
void *malloc (size_t size);
1.6 VARIABLE IN C
A variable is an Identifier used for naming entity in Programming. Variable C is a
memory location with some name that helps store some form of data and retrieves it when
required. They can be viewed as the names given to the memory location so that we can refer to
it without having to memorize the memory address.
The size of the variable depends upon the data type it stores.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.
datatype variablename = value ; // defining single variable
or
datatype variable_name1, variable_name2 ; // defining multiple variable
Here,
data_type: Type of data that a variable can store.
variable_name: Name of the variable given by the user.
value: value assigned to the variable by the user.
Example
int var; // integer variable
char a; // character variable
float fff; // float variables
int var = 10; // variable declaration and definition (i.e. Vairable Initialization)
EXAMPLE
// C program to demonstrate the declaration, initialization
#include <stdio.h>
int main()
{
// declaration
int defined_var;
// assignment
defined_var = 12;
// initialization
int ini_var = 25;
printf("Value of defined_var after assignment: %d\n", defined_var);
printf("Value of ini_var: %d", ini_var);
return 0;
}
Output
Value of defined_var after assignment: 12
Value of ini_var: 25
C VARIABLE TYPES
The C variables can be classified into the following types:
1. Local Variables
2. Global Variables
3. Static Variables
4. Automatic Variables
5. Extern Variables
6. Register Variables
1) Local Variables in C
A Local variable in C is a variable that is declared inside a function or a block of code. Its
scope is limited to the block or function in which it is declared.
Example of Local Variable in C
// C program to declare and print local variable inside a function.
#include <stdio.h>
void function()
{
int x = 10; // local variable
printf("%d", x);
}
int main()
{
function();
}
Output
10
In the above code, x can be used only in the scope of function (). Using it in the main function
will give an error.
2. Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of
code. Its scope is the whole program i.e. we can access the global variable anywhere in the C
program after it is declared.
Function 2: 20
3. Static Variables in C
A static variable in C is a variable that is defined using the static keyword. It can be
defined only once in a C program and its scope depends upon the region where it is declared
(can be global or local).
The default value of static variables is zero.
Syntax of Static Variable in C
static data_type variable_name = initial_value;
As its lifetime is till the end of the program, it can retain its value for multiple function
calls as shown in the example.
/ C program to demonstrate use of static variable
#include <stdio.h>
void function()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\t Static: %d\n", x, y);
}
int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}
Output
First Call
Local: 30
Static: 40
Second Call
Local: 30
Static: 50
Third Call
Local: 30
Static: 60
4. Automatic Variable in C
All the local variables are automatic variables by default. They are also known as auto
variables.
Their scope is local and their lifetime is till the end of the block. If we need, we can use
the auto keyword to define the auto variables.
The default value of the auto variables is a garbage value.
In the above example, both x and y are automatic variables. The only difference is that variable
y is explicitly declared with the auto keyword.
5) External Variables in C
External variables in C can be shared between multiple C files. We can declare an external
variable using the extern keyword.
Their scope is global and they exist between multiple C files.
Syntax of Extern Variables in C
extern data_type variable_name;
----------program1.c----------
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", x);
}
6) Register Variables in C
Register variables in C are those variables that are stored in the CPU register instead of the
conventional storage place like RAM. Their scope is local and exists till the end of
the block or a function.
These variables are declared using the register keyword.
The default value of register variables is a garbage value.
Syntax of Register Variables in C
register data_type variable_name = initial_value;
Output
Value of Register Variable: 22
1.7 CONSTANTS IN C
The constants in C are the read-only variables whose values cannot be modified once
they are declared in the C program.
The type of constant can be an integer constant, a floating pointer constant, a
string constant, or a character constant.
In C language, the const keyword is used to define the constants.
As the name suggests, a constant in C is a variable that cannot be modified once
it is declared in the program.
We cannot make any change in the value of the constant variables after they are
defined.
How to Define Constant in C?
We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.
Syntax to Define Constant
const data_type var_name = value;
Example of Constants in C
// C program to illustrate consta
#include <stdio.h>
int main()
{
// defining integer constant using const keyword
const int int_const = 25;
// defining character constant using const keyword
const char char_const = 'A';
Output
Printing value of Integer Constant: 25
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the list
of the types of constants
Integer Constant
Character Constant
Floating Point Constant
Double Precision Floating Point Constant
Array Constant
Structure Constant
PROPERTIES OF CONSTANT IN C
The important properties of constant variables in C defined using the const keyword are as
follows:
1. Initialization with Declaration
We can only initialize the constant variable in C at the time of its declaration.
Otherwise, it will store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be initialized
only once in the whole program. After that, we cannot modify the value stored inside that
variable.
Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
Type qualifiers were introduced by ANSI C, It is used to control optimization done by the
compiler on any data object.
1. const
2. volatile
const and volatile type qualifiers can be applied to any type of data objects. When using a
type qualifier with an array identifier, each element of the array is qualified by the compiler, not the
array type itself.
This qualifier instructs compiler to mark any data object as read only i.e. no one can change
the value of the data object during program execution.
Objects qualified by the const keyword cannot be modified. This means that an object
declared as const cannot serve as the operand in any operation that changes its value.
Some const qualified objects and their behavior are given below:
Constant integer:
The value in the location pointed by Ptr can’t be modified i.e. *Ptr is non-modifiable but Ptr is
modifiable;
Constant pointer:
A pointer which will always point to the same location. Cptr is non-modifiable but *Cptr is
modifiable;
Neither the pointer nor the integer can be modified. Ccp and *Ccp, both are not modifiable.
EXAMPLE:
#include<stdio.h>
const int glob=10; /* reside inside read only data segment */
int main()
{
const int localc=10; /* goes onto stack and localc is marked as read only */
int *localp1=&localc; /* WARNING: local const accessed through a non const qualified
object */
int *localp2=&glob; /* WARNING: global const accessed through a non const qualified
object */
*localp1=0; /* Allowed */
*localp2=0; /* Illegal: since address localp2 reside in.ro section and any alteration in .ro
section results a segmentation fault */
return 0;
}
The volatile qualifier alters the default behavior of the variable and does not attempt to
optimize the storage referenced by it.
volatile means the storage is likely to change at any time and that is something outside the
control of the user program.
This means that if you reference the variable, the program should always check the
physical address (i.e. a mapped input fifo), and not use it in a cached way.
This qualifier forces the compiler to allocate memory for the volatile object, and to always access
the object from memory.
Some volatile qualified objects and their behavior are given below:
If you apply volatile to a struct or union, the entire contents of the struct/union are volatile.
If you don’t want this behavior, you can apply the volatile qualifier to the individual members of
the struct/union.
Example code 1:
void TestFunc()
{
unsigned int * ptr = (unsigned int *) 0x65917430;
/* Wait for register to become non-zero. */
while (0 == *ptr);
printf("Register updated\n");
}
1.9 TYPEDEF
The typedef is a keyword that is used to provide existing data types with a new name. The
C typedef keyword is used to redefine the name of already existing data types. When names of
datatypes become difficult to use in programs, typedef is used with user-defined datatypes, which
behave similarly to defining an alias for commands.
Syntax
typedef existing_name alias_name;
After this declaration, we can use the alias_name as if it were the real existing_name in out C
program.
Example:
typedef long long ll;
Below is the C program to illustrate how to use typedef.
// C program to implement typedef
#include <stdio.h>
// defining an alias using typedef
typedef long long Longl;
// Driver code
int main()
{
// using typedef name to declare variable
Long1 var = 20;
printf("%ld", var);
return 0;
}
Output
20
Use of typedef in C
Following are some common uses of the typedef in C programming:
The typedef keyword gives a meaningful name to the existing data type which helps other
users to understand the program more easily.
It can be used with structures to increase code readability and we don’t have to type struct
repeatedly.
The typedef keyword can also be used with pointers to declare multiple pointers in a single
statement.
It can be used with arrays to declare any number of variables.