Chap 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Introduction to C

programming
Introduction
• A programming language is designed to help process certain kinds of
data consisting of numbers, characters and strings and to provide
useful output known as information.
• The task of processing a data is accomplished by executing a
sequence of precise instructions called a program.
• This instructions are formed using certain symbols and words
according to some rigid rules known as syntax rules.
Character set
• The characters in C are grouped into following categories:
1. Letters
2. Digits
3. Special characters
4. White spaces

The entire character set is given in next slide


• Letters: Uppercase A….Z, lowercase a…z
• Digits: All decimal digits 0…9
• Special Characters: ,.;:?’”!|/\~_$%&^*+-<>(){}[]#
• White spaces: blank space, horizontal tab, carriage return, new line,
form feed
C Tokens
• The smallest unit of a C program is called C token.
• C has six types of token:
1. Keywords (int, float etc…)
2. Identifiers (a, n, x, y etc…)
3. Constants (12,24,-15, etc…)
4. Strings (“Apple”, “Banana”, etc…)
5. Special symbols ([] {} etc…)
6. Operators (+, -, *, etc…)
Keywords:
• Keywords are C token which has a special meaning that cannot be changed.
• Keywords are the basic building blocks for program statement.
• Keywords are written in small letters
• The list of keywords are:
auto, break, case, char, const, continue, default, do, double, else, enum, extern,
float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct,
switch, typedef, union, unsigned, void, volatile, while
Identifiers:
• Identifiers refers to the names of variables, functions, arrays.
• These are user-defined names consist of sequence of letters, digits and
underscore with a letter as a first character.
• Both uppercase and lowercase are permitted, although lowercase are
commonly used.
Rules for naming an identifiers:
1. First character must be letter (or underscore)
2. Must consist of only letter, digit and underscore
3. Only first 31 characters are significant
4. Keywords cannot be used as an identifiers
5. Must not contain white spaces
6. Identifiers are case sensitive
Constants:
• Constants in C refer to fixed values that do not change during the execution of
a program.
• C supports several types of constant.
Constant

Numeric Character
Constant Constant

Integer Single Character


Real Constant String Constant
Constant Constant
Integer constants
• Integer constants refer to the sequence of digits.
• There are three types of integer: decimal integer, octal integer, hexadecimal
integer.
• Embedded whites spaces, commas, non digits character are not permitted
between digits.
• The largest integer value that can be stored is machine dependent.
• It is 32767 in 16 bit machines and 2147483647 in 32 bit machines.
• It is also possible to store larger integer constants on these machines by
appending qualifiers such as U, L and UL to the constants.
Example:
Assume that the machine is 16 bit
Then
printf(“%d %d %d”, 32767, 32767+1, 32767+10);
printf(“%ld %ld %ld”, 32767L, 32767L+1L, 32767L+10L);

Output:
32767 -32768 -32759
32767 32768 32777
Real Constant:
• Integer constant are inadequate to represent quantities that vary
continuously, such as distance, heights, temperature etc…
• These quantities are represented by numbers with fractional parts like 13.234
• Such numbers are called real (or floating points)
• A real number can also be represented in exponential form. For example,
215.65 may be written as 2.1565e2 in exponential form where e2 means
multiply by 102.
• The general form is:
mantissa e exponent
• Which of the following are legal numeric constant:
698354L
25,000
+5.0E10
3.5e-2
7.1 e 6
8e3.5
Single character constant:
• Single character constant or simply character constant contains a single
character enclosed within a pair of single quote marks. Example: ‘5’, ‘A’, ‘;’, ‘ ’
• Note character constant ‘5’ is not same as numeric 5.
• Character constant has integer values known as ASCII values. For example,
printf(“%d”, ‘a’);
Would print 97, the ASCII value of ‘a’. Similarly,
printf(“%c”, ’97’);
Would print a.
• Since each character constant represents an integer constant, it is possible to
perform arithmetic operations on character constants.
String Constant:
• A string constant is a sequence of characters enclosed within double quotes.
• The characters may be letters, digits, special characters and blank spaces
• Example are: “Hello!” , “2023”, “NIT MEGHALAYA” , “X”, “5+3”, “?;;;;;”
• Note: a character constant ‘X’ and string constant “X” are not equivalent.
• Single character string constant does not have integer value
Backslash character constant:
• C supports some special backslash character constants that are used in output
functions.
• For example, \n represents next line, \t represents horizontal tab space etc…
Variable:
• Variable is a data name that may be used to store a data value.
• Unlike constant that does not change during the execution of
program, variable may take different values at different times during
execution.
• Variable name has to follow the rules for identifier.
Datatypes:
• C language is rich in data types.
• The variety of data types available allow the programmer to select the type
appropriate to the needs of the application as well as the machine.
• C supports three classes of datatypes
• Primary (or fundamental or basic) data types
• Derived data types
• User-defined datatypes
void
• All C compilers support five fundamental datatypes, namely integer
(int), character (char), floating point (float), double precision floating
point (double) and void.
• Many of them offer extended datatypes such as long int, long
double.
• Integer types:
• This data type is used to store whole numbers.
• The integer storage are short int, int and long int in both signed and unsigned
forms.

Short int

int

long int
Integer Data Types
Type size(in bytes) Range Control String
short int (or) 1 -128 to 127 %h
signed short int
unsigned short 1 0 to 255 %uh
int
int (or) signed int 4 -32768 to 32767 %d or %i
unsigned int 4 0 to 65535 %u
Long int (or) 4 -2147483648 to %ld
signed long int 2147483647

Unsigned long int 4 0 to 4294967295 %lu


• Floating point datatypes:
• Floating point data types are used to store real numbers.
• float’ is used for 6 digits of accuracy.
• ‘double' is used for 14 digits of accuracy.
• More than 14 digits, ‘long double’ is used.
Floating Point Data Types
Type size(in Range Control
bytes) String
float 4 3.4E - 38 to %f
3.4 E + 38

double 8 1.7 E - 308 %lf


to 1.7 E +
308
long double 16 3.4 E - 4932 %Lf
to 1.1 E +
4932
• Character data type
• Character data type is used to store characters only.
• These characters are internally stored as integers.
• Each character has an equivalent ASCII value.
• For example, ‘A’ has ASCII value 65.
Character Data Types
Type Size(in Range Control
bytes) String
Char(or) 1 -128 to 127 %C
signed Char

unsigned 1 0 to 255 %c
Char
• void:
• The void type has no value.
• This is usually used to specify the type of functions.
Declaration of Variables
• After designing suitable variable names, it must be declare to the
compiler.
• Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies the what type of data the variable will hold.
• The declaration of variables must be done before they are used in the
program.
Primary Type Declaration
• A variable can be used to store a value of any data type.
• That is, the name has nothing to do with its type.
• The syntax for declaring a variable is as follows:
Data-type v1,v2,v3,……vn;
v1,v2,v3,…. vn are the names of variables.
• Variables are separated by commas.
• A declaration statement must end with a semicolon.
• For example, valid declarations are
• int count;
• int number, total;
• double ratio;
• int and double are the keywords to represent integer type and real
type data values respectively.
• The following table shows various data types and their keyword
equivalents:
Data type Keyword equivalent
Character char
Unsigned character unsigned char
Signed character signed char
Signed integer signed int (or int)
Signed short integer signed short int (or short int or short)
Signed long integer signed long int (or long int or long)
Unsigned integer unsigned int (or unsigned)
Unsigned short integer unsigned short int (or unsigned short)
Unsigned long integer unsigned long int (or unsigned long)
Floating point float
Double precision floating point double
Extended double precision floating point long double
User Defined type
• C supports a feature known as “type definition” that allows users to
define an identifier that would represent an existing data type.
• The user defined data type identifier can later be used to declare
variables.
• It takes the general form:
typedef type identifier;

Where type refers to an existing data type and identifier refers to the new
name given to the data type.
• The existing data type may belong to any class of type, including user
defined ones.
• Some examples of type definition are:
typedef int units;
typedef float marks;
• Here, units symbolizes int and marks symbolizes float. They can later be
used to declare variables as follows:
units batch1, batch2;
marks name1[50], name2[50];
• The main advantage of typedef is that we can create meaningful data type
names for increasing the readability of the programs.
• Another user-defined data type names is enumerated data type.
• It is defined as follows:
enum identifier {value1, value2,….. Valuen};
• The identifier is an user defined enumerated data type which can be
used to declare variables that can have one of the values enclosed
within the braces.
• After this definition, we can declare variables to be of this new type
as below:
enum identifier v1,v2,….vn;
• The enumerated variables v1,v2,…vn can only have one of the values value1,
value2,…valuen. The assignments of the following types are valid:
v1 = value3;
v5 = value1;
An example:
enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum day week_st, week_end;
week_st = Monday;
week_end = Friday;
if(week_st == Tuesday)
{
week_end = Saturday;
}
• The compiler automatically assigns integer digits beginning with 0 to
all the enumeration constants.
• That is, the enumeration constant value1 is assigned 0, value2 is
assigned 1 and so on.
• However, the automatic assignment can be overridden by assigning
values explicitly to the enumeration constants.
• Example:
enum day{Monday = 1, Tuesday,… Sunday};
Here, the constant Monday is assigned the value of 1. The remaining
constants are assigned values that increase successively by 1.
• The definition and declaration of enumerated variables can be
combined in one statement. Example:
enum day {Monday,…Sunday} week_st, week_end;
Declaration of Storage Class
• Variables in C can have not only data type but also storage class that provides
information about their location and visibility.
• The storage class decides the portion of the program within which the
variables are recognized.
• Consider the following example:
int m;
int main()
{
int i;
float bal;

function1();
}
void function1()
{
int i;
float sum;

}
• The variable m which has been declared before main is called global
variable.
• It can be used in all the functions in the program.
• It need not be declared in other functions.
• A global variable is also known as external variable.
• The variables i, bal, sum are called local variables because they are
declared inside a function.
• Local variables are visible and meaningful only inside the functions in
which they are declared.
• They are not known to other functions.
• Note that the variable i has been declared in both the functions. Any
change in the value of i in one function does not affect its value in the
other.
• C provides a variety of storage class specifiers that can be used to
declare explicitly the scope and lifetime of variables.
• There are four storage class specifiers (auto, register, static and
external) whose meaning is given below:
1. auto: local variable known only to the function in which it is
declared.
2. static: local variable which exists and retains its value even after the
control is transferred to the calling function.
3. extern: global variable known to all the functions in the file.
4. register: local variable which is stored in the register.
• The storage class is another qualifier (like long or unsigned) that can
be added to a variable during declaration as shown below:
auto int count;
register char ch;
static int x;
extern long total;
• Static and external variables are automatically initialized to zero.
• Automatic variables contain undefined values (known as garbage)
unless they are initialized explicitly.
Assigning values to variables
• Values can be assigned to variables using assignment operator = as
follows:
variable_name = constant;
Examples:
i = 0;
ch = ‘a’;
C allows multiple assignment in one line.
i = 0; ch = ‘a’;
• An assignment statement implies that the value of the variable on the
left of the equal sign is set equal to the value of the expression on the
right.
• It is also possible to assign a value to a variable at the time of
declaration (it is called as initialization)
datatype variable_name = constant;
Examples:
int i = 0;
char ch = ‘a’;
• The process of giving initial values to variables is called initialization.
• C permits the initialization of more than one variables in one
statement using multiple assignment operator.
p = s = q =10;
Here the variables p, s and q are initialized to 10.
Reading data from keyboard
• Another way of giving values to variables is to input data through
keyboard using scanf function.
• It is a general input function available in C and is very similar in
concept to the printf function.
• The general form:
scanf(“control string”,&variable1, &variable2…);
• The control string contains the format of data being received.
• The ampersand symbol & before each variable name in an operator
that specifies the variable name’s address.
• Example:
scanf(“%d”,&number);
• When this statement is encountered by the computer, the execution
stops and wait for the value of the variable number to be typed in.
• Since the control string %d specifies that an integer value is to be read
from the terminal, we have to type in the value in integer form.
• Once the number is pressed in and the ‘Return’ key is pressed, the
computer then proceeds to the next statement.
Defining symbolic constants
• Sometimes in the program, we may used certain unique constant
which is used repeatedly in the program.
• One such example is 3.142, representing the value of mathematical
pi.
• We can encounter two problems in subsequent use of such programs.
They are:
1. Problem in modification of the program
2. Problem in understanding the program.
Modifiability:
• We may like to change the value of pi from 3.142 to 3.14159 to
improve the accuracy of calculations.
• Then we will have to search the whole program and explicitly change
the value of the constant wherever it has been used.
• If any value is left unchanged, the program may produce disastrous
outputs.
Understandability:
• When a numeric value appears in a program, its used is not always
clear, especially when the same value means different things in
different places.
• For example, the number 50 may mean the number of students at
one place and the pass mark at another place on the same program.
We may forget what a certain number meant, when we read the
program some days later.
• Assignment of such constants to a symbolic name frees us from these
problems.
• A constant is defined as follows:
#define symbolic_name value
Example:
#define STRENGTH 50
#define PASS_MARK 50
#define PI 3.14159
Declaring a variable constant
• We may like the value of certain variables to remain constant during
the execution of a program.
• This can be achieved by declaring a variable with qualifier const at the
time of initialization.
• Example:
const int class_size =40;
Declaring a variable as volatile
• Another qualifier defined by C is volatile.
• It tells the compiler that a variable’s value may be changed at any
time by some external sources (from outside the program).
• Example:
volatile int date;
• The value of date may be altered by some external factors even if it
does not appear on the left hand side of the assignment statement.
• When a variable is declared as volatile, the compiler will examine the
value of the variable each time it is encountered to see whether any
external alteration has changed the value.

You might also like