Unit II Basics of C Programming

You might also like

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

Unit II

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.

Course Outcome addressed by Unit:


- Write simple C programs using arithmetic expressions.

Learning Outcomes those are to be achieved through practical:


- Write/Compile/Execute simple C program (Develop minimum two programs using
constants, variables, arithmetic expression). (Expt. No. 1) (Compulsory)
- Write/Compile/Execute simple C program (Develop minimum two programs using
increment/decrement operators, exhibiting data type conversion). (Expt. No. 2)
(Compulsory)
- Write simple C program to convert temperature in Fahrenheit to Celsius. (Expt. No. 3)
(Compulsory)
- Write simple C program to calculate area & perimeter of rectangle and area and
circumference of circle. (Expt. No. 4) (Compulsory)

Major Learning Outcomes (Cognitive Domain):


2a. Identify given building blocks of C program
2b. Write simple C program using given arithmetic expressions
2c. Write simple C program demonstrating the given data type conversion
2d. Write I/O statements for given data

Affective Domain Outcomes:


- Follow safety practices.
- Practice energy conservation.
- Follow ethical practices.

Topics and Subtopics:


2.1.Introduction to C – History of C, General structure of a C program, Header files,
main( ) function
2.2.Data concepts – Character set, tokens, keywords, identifiers, variables, constants, data
types, C operators, arithmetic operators, arithmetic expressions, declaring variables,
data type conversion
2.3.Basic input output – Input and output statements, using printf( ) and scanf( ), character
input/output statements, Input/output formatting, use of comments

Suggested specification table:


Distribution of Theory Marks
Remember Level Understand Level Apply and Above Level Total Marks
02 04 04 10
This specification table provides general guidelines to assist students for their learning
and to teachers to teach and assess students with respect to attainment of Learning
Outcomes (LOs). The actual distribution of marks at different taxonomy levels (R, U and
A) in the question paper may vary from above table.
1 of 21
2.1.1 History of C
„C‟ is a programming language that was developed at AT & T‟s Bell
Laboratories of USA in 1972. It was designed and written by Dennis Ritchie.
Dennis Ritchie and Ken Thompson were working on Basic Common
Programming Language (BCPL). They were thinking its name as B. But
afterwards some features were added by them. So, the name was given as C (As
„C‟ comes after „B‟).
Without any advertisement C‟s reputation spread and so many
programmers preferred „C‟ over other older languages like FORTRAN, PL/I or
Pascal. C became so popular; because it is reliable, simple and easy to use.

2.1.2 Where C stands?


Advanced programming languages like C++ and Java are evolved from C.
These languages are having additional concepts and newer approach to
programming. So it is necessary to learn C before studying these languages.
Major parts of popular operating systems like Windows, Linux and UNIX
are written in C.
C is a robust language with rich set of built-in functions. C Compiler
combines features of assembly language with high level language features. So
system software as well as business packages can be developed using C.

2.1.3 General Structure of a C Program


A C program may contain one or more sections shown in figure 2.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 2.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. 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 pogram
always starts from main( ) function. It can be defined as follows.
main( )
{
Statements ---
---
}
2 of 21
User-defined functions can be written either before or after the main( )
function.

2.2.1 C Character Set


An alphabet, digit or any special symbol used to represent information is
called a character. Valid characters allowed in C are as follows:
Alphabets A, B, C, …, X, Y, Z
a,b,c, …, x, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols ~!@#%^&*()_–+=
{}[]:;“„<>,.?/\|
White spaces are ignored by compiler until they are part of string
constant.

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

C has six types of tokens. They are shown in figure 2.2.

3 of 21
Keywords int do while

Constants -10 27.89

"C Programming"
Strings "Hello"
Tokens
Identifiers main sum

Operators + - * /

Special ( ) [ ]
Symbols

Figure 2.2: C Tokens

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

0553 0xa2 0X5a3 0x2B 0XFF 123456789L

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

Figure 2.3: Memory locations when variables x, y and z are declared


(Values are random/ garbage)

23 • After execution of x=23;

-12 • After execution of y=-12;

3564 • After execution of z=3564;

Figure 2.4: Values of variables x, y and z after execution of assignment


statements shown

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).

2.2.7.1 Arithmetic Operators


C provides all the basic arithmetic operators. They are shown in
Table 2.3. These operators can operate on built-in data types of C.
Table 2.3: Arithmetic Operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo Division (used with only integers)

2.2.7.2 Relational Operators


For taking certain decisions, we have to compare two entities. This
can be done with the help of relational operators shown in Table 2.4.
Table 2.4: Relational Operators
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
An expression containing relational operator is called as relational
expression. Value of relational expression is either one (TRUE) or 0
(FALSE).

2.2.7.3 Logical Operators


If we want to combine two relational operators or if we want to
negate a relational expression, logical operators are used. They are shown
in Table 2.5.
Table 2.5: Logical Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

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

2.2.7.4 Assignment Operators


These operators are used for assigning result of an expression to a
variable. The assignment operators supported by C are shown in Table
2.7.
Table 2.7: Assignment Operators
Operator Meaning
= Normal assignment
+= x+=12; → x=x+12;
–= x– =7; → x=x–7;
*= x*=2; → x=x*2;
/= x/=2; → x=x/2;

2.2.7.5 Increment and Decrement Operators


These operators are used for increasing or decreasing value of a
variable by 1.
Table 2.8: Increment and Decrement Operators
Operator Meaning
++ Post-increment or Pre-increment
–– Post-decrement or Pre-decrement
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.

2.2.7.6 Conditional Operators


C provides a ternary conditional operator pair as „? :‟ which can be
used in the following form.
exp1 ? exp2 : exp3
Here exp1 is relational expression. At first, exp1 is evaluated. If the
result of exp1 is TRUE, exp2 is evaluated. If the result of exp1 is FALSE,
exp3 is evaluated.
e.g.

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.7 Bitwise Operators


C provides bit-wise operators for manipulation of data at bit-level.
These operators operate on integers.
Table 2.9: Bitwise Operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right

2.2.7.8 Special Operators


C also provides some special operators which are shown in Table
2.10.
Table 2.10: Special Operators
Operator Meaning
, For linking the related expressions together
sizeof Returns number of bytes the operand occupies
& Address of operator
* Indirection / dereferencing operator
The comma-linked expressions are evaluated left to right. The value
of right-most expression becomes the value of combined expression.

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.

2.2.7.10 Operator Precedence and Associativity


When an expression contains multiple operators, operator
precedence is used to determine how the expression is evaluated. Operator
precedence is defined in the form of different levels of precedence.
Operators at higher level of precedence are evaluated first. The operators
in the same level of precedence are evaluated according to defined
associativity in that level (either left to right or right to left).
Table 2.12 shows almost all the operators in C, their precedence
level and associativity. First priority is the highest level of precedence and
15th priority is the lowest level of precedence.
Table 2.12: Operator precedence and associativity
Operator Operation Associativity Priority
() Function Call
[] Array element reference
Left to Right 1st
-> Structure Operator
. Structure Operator
+ Unary plus
– Unary minus
++ Increment
–– Decrement
! Logical NOT
Right to Left 2nd
~ 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
10 of 21
Table 2.12 Continued …
Operator Operation Associativity Priority
^ 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

2.2.8 Data Types


C supports various data types. Basically there are three classes of data
types.
- Primary Data Types
- Derived Data Types
- User-defined Data Types

2.2.8.1 Primary Data Types


A distinct piece of information is called as data. Data can be of different
categories. Basic categories of data are shown in figure 2.5. Figure also shows the
supported data types in C for each category of data.

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

Figure 2.5: Basic Categories of Data

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

2.8.2 Derived Data Types


There are derived data types such as arrays (discussed in Unit #4),
functions (discussed in Unit #5), structures (discussed in Unit #4) and pointers
(discussed in Unit #6).
12 of 21
2.8.3 Declaration of Variables
A variable is used to store value of any data type. The syntax used for
declaring a variable is shown below.
data-type var1[,var2,var3,…];
e.g.
int a,b,c;
char choice;
float interest_rate, principal_amount;

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.

2.8.4 User-defined Data Types


C supports a type-definition feature that allows user to define his/ her own
data type identifier. This user-defined identifier can then be further used for
declaring variables. This can be achieved by using following syntax.
typedef type identifier;
e.g.
typedef int my_int;
Then the variables can be declared by using the user-defined identifier (in
above example it is my_int) as,
my_int x,y,z;

2.2.9 Data Type Conversion


In some situations, programmer needs to convert data type of a variable or
a value temporarily in an expression. Process of doing so is called typecasting.
This can be achieved by using following syntax.
(new-data-type)variable/value
Example:
int a,b;
float avg;
printf(“Enter two numbers: ”);
scanf(“%d%d”,&a,&b);
avg=(float)(a+b)/2;
/* Values (a+b) and 2 are integers. In C, when both the numerator
and denominator are integers, division operation gives integer
result. To get the floating point result, either of them needs to be
made float */

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)

2.3.1.1 Formatted Output


Basic syntax of printf( ) function is given below.
int printf(const char *format [, argument, … ]);
This function converts, formats and displays its arguments on the
standard output. It returns number of characters displayed.
The format string can contain following types of objects
– Ordinary characters (they are directly sent to output as they are)
– Escape sequences (listed in table 2.2)
– Control sequence or conversion specification (they are replaced
sequentially by arguments specified after the formats).
Simple example of displaying a constant string with ordinary characters is
shown below.
Example 1:
printf(“Hello”);
printf(“Everybody”);
Output:
HelloEverybody_
14 of 21
One may use escape sequences as shown below.

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

Formatted outputs for Single Character


(assuming value of c as „P‟)
Format Output
printf(“%c”,c); P
printf(“%5c”,c); P
printf(“%–5c”,c); P

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

2.3.2 Receiving Input


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>).
16 of 21
Functions defined in a file „stdio.h‟ and which are used for receiving input
are,
getchar( ) gets( ) scanf( )
For receiving a single character from standard input, getchar( ) function
is used.
e.g.
char var1;
var1=getchar( );
putchar(var1);
Output:
D
D_
The received character can be tested using functions shown in table 2.14
which are defined in header file ctype.h. Therefore before using these functions
we should include file ctype.h in the program (#include<ctype.h>).
Table 2.14: Functions for testing characters
Function Meaning
isalnum( char) Is char an alphanumeric character?
isalpha(char ) Is char an alphabet?
isdigit(char) Is char a digit?
islower(char) Is char a lowercase letter?
isprint(char) Is char a printable character?
ispunct(char) Is char a punctuation mark?
isspace(char) Is char a white space character?
isupper(char) Is char an uppercase letter?
We can use gets( ) function for getting a string from the standard input.
e.g.
char name[15];
gets(name);
puts(name);
Output:
Karmaveer
Karmaveer_
We can use scanf( ) function for receiving formatted input. (scanf stands
for scan-formatted).

2.3.2.1 Formatted Input


Basic syntax of scanf( ) function is given below.
int scanf(const char *format [, address, … ]);
This function scans input (one character at a time), formats each
field according to corresponding format specifier passed in format string and
stores the resulting values at the given addresses (in the specified variables).

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.

Table 2.15: Some scanf( ) examples


scanf( ) statement Input by Value Remarks
user Assignment
scanf(“%d%d”,&a,&b); 30275 765 a=30275 Normal integer
b=765
scanf(“%3d%5d”,&a,&b); 765 30275 a=765 Width of first field
b=30275 set to 3 and second to
5
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.
18 of 21
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.

Table 2.16: Some scanf( ) examples for strings


scanf( ) Input by user Value Remarks
statement Assignment
scanf(“%s”,name); Ram Gil name=“Ram” As after Ram, there
is a white space, it is
considered as end of
first field and the
next input will be
considered for next
scanf( ) statement.
scanf(“%7c”,name); Ram Gil name=“Ram Exactly 7 characters
Gil” are read.
scanf(“%[a-z]”,ad); Mumbai400051 ad=“Mumbai” Only a to z
characters are
permitted.
scanf(“%[^\n]”,ad); MSBTE, 49, ad=“MSBTE, Newline character is
Kherwadi 49, Kherwadi” not permitted in the
input. All the
characters until
newline are accepted.
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.

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 */
………………
}

2.3.4 Preprocessor Directives


In C, preprocessor processes the source program before giving it to a
compiler as shown in figure 2.6.

Source Object
Preprocessor Compiler
Program in C Program

Figure 2.6: Compilation process in C


Preprocessor directives are the statements which are handled by a
preprocessor. In C, these statements start with a „#‟ symbol.
When preprocessor gets a „#include‟ statement, it incorporates the header
file in the source code. When preprocessor gets a „#define‟ statement, it replaces
all the occurrences of the symbolic name by the defined value.
Other preprocessor directives (or commands) are #undef, #if, #ifdef,
#ifndef, #else, #endif, #line and #error. But they are out of the scope of
curriculum of this subject.

Sample Questions

1. Describe generic structure of a C program. [4M]


2. Explain any four library functions under conio.h header file. [4M]
3. Give significance of <math.h> and <stdio.h> header files. [2M]
4. List any four keywords used in C with their use. [2M]
5. Describe following terms. [4M]
i) Keyword ii) Identifier iii) Variable iv) Constant
6. Develop a simple C program for addition and multiplication of two integer
numbers. [4M]
7. Define typecasting. Give one example. [2M]
8. Write a program to accept marks of four subjects as input from user.
Calculate and display total and percentage marks of student. [4M]
9. Explain following functions with suitable examples. [4M]
getchar( ) putchar( ) getch( ) putch( )
10. State use of printf( ) and scanf( ) functions with suitable examples. [4M]
11. Explain how formatted input can be obtained. Give suitable example. [4M]
12. Enlist different format specifiers with their use. [6M]
13. Explain any four bitwise operators used in C with example. [4M]
14. Explain conditional operator with example. [4M]
15. Explain increment and decrement operator. [4M]
20 of 21
16. Find output of following program. [2M]
#include<stdio.h>
void main( )
{
int x=10, y=10, v1, v2;
v1=x++;
v2=++y;
printf(“Value of v1 is %d”,v1);
printf(“Value of v2 is %d”,v2);
}
17. State relational operators with example. [2M]
18. Implement a program to demonstrate logical AND operator. [4M]

21 of 21

You might also like