Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Computer ProgrammingChapter 2

Chapter 2 provides an overview of C programming, detailing its history, features, and importance as a foundational language for many others. It discusses the structure of a C program, including sections like documentation, linking, and function definitions, as well as preprocessor directives and tokens. The chapter emphasizes C's efficiency, versatility, and its role in system programming and algorithm implementation.

Uploaded by

samirlakhe97
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Computer ProgrammingChapter 2

Chapter 2 provides an overview of C programming, detailing its history, features, and importance as a foundational language for many others. It discusses the structure of a C program, including sections like documentation, linking, and function definitions, as well as preprocessor directives and tokens. The chapter emphasizes C's efficiency, versatility, and its role in system programming and algorithm implementation.

Uploaded by

samirlakhe97
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CHAPTER - 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

1960 ALGOL International Group

1967 BCPL Martin Richards

1970 B Ken Thomson

1972 C Dennis Ritchie

1978 K&R C Kernighan and Ritchie

1989 ANSI C ANSI Comittee

1999 C99 Standard Comittee

2011 C11 Standard Comittee

Ø In 1960, ALGOL was developed by the international group.


Ø In 1966, Martin Richards developed BCPL (Basic Combined
Programming Language before developing C.
Ø Later, Ken Thomson further developed BCPL by developing the
first letter of BCPL i.e. he developed the B language.
Ø Ken Thomson developed BASIC type of UNIX Operating
System, while the B language was in motion.
Ø After all this, by further developing the B language, Dennis
Ritchie developed the C language in the Bell laboratory.
Ø After developing the C language, Dennis Ritchie and Ken
Thompson together developed the UNIX Operating System.
Ø In 1978, Kernighan and Ritchie both did further improvement in
C language and they brought the C programming language in
front of the whole world.
Ø In 1989, ANSI C developed by the ANSI Committee.

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>

2.3.2 Library Functions


Predefined functions offered by the C Standard Library are known as
library functions in C. By incorporating the necessary header files, we can

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.

2.4 Basic Structure of C Program


Basic structure of a C program contains following sections:
!"#$%&DEFEG"D++,&#EG"D
-GD.+,&#EG"D
!&LGDGEG"D+,&#EG"D
01"2F1+3&#1F4FEG"D+,&#EG"D
%FGD+L$D#EG"D+,&#EG"D
%FGD5S
7
!&#1F4FEG"D+9F4E
;<&#$EF21&+9F4E
=
8$294":4F%+,&#EG"D
5$,&4+3&LGD&3+L$D#EG"D5,SS

>$D#EG"D?@
>$D#EG"D?A
BBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBB
>$D#EG"D?D

Fig.: A general structure of C programs


The documentation section consists of a set of comment lines giving the
name of the program and other details.
The link section provides instructions to the compiler to link functions
from the system library.
The definition section defines all symbolic constants.

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);
}

2.5 Preprocessor Directives


Preprocessor directives are commands or instructions that are processed
by the preprocessor in programming languages like C. These directives
provide instructions to the preprocessor to perform certain actions before
the actual compilation of the code takes place. They are typically used to
include or exclude code sections, define constants, or perform conditional

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.5.1 Macro expansion/substitution Directives


It is a process where an identifier in a program is replaced by a predefined
string composed of one or more tokens. This process performs the task
under the direction of #define statement.
Example:
#define PI 3.1415 (simple macro, used to define constants),
#define AREA(x) 3.1414*x*x (macro with argument, that can be
used as a function)

2.5.2 File inclusion Directives


This directive causes one file to be included in another. The file
contains functions and macros definitions. The #include directives that we
use are file inclusion directives that we generally use to include header
files in the program.
Example:
//Program to find the area of a circle
#include<stdio.h>
#include<conio.h>
Compiled By Bishon
#define PI 3.1415
#define AREA(x) PI*x*x
void main()
{
float r,A;
printf("Enter radius:");
scanf("%f",&r);
A=AREA(r); //Here AREA(r) is expanded to 3.1415*r*r
printf("Area=%f",A);
}
//Program to calculate the square of a number
#include <stdio.h>
// Example of a multi-line macro
#define SQUARE(x) \
{ \
int result = (x) * (x); \
printf("The square of %d is %d\n", (x), result); \
}
void main()
{
int num = 5;
// Using the multi-line macro
SQUARE(num);
}

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.1 Character Set


Ø Character set refers to the set of characters that can be used in C
source code.
Ø C uses a character set called ASCII (American Standard Code for
Information Interchange) by default. ASCII is a character
encoding standard that assigns unique numeric codes to represent
characters.
Ø The ASCII character set consists of 128 characters, including
control characters (such as newline, tab, and carriage return) as
well as printable characters (such as uppercase and lowercase
letters, digits, punctuation marks, and special symbols).
Ø Each character is represented by a 7-bit code, allowing a total of
128 different characters.
Types:
Letters
Ø A,B,C… Z
Ø a,b,c…z
Digits
Ø 0,1,2…9
Special Characters
,:“”‘’?
White Spaces

2.6.2 Keywords (reserved words)


Ø Keywords are predefined words for a C programming language.
Ø They are used for pre-defined purposes and can’t be used as
identifiers.
Ø They are written in lower case. There are 32 keywords in C.
Ø Keywords used in C are given below:
double int struct
else long switch
enum register typedef
Compiled By Bishon
extern return union
float short unsigned
for signed void
goto sizeof volatile
if static while

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

2.7 Type Casting in C


Rfer Chapter 3

Compiled By Bishon
2.8 Data Types, Variables and Constants

2.8.1 Data Type


Ø A data type is defined as a name or label for a set of values in
programming.
Ø It is used to define the kind of data being stored or manipulated.
Ø In programming, the data type specifies the range of values that
can be used and the size of memory needed for that value.
Ø For example, in C, some data types are:
int for integer number (1, 2, 30, 55, etc.)
float for fractional number (2.5, 3.861, etc.)
char for character type ('*', 'a', 'Z', '2', etc.)
Ø C programming language supports the following classes of data
types:
i. Fundamental data type
ii. Derived data type
iii. User defined data type
i. Fundamental data type
Ø There are four fundamental data types which are listed below:
Data type Size (byte) Range
char 1 -128 to 127
int 2 -32,768 to 32,767
float 4 3.4e-38 to 3.4e+38
double 8 1.7e-308 to 1.7e+308
Qualifiers: They are used to modify the property of the variable
data type to which they are applied.
There are four types of qualifiers:
a. Size qualifiers: “short” and “long” are size qualifiers.Both long
and short can be applied to int.But for double we can apply long.
b. Sign qualifiers: “signed” and “unsigned” are sign qualifiers.
They can be applied to int and char
c. const: The variable declared “const” cannot be modified by a
program.
Declaration:
Compiled By Bishon
const data_type const_name = const_value
eg. const int p=20;
d. volatile: The variable declared “volatile” can be modified by
some external sources outside the program.
Declaration:
volatile data_type variable_name = value
eg. volatile int p=20;

ii. Derived data type


Ø They are the data types which are derived from the fundamental
data types.
Ø Functions, arrays, and pointers are derived data types.
iii. User defined data type
Ø They are the data types which are defined by the user.
Ø Structure, union, and enumeration are user defined data types.

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)

2.9 IDE for C Programming


An IDE, or Integrated Development Environment, is a powerful software
application designed specifically for computer programmers. Its
comprehensive features aim to streamline the entire software development
process, providing a convenient and unified environment for writing,
testing, and debugging code. Complete with a source code editor,
compiler or interpreter, build automation tools, and a debugger, an IDE is
an essential tool for developers. There are several Integrated Development
Environments (IDEs) available for C programming, each with its own
features and capabilities. Here are some popular IDEs for C
programming:
i. Code::Blocks
Code::Blocks is a free and open-source IDE that supports C, C++, and
Fortran. It provides a customizable interface, features like syntax
highlighting, code completion, and integrated debugging.
ii. Eclipse:
Eclipse is a versatile IDE that supports various programming languages,
including C. It offers a rich set of features, plugins, and a powerful
debugger. Eclipse IDE for C/C++ Developers is a popular distribution for
C development.
iii. Visual Studio
Microsoft Visual Studio is a powerful and feature-rich IDE. Visual Studio
Community edition is free and provides excellent support for C and C++
development. It includes a robust debugger, IntelliSense, and other
advanced features.
iv. Dev-C++
Dev-C++ is a simple and lightweight IDE for C and C++ development. It
comes with an integrated debugger, a form designer, and supports
multiple compilers.
v. CLion

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

You might also like