Computer ProgrammingChapter 2
Computer ProgrammingChapter 2
OVERVIEW OF C PROGRAMMING
2.1 Introduction to C Programming
C is a general-purpose programming language created by Dennis Ritchie
at the Bell Laboratories in 1972. It is a very popular language, despite
being old. C is strongly associated with UNIX, as it was developed to
write the UNIX operating system.C is a procedural programming
language and was mainly developed as a system programming language
to write an operating system. It is a third generation, 'high level'
programming language, that is particularly good at producing fast,
efficient code.
The main features of the C language include:
i. Low-level memory access
ii. A simple set of keywords
iii. A clean style
These features make C language suitable for system programming’s like
an operating system or computer development. Many later languages have
borrowed syntax/features directly or indirectly from the C language. Like
syntax of Java, PHP, JavaScript, and many other languages are mainly
based on the C language. C++ is nearly a superset of C language (Few
programs may compile in C, but not in C++).
Why Learn C?
Ø It is one of the most popular programming languages in the
world
Ø If you know C, you will have no problem learning other popular
programming languages such as Java, Python, C++, C#, etc, as
the syntax is similar
Ø C is very fast, compared to other programming languages,
like Java and Python
Ø C is very versatile; it can be used in both applications and
technologies
Compiled By Bishon
2.2 History and Importance of C
2.2.1 History of C
History of C
Compiled By Bishon
Ø In 1999, The new version of C was developed, In which have
new features like Data Types- char,float,int,double was used.
Ø Today’s we are using the new version of C is C11, which is
developed by Standard Committee.
2.2.2 Importance of C
Followings are the imporatance of C:
i. Building block for many other programming
languages
C is considered to be the most fundamental language
that needs to be studied if we are beginning with any
programming language. Many programming
languages such as Python, C++, Java, etc are built
with the base of the C language.
ii. Powerful and efficient language
C is a robust language as it contains many data types
and operators to give us a vast platform to perform all
kinds of operations.
iii. Portable language
C is very flexible, or we can say machine independent
that helps us to run our code on any machine without
making any change or just a few changes in the code.
iv. Built-in functions
There are only 32 keywords in ANSI C, having many
built-in functions. These functions are helpful when
building a program in C.
v. Quality to extend itself
Another crucial ability of C is to extend itself. We
have already studied that the C language has its own
set of functions in the C library. So, it becomes easy
to use these functions. We can add our own functions
to the C Standard Library and make code simpler.
vi. Structured programming language
Compiled By Bishon
C is structure-based. It means that the issues or
complex problems are divided into smaller blocks or
functions. This modular structure helps in easier and
simpler testing and maintenance.
vii. Middle-level language
C is a middle-level programming language that means
it supports high-level programming as well as low-
level programming. It supports the use of kernels and
drivers in low-level programming and also supports
system software applications in the high-level
programming language.
viii. Implementation of algorithms and data structures
The use of algorithms and data structures in C has
made program computations very fast and smooth.
Thus, the C language can be used in complex
calculations and operations.
ix. Procedural programming language
C follows a proper procedure for its functions and
subroutines. As it uses procedural programming, it
becomes easier for C to identify code structure and to
solve any problem in a specific series of code. In
procedural programming C variables and functions
are declared before use.
x. Dynamic memory allocation
C provides dynamic memory allocation that means we
are free to allocate memory at run time. For example,
if we don’t know how much memory is required by
objects in our program, we can still run a program in
C and assign the memory at the same time.
xi. System-programming
Compiled By Bishon
xii. C follows a system-based programming system. It
means the programming is done for the hardware
devices.
2.3 C Headers and Library Functions
2.3.1 C Headers
In the C programming language, C header files are files that include
declarations and definitions for variables, functions, and other elements.
They offer a method for structuring code and distinguishing between the
implementation (definitions) and the interface (declarations). Headers are
included in C source code files using the #include directive and usually
have a.h extension.
Here are some commonly used C headers:
stdio.h: Provides input/output functions such as printf and scanf.
#include <stdio.h>
stdlib.h: Contains functions involving memory allocation, random
numbers, and other general utilities.
#include <stdlib.h>
string.h: Includes functions for manipulating strings, such as strcpy and
strlen.
#include <string.h>
math.h: Contains mathematical functions like sqrt, sin, and cos.
#include <math.h>
ctype.h: Provides functions for character handling, like isalpha and
isdigit.
#include <ctype.h>
time.h: Contains functions related to time, such as time and ctime.
#include <time.h>
limits.h: Defines various constants that represent the limits of integral
types.
#include <limits.h>
Compiled By Bishon
use these functions—which carry out common tasks—in our programs.
The following are some groups of frequently used C library functions:
i. Input/Output Functions
Ø printf(), fprintf() : Output formatted text to the console or
files.
Ø scanf(), fscanf() : Read formatted input from the console or
files.
Ø getchar(), getch() : Read a single character from the standard
input.
ii. Memory Allocation Functions
Ø malloc(), calloc(), realloc(): Allocate dynamic memory.
Ø free(): Deallocate dynamic memory.
iii. String Manipulation Functions
Ø strcpy() : Copy strings.
Ø strcat() : Concatenate strings.
Ø strcmp() : Compare strings.
Ø strlen() : Get the length of a string.
Ø strstr() : Find a substring within a string.
iv. Math Functions
Ø sqrt(), pow(): Square root and power functions.
Ø sin(), cos(), tan(): Trigonometric functions.
Ø fabs(): Absolute value of a floating-point number.
Ø ceil(), floor(): Round a floating-point number up or down.
v. Character Functions
Ø isalpha(), isdigit(), isalnum(): Check character properties.
Ø toupper(), tolower(): Convert characters to uppercase or
lowercase.
vi. File Handling Functions
Ø fopen(), fclose(): Open and close files.
Ø fprintf(), fscanf(): Read and write to files.
Ø fgets(), fputs(): Read and write strings to files.
vii. Random Number Functions
Ø rand(): Generate a pseudo-random integer.
Compiled By Bishon
Ø srand(): Seed the random number generator.
viii. Date and Time Functions
Ø time(): Get the current time.
Ø ctime(): Convert a time value to a string representation.
ix. Miscellaneous Functions
Ø exit(): Terminate the program.
Ø sizeof(): Get the size in bytes of a data type or variable.
>$D#EG"D?@
>$D#EG"D?A
BBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBB
>$D#EG"D?D
Compiled By Bishon
The global declaration section: There are some variables and those
variables are declared in this section that is outside of all functions.
main( ) function: Every C program must have one main function section.
This section contains two parts, declaration and executable part.
Declaration part declares all the variables used in the executable part.
There should be at least one statement in the executable part which
contains instructions to perform certain task.
The declaration and executable part must appear between the opening and
closing braces. All statements in the declaration part should end with the
semicolon.
The subprogram section contains all the user defined functions that are
called in the main function.
Example:
/*Documentation Section: program to find the area of circle*/
#include <stdio.h> /*link section*/
#include <conio.h> /*link section*/
#define PI 3.14 /*definition section*/
float area; /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf ("Enter the radius of the circle\n"); //executable part starts here
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
}
Compiled By Bishon
compilation. These begin with hash(#) sign. They are not program
statements.
e.g., #include<stdio.h>
#define sum(x,y) x+y etc.
#define PI 3.14159
#ifdef, #ifndef, #endif, #error, #if, #elif, #else, #pragma
Macro expansion and file inclusion are the types of C pre-processor
directives. The preprocessor is a program that processes the source code
before it passes through the compiler.
Commonly used preprocessor directives in C:
#include: This directive is used to include header files in the source code.
It allows us to use functions, macros, and other declarations defined in the
included files.
#define: It is used to define macros, which are symbolic names or
constants. Macros are typically used for code substitution before
compilation.
2.6 Tokens in C
C tokens are the basic building blocks of in c programming language
which are constructed together to write a c program. Each and every
smallest individual units in a c program are known as c tokens.
Types:
i. Character Sets
Compiled By Bishon
ii. Keywords
iii. Identifiers
2.6.3 Identifiers
Ø Identifiers are names given to c entities and are used to identify
variables, functions, classes, objects, or any other user-defined
entities.
Ø These names serve as references to the associated entities within
the program code.
Ø The rules for naming identifiers are:
i. It shall be a combination of letters, digits and “_”,
ii. It must start with a letter.
iii. Names can start with the "_", underscore character but this is
not recommended as many system macros and functions are
given names in this format.
ii. Underscore is permitted between two words, but white space
is not allowed.
iii. Keywords can't be used as identifiers.
iv. It is case sensitive i.e., Xyz is not the same as xyz
Invalid identifiers:
Ø int , float , sum 1 , total sum, name$ , sum* , 1x,
total.sum
Valid identifiers:
Ø a , sum , sum1 , total_sum
Compiled By Bishon
2.8 Data Types, Variables and Constants
2.8.2 Constants
Ø In C programming, constants are fixed values that cannot be
modified during the execution of a program.
Ø They provide a way to store and use values that remain unchanged
throughout the program's execution.
Ø Constants can be of different types, including integer constants,
floating-point constants, character constants, and string literals.
i. Integer Constants:
Ø Integer constants represent whole numbers without fractional
parts. They can be specified in decimal, octal, or hexadecimal
formats.
Decimal format: For example, 123, -45, 0.
Octal format: An integer constant preceded by a 0 (zero)
indicates an octal constant. For example, 012 represents the
octal value of 10.
Hexadecimal format: An integer constant preceded by 0x or 0X
indicates a hexadecimal constant. For example, 0x1F
represents the hexadecimal value of 31.
ii. Floating-Point Constants:
Compiled By Bishon
Ø Floating-point constants represent numbers with fractional parts.
They can be specified in standard or exponential notation.
Standard notation: For example, 3.14, -2.5, 0.0.
Exponential notation: For example, 1.23e-5 represents 1.23
multiplied by 10 raised to the power of -5.
iii. Character Constants:
Ø Character constants represent individual characters enclosed in
single quotation marks.
For example, 'A', 'x', '7’.
iv.String Literals:
Ø String literals represent a sequence of characters enclosed in
double quotation marks. They are treated as arrays of characters,
terminated by a null character '\0'.
For example, "Hello, world!", "C programming".
2.8.3 Variables
Ø Variables are used to store and manipulate data during the
execution of a program.
Ø A variable is a named storage location in computer memory that
holds a value of a specific type.
Ø The value of a variable can change during the execution of a
program, hence the name "variable”.
Ø Every variable is of certain data type, can hold different constants
at different time, and different portion of a program
Ø For example,
int a;
float sum;
Ø Variables should be declared before the use
Ø Syntax of variable declaration:
data_type variable_name;
Assigning values to the variables
Before using any variables in the program for further processing they
must be given their values
we can assign values to the variables by two ways:
i. using assignment statement
Compiled By Bishon
ii. reading values of variables from keyboard using scanf library
function
i. Using assignment statement
Syntax:
variable_name=constant;
for example:
int v1;
float v2;
char ch;
Values can be assigned as:
v1=1253;
v2=5432.145;
ch= ‘v’;
Ø Value on the left of the equal sign is set to the value of the quantity
on the right
marks=marks+5;
Ø We can assign value to a variable at the time of its declaration
data type=variable _name=constant;
for example,
int v1=1245;
float v2=5432.315;
char ch= ‘v’;
Ø Process of giving intial values to variables is called initialization
a=b=c=d=e=0 is valid
ii. Reading values of variables from keybord using scanf() library
function
Ø general form of scanf():
scanf(“Control String”,addres of arg 1, address of arg 2,address of
arg3,…,address of arg n)
• Control string is the format of data being received
• address of variable can be obtained by using address of(&)
operator but for reading string variable we don’t need to use
& operator
Compiled By Bishon
For example:
int v1;
char district[25];
scanf(“%d”,&v1);
scanf(“%s”,district)
Compiled By Bishon
CLion is a commercial IDE developed by JetBrains. It is known for its
powerful code analysis, refactoring tools, and integrated support for
CMake, GDB, and other tools.
Compiled By Bishon