0% found this document useful (0 votes)
17 views18 pages

Module 1-INTRODUCTION TO C

The document provides an introduction to the C programming language, detailing its history, characteristics, and structure. It explains the evolution of C from earlier languages, its key features such as portability and dynamic memory management, and outlines the components of a C program. Additionally, it covers the compilation process, types of files used, comments, keywords, identifiers, basic data types, and variable declaration in C.

Uploaded by

puneethappi66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views18 pages

Module 1-INTRODUCTION TO C

The document provides an introduction to the C programming language, detailing its history, characteristics, and structure. It explains the evolution of C from earlier languages, its key features such as portability and dynamic memory management, and outlines the components of a C program. Additionally, it covers the compilation process, types of files used, comments, keywords, identifiers, basic data types, and variable declaration in C.

Uploaded by

puneethappi66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

INTRODUCTION TO C

The programming language C was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories to be used by the UNIX operating system.

C is one of the most powerful programming languages.

History of C

 C is a structured, high-level, machine-independent language. It allows software


developers to develop programs without worrying about the hardware
platforms where these will be implemented.
 The root of all modern languages is ALGOL, introduced in the early 1960s.
ALGOL was the first computer language to use a block structure.
 In 1967, Martin Richards developed a language called BCPL (Basic Combined
Programming Language) primarily for writing system software.
 In 1970, Ken Thompson created a language using many features of BCPL and
called it simply B. B was used to create early versions of UNIX operating
system at Bell Laboratories.
 C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell
Laboratories in 1972. C uses many concepts from these languages and added
the concept of data types and other powerful features.
 During 1970s, C had evolved into what is now known as „traditional C‟. The
language became more popular after publication of the book The C
Programming Language by Brian Kerningham and Dennis Ritchie in 1978. The
book was so popular that the language came to be known as „K&R C‟ among
the programming community.
 To assure that the C language remains standard, in 1983, American National
Standards Institute (ANSI) appointed a technical committee to defi ne a
standard for C. The committee approved a version of C in December 1989,
which is now known as ANSI C.
 It was then approved by the International Standards Organization (ISO) in
1990. This version of C is also referred as C99.

Characteristics of C
C is a robust language whose rich set of built-in functions and operators can be used to
write complex problems.

Some of the important characteristics of C are:

 It is a highly structured language.


 It uses features of high-level languages.
 It can handle bit-level operations.
 C is a machine-independent language and, therefore, highly portable.
 It supports a variety of data types and a powerful set of operators.
 It supports dynamic memory management by using the concept of pointers.
 It enables the implementation of hierarchical and modular programming with
the help of functions.
 C can extend itself by addition of functions to its library continuously.
 C supports loose typing. (a character can be treated as an integer and vice
versa.)
 C supports pointers to refer computer memory, array, structures and functions
 C is a core language as many other programming languages (such as C++, Java
or Perl) are based on C.
 C is a portable language i.e. a program written in one computer can be run on
another computer with little or no modification.
Uses of C.

 C language is primarily used for system programming.


 C is widely accepted by professionals that compilers, libraries and
interpreters of other programming languages are implemented in C.
 For portability and convenience reasons, C is sometimes used as an
intermediate language for implementation of other languages.
 C is widely used to implement end-user applications.

Structure of a C Program
A C program is composed of preprocessor commands, a global declaration section and
one or more functions.

The structure of a C program can be mainly divided into six parts, each having its
purpose. It makes the program easy to read, easy to modify, easy to document, and
makes it consistent in format.

Section Description
Documentation Consists of the description of the
program, programmer's name, and
creation date. These are generally written
in the form of comments.
Link All header files are included in this
section which contains different functions
from the libraries. A copy of these header
files is inserted into your code before
compilation.
Definition Includes preprocessor directive, which
contains symbolic constants.
E.g.: #define allows us to use constants in
our code. It replaces all the constants with
its value in the code.
Global Declaration Includes declaration of global variables,
function declarations, static global
variables, and functions.
It is a variable/function which is declared
after the preprocessor directives and
before the main() function.
main() function For every C program, the execution starts
from the main () function. It is mandatory
to include a main () function in every C
program. The statements in C program
are written in a logical sequence to
perform a specific task.
Subprograms Includes all user-defined functions
(functions the user provides). They can
contain the inbuilt functions and the
function definitions declared in the
Global Declaration section. These are
called in the main() function.

Preprocessor directives contain special instructions that indicate how to prepare


program for compilation.

Eg: #include, #define

All functions (including main()) are divided into two parts- the declaration section
and the statement section. The declaration section precedes the statements and is used
to describe the data that will be used in the function.

The data declared within a function are known as local declaration as that data will
be visible only within that function. The lifetime of the data will be only till the
function ends. The statement section in the function contains the code that
manipulates the data to perform a specified task.

WRITING THE FIRST C PROGRAM

#include<stdio.h>
void main()
{
printf(“\n Welcome to the world of C”):
}
#include <stdio.h>
This is a pre-processor command. All pre-processor commands start with hash(#) symbol.
The # include statement tells the compiler to include the standard input output library or
header files The stdio.h header file contains functions for input and output of data . The
printf() function is defined in stdio.h .

void main()
void is the return value of the main function. The program execution will begin from main().
The two curly brackets{} are used to group all the related statements of the main function.
All the statements between the braces form the function body. The function body contains a
set of instructions to perform the given task.

The printf() function is defined in stdio.h file and is used to print text on the screen. The
message to be displayed on the screen is enclosed within double quotes and put inside
brackets.

FILES USED IN A C PROGRAM

A C program uses four types of files as follows:

Source Code File


 This file includes the source code of the program.
 The extension for these kind of files are '.c'. It defines the main and many more functions
written in C.
 main() is the starting point of the program. It may also contain other source code files.
Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions
that are shared between various source files.

Advantages of header files:


1. At times the programmer may want to use the same subroutines for different programs. To
do this, he would just compile the code of the subroutine once and link to the resulting object
file in any file in which the functionalities of this subroutine are required.

2. At times the programmer may want to change or add the subroutines and reflect those
changes in all the programs. For doing this, he will have to only change the source file for the
subroutines, recompile the source code and then recompile and re-link the program.

This tells us that including a header file will make it easier at all levels of the program. If we
need to modify anything then changes are made only in the subroutines after which all the
changes will be reflected.

Standard header files


C provides us with some standard header files which are available easily.

Common standard header files are:

i) string.h – used for handling string functions.


ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.

The header files are added at the start of the source code so that they can be used by more
than one function of the same file.

Object Files

 They are the files that are generated by the compiler as the source code file is processed.
 These files generally contain the binary code of the function definitions.
 The object file is used by the linker for producing an executable file for combining the
object files together. It has a '.o' extension.

Binary Executable File


 This file is generated by the linker.
 Various object files are linked by the linker for producing a binary file which will be
executed directly.
 They have an '.exe' extension.
COMPLING AND EXECUTING A ‘C’ PROGRAM
Executing a program written in C involves a series of steps. These are:

1. Creating the program;


2. Compiling the program;
3. Linking the program with functions that are needed from the C library; and
4. Executing the program.
The below flowchart illustrates the process of creating, compiling and executing a C
program. Although these steps remain the same irrespective of the operating system, system
commands for implementing the steps and conventions for naming files may differ on
different systems.

 C is a compiled language. So once the C program is written , we must run it through a C


compiler that can create an executable file to be run by the computer.
 The compiler translates the source code into an object code. The object code contains the
machine instructions for the CPU and calls to the operating system application
programming interface (API).
 The object file is processed by linker and converted to the executable file.
Source file
Object files
I
Preprocess Compiler Linker
or

Library files
Library files
Binary
Executable file

The compilation process is done in 2 steps:


1. In the first step, the pre-processor program reads the source file as text, and produces
another text file as output. Source code lines which begin with the #symbol are written in a
pre-processor language. The output of pre-processor is a text file. This file is ready to be
processed by the compiler.
2. The linker combines the object file with library routines to produce the final executable
file.

Comments in C
Comments can be used to explain code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. The compiler ignore the comments when
forming the object file.

Comments can be either line comment or block comments.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment

printf("Hello World!");

This example uses a single-line comment at the end of a line of code:

printf("Hello World!"); // This is a comment

Block Comments

Block comments are also known as Multi-line comments.

Multi-line comments start with /* and ends with */.


Any text between /* and */ will be ignored by the compiler:

Example

/* The code below will print the words Hello World!

To the screen, and it is amazing */

printf(“Hello World!”);

Keywords

Keywords are a sequence of characters that have a fixed meaning. C has a set of reserved
keywords. They are written in lower case. In all there are 32 keywords.

Following table provides with all the keywords:

Auto Break Case char


Const continue default double
Else Enum extern float
For Goto Int long
Register Return short signed
Sizeof Struct switch typedef
Union unsigned Void volatile
Do If static while

Identifiers

Identifiers help us to identify data and other objects in the program. Identifiers are the names
given to the variables, constants, functions and the user-defined data. They may consist of an
alphabet, digit or an underscore.Identifiers are written by keeping in mind a set of rules.

The rules are as follows:

1. Special characters or punctuation marks like #, $, ^,?, . etc cannot be included. But an '_'
underscore can be used.
2. Two successive underscores cannot be used at the same time.
3. Any keywords cannot be used as an identifier.
4. Identifiers are case-sensitive.
5. The identifier name can begin with an alphabet or an underscore.
6. An identifier can be of any reasonable length, but it should not contain more than 31
characters.
7. The identifier name is case sensitive. For example, „FIRST‟ is different from „first‟.
Some valid identifier name are as follows:
Roll_num, marks, DeptCode, EMP_NO

Basic data types in C

C language provides very few basic data types.


C does not provide any data-type for storing text as it is made up of individual characters.

Following table shows the basic data-types:

Data-type Keyword Storage size in Range Use


bytes
Character char 1 -128 to 127 For storing characters.
Integer int 2 -32768 to 32767 For storing integer numbers.
Floating float 4 3.4E-38 to For storing the floating point
Point 3.4E+38 numbers.
Double double 8 1.7E-308 to For storing the big floating point
1.7E+308 numbers.
Valueless void 0 Valueless

In the above table we have a data-type called 'void' which has no value but is used in the
following cases:
 For specifying the return type of the function when the function returns no value.
 For specifying the parameters of the function when no arguments are accepted by the
function from the caller.
 For creating generic pointers.
The unsigned and signed char is used for ensuring the portability of the programs which store
the non-character data as char.

Following table shows the different signed and unsigned char:

Data-type Storage size in bytes Range


char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed short int 2 -32768 to 32767
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
signed long int 4 -2147483678 to 2147483647
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

Variables

 A meaningful name given to a data storage location in the computer memory is known as
a Variable.
 When a variable is used it actually refers to an address of the memory where the data is
stored.
 A variable name can comprise of letters, digits and underscore characters.
 The first character has to be an alphabet.
 There should be no commas or blank spaces between the variable names.

Variable declaration

All the variables that are used in the program need to be declared.
Syntax:
data-type variable-name;

In the above syntax a data-type is declared along with a variable name.


Meaningful names should be given to the variables.
Example:

int emp_code;

float salary;

Variables can be declared anywhere in the program according to their needs.


Multiple variables can also be declared in one statement but the data-type has to be the same.

Example:
float salary, bonus;

Generally variables are declared in three places as follows:


1. Local variable is declared inside the function.

2. Formal parameters are declared in the definition of the function parameters.


3. Global variables are declared outside all the functions.

Constants
The identifiers whose value do not/ cannot change are known as Constants.

Variables can change their values but constants will never change their value.

Types of constants

There are three types of constants:

1. Integer constants

 An integer quantity which contains a sequence of digits is known as an Integer


constant. There are no decimal points.
 They can be either positive or negative.
 Blanks and commas are not allowed.
 Its value must lie within the range of its values.
Example: A decimal integer which consists of any combinations of the digits from 0 to 9.
0 5250 9990
Example: An octal integer constant which is a combination of digits from 0 through 7. Its
first digit should always be a 0.

0 03 056
Example: Hexadecimal integer begins with 0x or 0X followed by the combination of the
digits from 0 through 9 and a through f.

0x 0x4 0xcdf
Certain suffixes are given to the constants.
The suffixes are given for the following types:
Long – I or L

Unsigned long – ul or UL.

Example:
6000U unsigned (decimal)

0x3000U unsigned (hexadecimal)

3421ul unsigned long(decimal)

0325U unsigned (octal)

2.Floating point constants

These type of constants contain a decimal point or an exponent. They can be either negative
or positive. Commas or blanks are not allowed within a real constant.

Example: Floating point constants

+3.2f-4 -0.3e-3 325.0 -33.75

Unlike the integer constants they too have a suffix for the following type:

Float– f or F

Long double – I or L

3. Character constant

They consist of a single character which are enclosed in single quotes.


Example: Character constant

'b' '@' '5'

The characters are stored by using the machines character set using the ASCII code.

4. String constant

 A string constant is a sequence of characters enclosed in double quotes. Hence, “a” is


not the same as „a‟.
 The characters comprising the string constant are stored in successive memory
locations. When a string constant is encountered in a C program , the compiler records
the address of the first character and appends a null character („\0‟) to the string to
mark the end of the string. Thus the length of the string constant is equal to the
number of characters in the string plus 1.

Declaring constants.

 A constant can be declared by using the const keyword and assigning it a value.

Example: Simple constant

const float pi = 3.14;

The const keyword tells us that the value of pi can never be changed.

 Other way of declaring the constant is by using the pre-processor command define.
#define can be placed anywhere in the program

Example: declaring a constant by using a pre-processor

#define pi 3.14159

INPUT/OUTPUT STATEMENTS IN C

i) printf()

 The printf() function stands for print formatting


 This function is used for displaying the output on the screen i.e the data is moved from
the computer memory to the output device.
 For this, the printf() function takes data values and functions specified in a control string
and passes the resulting text stream to the standard output.

Syntax:
printf(“control string”, arg1, arg2, …..);

In the above syntax, 'control string' will contain the information that is formatted. They are
the general characters which will be displayed as they are.
arg1, arg2 are the output data items.

The prototype of the control string is as follows:

%[flags][width][.precision][length specifier]

Each control string must begin with a % sign.


Flags specify output justification such as decimal point, numerical sign, trailing zeroes, etc.
Sr.No. Flags & Description

1 -
Left-justify within the given field width; Right justification
is the default

2 +
Forces to precede the result with a plus or minus sign (+ or
-) even for positive numbers. By default, only negative
numbers are preceded with a -ve sign.

3 (space)
If no sign is going to be written, a blank space is inserted
before the value.

4 #
Used with o, x or X specifiers the value is preceded with 0,
0x or 0X respectively for values different than zero. Used
with e, E and f, it forces the written output to contain a
decimal point even if no digits would follow. By default, if
no digits follow, no decimal point is written. Used with g
or G the result is the same as with e or E but trailing zeros
are not removed.

5 0
Left-pads the number with zeroes (0) instead of spaces,
where padding is specified (see width sub-specifier).

Width specifies the minimum number of characters to print after being padded with zeros or
blank spaces , i.e. it specifies the minimum number of positions in the output.

Precision specifies the maximum number of characters to print.


Sr.No. .precision & Description

1 .number
For integer specifiers (d, i, o, u, x, X) − precision specifies the
minimum number of digits to be written. If the value to be written is
shorter than this number, the result is padded with leading zeros. The
value is not truncated even if the result is longer. A precision of 0
means that no character is written for the value 0. For e, E and f
specifiers − this is the number of digits to be printed after the decimal
point. For g and G specifiers − This is the maximum number of
significant digits to be printed. For s − this is the maximum number of
characters to be printed. By default all characters are printed until the
ending null character is encountered. For c type − it has no effect.
When no precision is specified, the default is 1. If the period is
specified without an explicit value for precision, 0 is assumed.
2 .*
The precision is not specified in the format string, but as an additional
integer value argument preceding the argument that has to be
formatted.

Length
Sr.No. Length & Description

1 h
The argument is interpreted as a short int or unsigned short int (only
applies to integer specifiers: i, d, o, u, x and X).

2 l
The argument is interpreted as a long int or unsigned long int for integer
specifiers (i, d, o, u, x and X), and as a wide character or wide character
string for specifiers c and s.

3 L
The argument is interpreted as a long double (only applies to floating point
specifiers: e, E, f, g and G).

Specifier field

Format Specifiers Type of Output

A decimal integer or signed


%d or %i
integer

%c Signed character

%f Signed float

%e A floating-point number

A string or sequence of
%s
character

%lf Double

%Lf Long double


%o Octal integer
%u Short unsigned integer

%ld Long decimal integer

%x Hexadecimal integer

Print memory address in the


%p
hexadecimal form

Example: Demonstrating the printf function


printf(“Enter a value:”);

printf() will generally examine from left to right of the string.


 The characters are displayed on the screen in the manner they are encountered until it comes
across % or \.
 Once it comes across the conversion specifiers it will take the first argument and print it in
the format given.

ii) scanf()

 scanf() stands for scan formatting.


 It is used to read formatted input from the keyboard.
 This function takes a text stream from the keyboard, extracts and formats data from the
steam according to the format control string and then stores the data in the specified
program variables.

Syntax:
scanf (“control string”, &arg1, &arg2, …..);

Format string consists of the conversion specifier. The control string specifies the type
and format of the data that has to be obtained from the keyboard and stored in the
memory locations pointed by the arguments arg1,arg2,etc.

Arguments can be variables or array name and represent the address of the variable.
Each variable must be preceded by an ampersand (&). Array names should never begin
with an ampersand.

The prototype of control is [[%*][width][modifiers]type=]

Example: Demonstrating scanf()


int avg;

float per;

char grade;
scanf(“%d %f %c”,&avg, &per, &grade);

scanf works totally opposite to printf. The input is read, interpret using the conversion
specifier and stored it in the given variable.
 The conversion specifier for scanf is the same as printf.
 Rules to be followed while using scanf():
 scanf reads the characters from the input as long as the maximum number of
characters has been processed , a whitespace character is encountered or an error is
encountered. The order of the characters that are entered are not important.
 It requires an enter key in order to accept an input.
 Every variable must have a conversion specification associated with it.
 There must be a variable address for each conversion specification.
 A fatal error will be generated if the format string ended with a white space character.
 The data entered by the user must match the character specified in the control string.
 Input data values must be separated by spaces.
 Any unread data value will be considered as a part of the data input in the next call to
scanf.
 When the field width specifier is used, it should be large enough to contain the input
data size.

You might also like