Unit II Basics of C Programming
Unit II Basics of C Programming
Basics of C Programming
06 Hours
10 Marks
Industry identified competency addressed by this course:
- Develop C programs to solve broad-based computer related problems.
2.2.2 Tokens
Tokens are individual words and punctuation marks in a passage of text.
These are the smallest individual units. In C program, they are called as C
tokens.
e.g.
main( )
{
printf(“Welcome”);
getch( );
}
In the above C program, C tokens are as follows (each token shown on separate
line):
main
(
)
{
printf
(
“Welcome”
)
;
getch
(
)
;
}
3 of 21
Keywords int do while
"C Programming"
Strings "Hello"
Tokens
Identifiers main sum
Operators + - * /
Special ( ) [ ]
Symbols
2.2.3 Keywords
Keywords are the words whose meaning is already explained to the C
compiler. They have fixed meanings and these meanings cannot be changed. The
keywords cannot be used as variable name or function name. The keywords are
also referred as reserved words. List of keywords is shown in table 2.1. Some C
compilers may use additional keywords.
Table 2.1: Keywords in C
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
2.2.4 Constants
A constant is an entity that does not change during execution of a
program. Constants can be of different types as integer constants, real constants,
character constants, string constants etc.
Integer constants must have at least one digit. They cannot have decimal
point. They can be positive or negative. Commas, blank spaces and currency
signs like ₹ or $ are not allowed. Some of valid integer constants are shown
below.
4312 -76 31906 +34 0 065
4 of 21
Integer constants cannot represent some real life values like height,
distance etc. These values can be represented by real constants. These are also
called as floating point constants. They must have at least one digit and a
decimal point. There are two ways of representing these constants – fractional
form and exponential form. Some of valid real constants in fractional form are:
0.000091 -236.213 +43.26 -.5 .37 21.
Some of valid real constants in exponential form are:
3.543e7 -5.1E3 0.33E8 6.8945e-6 -2.571E-4 3.2e+5
A character constant contains a single character (an alphabet, a digit or a
special symbol) encoded within a pair of single quote marks (inverted commas).
Some valid character constants are,
„F‟ „y‟ „@‟ „2‟ „ ‟ „70‟
Each character is represented internally by a ASCII value. So the last
constant „70‟ represents „F‟.
Certain character constants can be defined using escape sequences.
Though these sequences look like two characters, they represent only one
character. Some of escape sequences are given in table 2.2.
Table 2.2: Escape Sequences
Escape Meaning Escape Meaning
Sequence Sequence
\a Alert (Bell) \b Backspace
\f Form Feed \n Newline
\r Carriage Return \t Horizontal Tab
\v Vertical Tab \\ Backslash
\? Question Mark \‟ Single Quote (single
inverted comma)
\” Double Quote (double
inverted comma)
A string constant is represented by sequence of characters enclosed in pair
of double quotes (inverted commas). Some valid examples are:
“Welcome to C programing” “15August” “Hello!!!” “1947”
If the same constant value is to be used for many times in a program, we
may use a concept of symbolic constant. Symbolic constants can be defined
using a preprocessor directive #define. Syntax is given below
#define symbolic_name value
The symbolic_name is defined using the rules same as that of identifier
(discussed in 2.2.6). But it is good habit to use uppercase letters (although not
compulsory) while giving symbolic constants. Some examples are given below.
#define SIZE 25
#define SAMPLE “Hello”
2.2.5 Strings
It is discussed in 2.2.4 as string constants.
5 of 21
2.2.6 Identifiers
Identifiers refer to the name of variable, function, array etc. They are
user-defined names. Following are the rules which should be followed while
defining identifiers.
1. Identifier should contain alphabets (upper-case and lower-case
letters), digits or underscore. Other characters are not allowed.
Even white spaces are not allowed.
2. Identifier can be a combination of 1 (minimum) to 31 (maximum)
characters. Even if we use more than 31 characters, they do not
have any significance.
3. First character in the identifier should not be a digit. (i.e. It could be
either an alphabet or an underscore.)
4. Keyword cannot be used as identifier.
C is case-sensitive. i.e. It identifies difference between lowercase (small)
and uppercase (capital) letters. So, all the following variable names are different.
val Val VAL vAL VAl vaL
Variable is an entity whose value can be changed during execution of a
program. Actually, the variable names are the names given to locations in
memory (primary memory – which is most commonly RAM).
Generally, while naming local variables short-names are used and while
naming global or external variables long-names are used.
30778 •x
273 •y
8721 •z
2.2.7 Operators
An operator is a symbol that tell computer to perform some mathematical
or logical operation. Operators in C can be classified into number of categories.
They are:
- Arithmetic operators
- Relational operators
- Logical operators
6 of 21
- Assignment operators
- Increment and decrement operators
- Conditional operators
- Bitwise operators
- Special operators
Some operators are binary operators (require two operands), some are
unary operators (require one operand only) and there is one ternary
operator (require three operands).
7 of 21
Truth table for above logical operators is shown in table 2.6.
Table 2.6: Truth Table for Logical Operators
exp1 exp2 Value of
! exp1 exp1 && exp2 exp1 || exp2
TRUE TRUE FALSE TRUE TRUE
TRUE FALSE FALSE FALSE TRUE
FALSE TRUE TRUE FALSE TRUE
FALSE FALSE TRUE FLASE FALSE
8 of 21
interest_rate = (age >= 60) ? 9.5 : 8.75;
If value of variable age is greater than or equal to 60, 9.5 is assigned
to variable interest_rate. Otherwise, 8.75 is assigned to variable
interest_rate.
2.2.7.9 Expressions
An expression is a combination of variables, constants and
operators arranged as per the syntax of the language. Some examples of
valid expressions in C are shown in Table 2.11.
Table 2.11: C Expresssions
Actual Expression Expression in C
a(b+c) a*(b+c)
x/y
3x+2y 3*x+2*y
a*b+c
7*x*x – 4*x + 7
p/q
1/2*b*l Or b*l/2
(a+b+c) / (d+e)
9 of 21
The expressions are normally evaluated using assignment
statements in the following form.
variable = expression;
When above kind of statement is executed, the expression is
evaluated first and then the result of expression is assigned to the
variable.
Whole Numbers
int, unsigned int, Characters
short int, unsigned short int, char, unsigned char
long int, unsigned long int
Fractional Numbers
void
float, double, long double
11 of 21
For whole numbers, integer data types are used. They can be either signed
(with a sign) or unsigned (without a sign). Generally an integer occupies one
word of storage. (For 16-bit compilers like Turbo C or Turbo C++ a word is of 16
bits and for 32-bit compiler like Visual Studio or gcc a word is of 32 bits). So, size
of int is either 2 bytes (For TC, TC++) or 4 bytes (for VC/VC++, gcc). In both the
cases, size of short int is 2 bytes and size of long int is 4 bytes.
A single character can be defined as a char. It requires one byte (8 bits) of
storage. We can use qualifiers signed (-128 to +127) and unsigned (0 to 255) with
char also.
Fractional numbers (or real numbers) can be used by using float, double or
long double data types. Data type float requires 4 bytes of storage. It supports
precision of 6 digits. A double data type uses 8 bytes of storage and it supports
precision of 14 digits. For having more precision than above, long double is
used which requires 10 bytes of storage.
The void type has no values. It is usually used for specifying type of
function (i.e. function‟s type is void when it does not return any value).
Table 2.13 shows the list of data types supported in C along with their
size, range and format specifiers.
Table 2.13: Data Types in C (for 16-bit compiler like TC)
Category Data Type Size in Format
Range
of Data Bytes Specifier
Char
or 1 -128 to +127 %c
Character
signed char
unsigned char 1 0 to 255 %c
%d (decimal)
Int
%o (octal)
or 2 -32768 to + 32767
%x or %X
signed int
(hexadecimal)
unsigned int 2 0 to 65535 %u
short int
Whole or 2 -32768 to + 32767 %d
Number signed short int
unsigned short
2 0 to 65535 %u
int
long int
-2147483648 to
or 4 %ld
+2147483647
signed long int
unsigned long int 4 0 to 4294967295 %lu
float 4 3.4e–38 to 3.4e+38 %f or %e
Fractional
double 8 1.7e–308 to 1.7e+308 %lf or %g
or Real
3.4e–4932 to
Numbers long double 10 %Lf
1.1e+4932
When a variable is declared a memory space is allocated (as per its data
type) and the variable points to the allocated memory (the allocated memory
location initially contains garbage value).
The variables can be declared in two places only. They are
i) Outside all functions
Variables declared here are called global variables. These variables
are accessible or visible to all the functions in the program. Scope
of such variables is global.
ii) Immediately after „{‟ in a block
These variables are local variables. They are accessible or visible
within the block where they are defined. Scope of such variables is
local.
13 of 21
2.3.1 Generating Output
In a computer, normally a keyboard is treated as standard input and a
monitor is treated as a standard output. A set of C library functions defined in a
header file „stdio.h‟ is used for handling input and output of a C program.
Therefore before using these functions in our program we have to include stdio.h
file (#include<stdio.h>).
Functions defined in a file „stdio.h‟ and which are used for generating
output are,
putchar( ) puts( ) printf( )
For putting a single character on standard output, putchar( ) function is
used.
e.g.
char var1=‟C‟;
putchar(var1);
putchar(„M‟);
Output:
CM
We can use puts( ) function for putting a string on the standard output. It
also appends a newline character at the end.
e.g.
puts(“Welcome”);
puts(“to C Programming”);
Output:
Welcome
to C Programming
We can use printf( ) function for displaying formatted output. (printf
stands for print-formatted)
Example 2:
printf(“Hello\nEverybody”);
Output:
Hello
Everybody_
Each conversion specification (or control sequence) begins with a % and
ends with a conversion character (which is similar to format specifiers listed in
table 2.13).
Example 3:
int a=28;
float x=23.76;
printf(“Value of a is %d and value of x is %f”,a,x);
Output:
Value of a is 28 and value of x is 23.76_
In between % character and conversion character, following optional
things can be used.
–w.p
The – symbol can be used for left justifying the output value. Sometimes,
instead of –, 0 can be used. In such case the blank spaces are padded with 0. „w‟
is a number specifying the number of columns for the output value. „p‟ is a
number specifying the number of digits after the decimal point. Default precision
for float is 6. (Important: while specifying values w and p, care should be taken
that ). In case of strings, p is number of characters to be displayed from
the string.
Some format strings and their outputs are shown below.
Formatted outputs for Integers
(assuming value of a as 483)
Format Output
printf(“%d”,a); 4 8 3
printf(“%7d”,a); 4 8 3
printf(“%–7d”,a); 4 8 3
printf(“%2d”,a); 4 8 3
printf(“%07d”,a); 0 0 0 0 4 8 3
printf(“%7.2d”,a); 0 0 0 0 4 8 3
printf(“%7x”,a); 0 0 0 0 1 e 3
printf(“%7X”,a); 0 0 0 0 1 E 3
printf(“%7o”,a); 0 0 0 0 7 4 3
15 of 21
Formatted outputs for Fractional or Real Numbers
(assuming value of b as 48.356)
Format Output
printf(“%f”,b); 4 8 . 3 5 5 9 9 9
printf(“%e”,b); 4 . 8 3 5 6 0 0 e + 0 1
printf(“%9.3f”,b); 4 8 . 3 5 6
printf(“%9.2f”,b); 4 8 . 3 6
printf(“%–9.2f”,b); 4 8 . 3 6
printf(“%12.4e”,b); 4 . 8 3 5 6 e + 0 1
printf(“%12.2e”,b); 4 . 8 4 e + 0 1
printf(“%-11.2e”,b); 4 . 8 4 e + 0 1
17 of 21
Example 1:
int a;
printf(“Enter a value: ”);
scanf(“%d”,&a);
/* Here a common mistake is – absence of & symbol. This error is not
identified by compiler and therefore very much problematic. We should
carefully avoid the error */
printf(“You have entered value of a as %d”,a);
Output:
Enter a value: 251
You have entered value of a as 251_
The format string may contain following type of objects,
- Blank spaces, tabs and ordinary characters (for formatting the input
field).
- Control sequence or conversion specification (they are replaced
sequentially by arguments specified after the formats).
Conversion specification (or a control sequence) consists of a % symbol,
optional number specifying maximum field width (not for float) and a conversion
character. It may contain * symbol (for skipping or suppressing the inputted
field) in between % symbol and conversion character. Some examples are
discussed in table 2.15 and table 2.16.
2.3.3 Comments
Comments are used for documentation purpose. This is a way of inserting
remarks and reminders into a program without affecting its content. Comments
are the statements which are not executed (i.e. they are ignored by compiler).
In C, comments can be written using combination of /* and */. But proper
care should be taken while writing comments. We should not forget to end the
comment. Otherwise the whole program after it will be treated as a comment.
e.g.
/* This is a program for performing …………….. */
19 of 21
main( )
{
int a,b,c; /* a and b is used for input and c is used for storing result */
………………
}
Source Object
Preprocessor Compiler
Program in C Program
Sample Questions
21 of 21