0% found this document useful (0 votes)
61 views

Unit i Basics of c Programming 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Unit i Basics of c Programming 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit I

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.

Course Outcome addressed by Unit:


- Develop C program using input - output functions and arithmetic expressions.

Theory Learning Outcomes:


1.1. Write algorithm for given problem statement.
1.2. Identify the given building blocks of a C Program.
1.3. Use basic constructs like constants, variables, data types for developing C program.
1.4. Write C programs using printf() and scanf() functions.
1.5. Write C programs using arithmetic operators, bitwise operators

Topics and Subtopics:


1.1. Fundamentals of algorithms: Notion of algorithm. Notations used for assignment
statements and basic control structures
1.2. Introduction to ‘C’: General structure of ‘ C' program. Header file, ‘main ()’ function
1.3. Fundamental constructs of ‘C’ : Character set, tokens, keywords, Identifiers,
Constants – number constants, character constants, string constants, Variables, Data
types in ‘C’. Declaring variables, data type conversion
1.4. Basic Input and Output functions: input and output statements using printf(), scanf()
functions
1.5. Assignments and expressions: simple assignment statements, arithmetic operators,
shift operators, bitwise operators, sizeof operator

Suggested specification table:


Distribution of Theory Marks
Remember Level Understand Level Apply and Above Level Total Marks
04 02 06 12
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.0 Introduction

We have heard the words hardware and software related to computer


system or mobile phones. Hardware consists of various electronic parts and their
interfacing. In other words, it is physical part of computer system. On the
contrary, software consists of set of instructions/commands and programs.
Software makes hardware to operate properly. Software is a logical part of
computer system.

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.1 Fundamentals of Algorithms

The word „algorithm‟ is derived from phonetic pronunciation of last name


of an Arabic mathematician named Abu Jafar Mohammed ibn Musa Al-
Khowarizimi.
This is a very popular technique used to obtain a solution for given
problem. Description of steps for solving a given problem is provided in
algorithm. Stress is given on text.
Definitions
- A sequential solution to any problem written in human language is
called as algorithm.
- A process that should be followed for solving a specific problem is called
algorithm.
- A step by step problem solving procedure for solving a problem in a
finite number of steps is called algorithm.
- The algorithm is defined as the finite set of steps, which provide a
chain of actions for solving a definite nature of problem.

An algorithm is said to be accurate and truthful only when it provides the


exact required output. We may use imperative statements, conditional
statements and iterative statements while designing algorithms.

Example 1: Making a milk tea.


Algorithm MAKING_TEA
1. START
2. WASH UTENSIL
3. WASH CUP
4. FILL THE CUP WITH WATER (HALF CUP)
5. TURN-ON THE STOVE/BURNER
6. ADJUST IT TO MEDIUM FLAME
7. PLACE UTENSIL ON THE BURNER
8. POUR THE WATER FROM THE CUP IN THE UTENSIL
9. OPEN SUGAR CONTAINER
10. PUT 2 SPOONS OF SUGAR IN THE BOILING WATER
11. TAKE CARDAMOM
12. GRIND IT IN A MIXER/GRINDER
13. TAKE A PINCH OF IT AND PUT IT IN THE VESSEL ALONG
WITH BOILING WATER AND SUGAR
14. LET THE WATER BOIL FOR A WHILE(~3 MINUTES)
15. MEANWHILE:
2 of 30
a. WASH THE SIEVE/DRAINER
b. TAKE OUT MILK FROM REFRIGERATOR
c. POUR MILK INTO THE CUP (3/4 TH CUP)
16. POUR THE MILK INTO THE BOILING WATER
17. LET THE MILK AND WATER BOIL (~4 MINUTES)
18. OPEN THE CONTAINER OF TEA POWDER.
19. ADD ONE SPOON OF TEA POWDER IN THE VESSEL OF
BOILING MILK AND WATER WITH DISSOLVED SUGAR &
CARDAMOM
20. LET IT BOIL FOR FEW MORE MINUTES
21. REDUCE THE BURNER TO LOW FLAME
22. CHANGE/MAKE IT TO HIGH FLAME
23. REPEAT STEPS 21-22, 2-3 TIMES
24. TURN THE BURNER OFF
25. TAKE THE SIEVE AND THE CUP
26. POUR THE TEA THROUGH THE SIEVE INTO THE CUP
27. TEA IS READY TO SERVE.
28. END

Algorithms of some realistic problems are discussed in section 1.2.

1.1.2 Algorithmic problems

Example 1: Finding multiplication (product) of two numbers. (Imperative


constructs)
Algorithm MULTIPLICATION
1. START
2. INPUT first number into variable A
3. INPUT second number into variable B
4. COMPUTE C = A * B
5. DISPLAY C
6. END

Example 2: Finding whether number is even or odd. (Conditional


constructs)
Algorithm EVEN_ODD
1. START
2. INPUT a number into variable A
3. IF A MOD 2 = 0
DISPLAY Number is Even
ELSE
DISPLAY Number is Odd
END IF
4. END

Example 3: Displaying first n natural numbers. (Iterative constructs)


Algorithm NATURAL
1. START
2. INPUT N
3 of 30
3. I = 1
4. REPEAT steps a and b WHILE I <= N
a) DISPLAY I
b) I = I + 1
END WHILE
5. END

Example 4: Finding greatest of three numbers


Algorithm GREATEST
1. START
2. INPUT first number into variable A
3. INPUT second number into variable B
4. INPUT third number into variable C
5. IF A > B AND A > C
DISPLAY A is greatest
END IF
6. IF B > A AND B > C
DISPLAY B is greatest
END IF
7. IF C > A AND C > B
DISPLAY C is greatest
END IF
8. END

Example 5: Determining whether given number is prime or not


Algorithm PRIME
1. START
2. INPUT N
3. I = 2
4. REPEAT steps a and b WHILE I < N
a) IF N MOD I = 0
DISPLAY N is not prime
GOTO step 6
END IF
b) I = I + 1
END WHILE
5. DISPLAY N is prime
6. END

1.1.3 Flowchart

Flowchart represents the solution of a given problem graphically. Pictorial


representation of the logical steps is a flowchart. It is a diagrammatic
representation that shows flow of execution of a program.
Each step in the process is represented by a different symbol and contains
a short description of the process step. Standard symbols used for drawing
flowcharts are shown here.

4 of 30
• Start / End (Terminal symbol)

• Input / Output box

• Process box

• Decision box

• Connector

• Refers to separate flowchart

• Manual Operation

• Arrows represent direction of flow of control

• Off page connector

5 of 30
Some sample flowcharts are given here.

Example 1: Finding multiplication (product) of two numbers. (Imperative


constructs)

START

INPUT A

INPUT B

C=A*B

DISPLAY C

END

Example 2: Finding whether number is even or odd. (Conditional


constructs)

START

INPUT A

IF
Yes A MOD 2 No
=0

DISPLAY Number is Even DISPLAY Number is Odd

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

DISPLAY N is not prime DISPLAY N is prime

END

1.1.4 Basic General Concepts (Content beyond Curriculum)

As computer is an electronic machine, it understands language of 0‟s and


1‟s only (i.e. Binary machine code). This language is called as machine
language or low-level language. It is very difficult (or we can say highly
impossible task) to write a program in machine language.
Symbolic representation of machine code can be used for writing
programs. This kind of programming language is called as assembly language.
Program written in assembly language is not understandable by a computer. So,
it is needed to be translated to machine language program. Conversion of an
assembly language program into a machine language program is done by system
software called assembler. Original assembly language program is known as
source code and the generated machine language program is called as object
code. For loading the object code and starting its execution, loader (it is also a
system software) is used. There are different assembly languages for different
processors. i.e. The programs written in assembly language are machine
dependent (cannot be easily run on other machines).
9 of 30
High level languages are nearer to human languages. So, they are
easily understandable. Programs written in high level language are not machine
dependent. But these programs are also not understandable by a computer.
There are two ways to make it understandable by computer.
With some programming languages, approach of Compiler is used.
Compiler is system software which translates high level language program
(source code) into a machine language program (object code). Then loader is
responsible for loading the object code and initiating execution. C uses this
approach.
The other approach is Interpreter. Interpreter is system software which
checks a single line of high level language program, executes it by converting to
machine level instruction. The process is repeated line by line.

A program is a sequence of instructions for performing a specific task. A


person who develops program is called programmer and the process of
developing programs is called as programming.
Every programming language has its own syntax which is to be studied by
a learner. Syntax is the set of rules that defines combination of symbols that are
considered to be correctly structured fragment in that language. It can be
considered to be similar to grammar in the human languages.
Before converting a source program into object program, compiler checks
for syntax errors. If the program contains such syntax errors, those are shown
to the programmer. These are the errors in the syntax of the programming
language.
Sometimes there is another type of errors in the program. Those are called
as logical errors or bugs. These errors are not shown by compiler. When we
develop a program that works, but it does not do what was expected from it.
These errors can be removed with the help of debugging (i.e. removing bugs).

1.2 Introduction to ‘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.
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. As a result,
system software as well as business packages can be developed using C.

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.

1.3 Fundamental Constructs of ‘C’

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

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 has six types of tokens. They are shown in figure 1.2.

Keywords int do while

Constants -10 27.89

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

Operators + - * /

Special ( ) [ ]
Symbols

Figure 1.2: C Tokens


12 of 30
1.3.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 1.1. Some C
compilers may use additional keywords.
Table 1.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

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

0553 0xa2 0X5a3 0x2C 0XFF 123456789L


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
Character constants contain 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‟ „ ‟ „72‟
Each character is represented internally by an ASCII value. So the
constant „72‟ represents „H‟.

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

Figure 1.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 1.4: Values of variables x, y and z after execution of assignment


statements shown

1.3.8 Data Types in ‘C’


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

1.3.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 1.5. Figure also shows the
supported data types in C for each category of data.

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

Figure 1.5: Basic Categories of Data


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 implemented 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 return-type
of function (i.e. function‟s return-type is void when it does not return any value).
Table 1.3 shows the list of data types supported in C along with their size,
range and format specifiers.
Table 1.3: 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
Whole signed int
(hexadecimal)
Number
unsigned int 2 0 to 65535 %u
short int
2 -32768 to + 32767 %d
or

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

1.3.8.2 Derived Data Types


There are derived data types such as arrays (discussed in Unit #3),
structures (discussed in Unit #3), functions (discussed in Unit #4) and pointers
(discussed in Unit #5).

1.3.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, 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.

1.3.8.4 User-defined Data Types


C supports a type-definition feature that allows user to define his/ her own
data-type name (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 data type (in
above example it is my_int) as,
my_int x,y,z;
17 of 30
1.3.9 Data Type Conversion
In some situations, programmer needs to convert data type of a variable, a
value or an expression temporarily. Process of doing so is called typecasting.
This can be achieved by using following syntax.
(new-data-type)variable/expression/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 */

1.4 Basic Input and Output functions


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 receiving input and generating output of a C
program. Therefore before using these functions in our program we have to
include stdio.h file (#include<stdio.h>).

1.4.1 Generating Output

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)

1.4.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 1.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_
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 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

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

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

1.4.2 Receiving Input


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 1.4
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 1.4: 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];
21 of 30
gets(name);
puts(name);
Output:
Karmaveer
Karmaveer_
We can use scanf( ) function for receiving formatted input. (scanf stands
for scan-formatted).

1.4.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 value at the given address (in the specified variable).

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.

Table 1.5: 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

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.

Table 1.6: 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.

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

1.5.1 Arithmetic Operators


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

1.5.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 1.8.
Table 1.8: 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
24 of 30
An expression containing relational operator is called as relational
expression. Value of relational expression is either one (TRUE) or 0
(FALSE).

1.5.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 1.9.
Table 1.9: Logical Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Truth table for above logical operators is shown in Table 1.10.

Table 1.10: 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

1.5.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
1.11.
Table 1.11: 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;

1.5.5 Increment and Decrement Operators


These operators are used for increasing or decreasing value of a
variable by one. The increment/ decrement operators supported by C are
shown in Table 1.12.
Table 1.12: Increment and Decrement Operators
Operator Meaning
++ Post-increment or Pre-increment
–– Post-decrement or Pre-decrement

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.

1.5.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 generally a relational expression. At first, exp1 is
evaluated. If the result of exp1 is TRUE, exp2 is evaluated. Otherwise,
exp3 is evaluated.
e.g.
interest_rate = (age >= 60) ? 9.5 : 8.75;
If value of variable age is greater than or equal to 60, value 9.5 is
assigned to variable interest_rate. Otherwise, value 8.75 is assigned to
variable interest_rate.

1.5.7 Bitwise Operators


C provides bit-wise operators for manipulation of data at bit-level.
These operators operate on integers. The bitwise operators supported by C
are shown in Table 1.13
Table 1.13: Bitwise Operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right

1.5.8 Special Operators


C also provides some special operators which are shown in Table
1.14.
Table 1.14: 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.

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.

1.5.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 of 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 1.16 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 1.16: 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 Right to Left 2nd
–– Decrement
! Logical NOT

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

1.6.2 Preprocessor Directives


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

Source Object
Preprocessor Compiler
Program in C Program

Figure 1.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.

Sample Questions

1. Define algorithm. [2M]


2. Write an algorithm to determine whether given number is divisible by 5 or
not. [4M]
3. Write algorithm to determine the given number is even or odd. [4M]
4. State importance of flowchart. [4M]
5. Draw and label different symbols used in flowchart. [2M]
6. State use of following symbols used for flowchart drawing. [2M]
i) ii)
iii) iv)
7. Draw a flowchart for checking whether given number is prime or not. [4M]
8. Draw flowchart for checking whether given number is even or odd. [2M]
9. Draw flowchart for finding largest number among three numbers. [4M]
10. Draw flowchart for addition of two numbers. [2M]
11. Write algorithm and draw flowchart to print even numbers from 1 to 100.
[4M]
12. Describe generic structure of a C program. [4M]
13. Explain any four library functions under conio.h header file. [4M]
14. Give significance of <math.h> and <stdio.h> header files. [2M]
15. List any four keywords used in C with their use. [2M]
16. Describe following terms. [4M]
i) Keyword ii) Identifier iii) Variable iv) Constant
17. Develop a simple C program for addition and multiplication of two integer
numbers. [4M]
29 of 30
18. Define typecasting. Give one example. [2M]
19. Write a program to accept marks of four subjects as input from user.
Calculate and display total and percentage marks of student. [4M]
20. Explain following functions with suitable examples. [4M]
getchar( ) putchar( ) getch( ) putch( )
21. State use of printf( ) and scanf( ) functions with suitable examples. [4M]
22. Explain how formatted input can be obtained. Give suitable example. [4M]
23. Enlist different format specifiers with their use. [6M]
24. Explain any four bitwise operators used in C with example. [4M]
25. Explain conditional operator with example. [4M]
26. Explain increment and decrement operator. [4M]
27. 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);
}
28. State relational operators with example. [2M]
29. Implement a program to demonstrate logical AND operator. [4M]

30 of 30

You might also like