Unit i Basics of c Programming 1
Unit i Basics of c Programming 1
Basics of C Programming
10 Hours
12 Marks
Industry/ Employer expected outcome of this course:
- Develop C programs that address issues with processing strings, mathematic
operations and data structures.
1.0 Introduction
1 of 30
A program is a sequence of instructions for performing a specific task.
Process of developing a program involves finding a solution to a complex
problem. To do so, there is a need of tools which enable programmer to represent
logic required in the program. Before solving any given problem we have to first
think about logical steps for finding one of the solutions for that problem. These
logical steps can be represented using different ways as
- Algorithm
- Flowchart
1.1.3 Flowchart
4 of 30
• Start / End (Terminal symbol)
• Process box
• Decision box
• Connector
• Manual Operation
5 of 30
Some sample flowcharts are given here.
START
INPUT A
INPUT B
C=A*B
DISPLAY C
END
START
INPUT A
IF
Yes A MOD 2 No
=0
END
6 of 30
Example 3: Displaying first n natural numbers. (Iterative constructs)
START
INPUT N
I=1
IF No
I <= N
Yes
DISPLAY I
I=I+1
END
7 of 30
Example 4: Finding greatest of three numbers
START
INPUT A
IF
A > B AND Yes
A>C
No
DISPLAY A is greatest
IF
B > A AND Yes
B>C
No
DISPLAY B is greatest
IF
C > A AND Yes
C>B
No
DISPLAY C is greatest
END
8 of 30
Example 5: Determining whether given number is prime or not
START
INPUT N
I=2
IF No
I<N
Yes
IF
Yes
N MOD I
=0
No
I=I+1
END
10 of 30
1.2.1 General Structure of a C Program
A C program may contain one or more sections shown in figure 1.1. Some
of the sections may be rearranged in different way.
Documentation Section
Link Section
Definition Section
Global Declaration Section
main( ) function section
section of user-defined functions
Figure 1.1: General Structure of C Program
Documentation section consists of set of comment lines. Normally it
contains name of program, author and other details. Actually it is possible to
write comments anywhere in the program.
Link section is used for linking functions from system library. When we
want to use any library function in our program, we have to include the header
file in which that function is defined. One example for doing so is shown below.
#include<stdio.h>
Definition section is used for defining symbolic constants. Symbolic
constants are discussed in 1.3 in detail.
Global variables are defined in global declaration section. These variables
are accessible by all the functions in the program.
Every C program must have a main( ) function. Execution of a C program
always starts from main( ) function. It can be defined as follows.
main( )
{
Statements ---
---
}
User-defined functions can be written either before or after the main( )
function.
11 of 30
1.3.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
(
)
;
}
"C Programming"
Strings "Hello"
Tokens
Identifiers main sum
Operators + - * /
Special ( ) [ ]
Symbols
1.3.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.
612 -71 5706 +34 0 065
13 of 30
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 1.2.
Table 1.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)
String constants are 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 in
the definition section of the program using 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 1.3.6). It is good habit to use uppercase letters (although not
compulsory) while giving names to symbolic constants. Some examples are given
below.
#define SIZE 25
#define SAMPLE “Hello”
1.3.5 Strings
It is discussed in 1.3.4 as string constants.
1.3.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 may 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.
14 of 30
C is case-sensitive. i.e. It identifies difference between lowercase (small)
and uppercase (capital) letters. So, all the following identifiers will be treated as
a different identifier.
val Val VAL vAL VAl vaL
1.3.7 Variables
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
15 of 30
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
16 of 30
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, 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 (Global declaration section)
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 declared. Scope of such variables is
local.
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
18 of 30
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 1.3).
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
19 of 30
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
20 of 30
Formatted outputs for Strings
(assuming value of d as “Hard Disk”)
Format Output
printf(“%s”,d); H a r D D i s k
printf(“%6s”,d); H a r D D i s k
printf(“%12s”,d); H a r d D i s k
printf(“%12.3s”,d); H a r
printf(“%.6s”,d); H a r D D
printf(“%–12.3s”,d); H a r
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 1.5 and table 1.6.
22 of 30
scanf(“%3d%5d”,&a,&b); 30275 765 a=302 As first field expects
b=75 width of 3, only first
3 digits are accepted
for a, remaining 2
digits are assigned to
b and value 765 will
be used in next
scanf() statement.
scanf(“%d%*d%d”,&a,&b); 87 54 62 a=87 54 will be skipped/
b=62 suppressed due to *.
scanf(“%d,%d”,&a,&b); 87,54 a=87 It expects , character
b=54 in between two
values. If it is not
given in input, it will
correctly accept the
first value but not
the second value.
scanf(“%f%f%f”,&x,&y,&z); 65.38 26.3e- x=65.38 Normal float
1 87 y=2.63 numbers
z=87.0
scanf(“%f%*f%f”,&x,&y) 65.38 26.3 x=65.38 26.3 will be skipped/
82.12 y=82.12 suppressed due to *.
scanf(“%d%f%s”,&a,&x,name); 12 87.33 a=12 Data of different
Ram b=87.12 types can be read in
name=“Ram” a single scanf( )
statement.
23 of 30
The scanf( ) function is very sensitive. Following cares should be taken
while using this function.
- Each variable to be read should have a field specification.
- Format specification in format string must match with the argument
list.
- Each argument (except format string) should be an address.
- Format string should not end with a white space.
1.5 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
- 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 (requires three operands).
25 of 30
These operators are unary operators and require a variable as their
operand.
When postfix ++ (or – –) is used with a variable in an expression,
the expression is evaluated with original value of variable and then the
variable is incremented (or decremented).
When prefix ++ (or – –) is used with a variable in an expression, the
variable is incremented (or decremented) and then the expression is
evaluated with new value of variable.
26 of 30
1.5.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 1.15.
Table 1.15: Some examples of C Expressions
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)
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.
27 of 30
~ Ones complement
* Pointer Indirection
& Address of
sizeof Size of an object
(type) Typecast (Conversion)
* Multiplication
/ Division Left to Right 3rd
% Modulus
+ Addition
Left to Right 4th
– Subtraction
<< Left shift
Left to Right 5th
>> Right shift
< Less than
<= Less than or equal to
Left to Right 6th
> Greater than
>= Greater than or equal to
== Equality
Left to Right 7th
!= Inequality
& Bitwise AND Left to Right 8th
^ Bitwise Exclusive OR Left to Right 9th
| Bitwise OR Left to Right 10th
&& Logical AND Left to Right 11th
|| Logical OR Left to Right 12th
?: Conditional expression Right to Left 13th
=
*=
/=
%=
+=
–= Assignment operators Right to Left 14th
&=
^=
|=
<<=
>>=
, Comma operator Left to Right 15th
1.6.1 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 …………….. */
main( )
{
28 of 30
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
30 of 30