Chapter 1 Basics of C - WordPress.com · - Flowchart - Pseudo-code Discussion about algorithm and...
Transcript of Chapter 1 Basics of C - WordPress.com · - Flowchart - Pseudo-code Discussion about algorithm and...
1-1
Chapter 1
Basics of C
08 Hours
18Marks
(Experiments covered [from Manual] = 4 [1, 2, 3, 4])
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 otherolder languages like FORTRAN, PL/I
orPascal.C became so popular; because it is reliable, simple and easy to use.
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.
1.3 Basic General Concepts
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.
1-2
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).
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 isanother type of errors in the program. Those are called
as logical errorsor 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.4 Problem solving techniques
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
- Pseudo-code
Discussion about algorithm and flowchart is done in 1.4.1 and 1.4.2.
1.4.1 Algorithm
The word „algorithm‟ is derived from phonetic pronunciation of last name
of an Arabic mathematician named Abu Jafar Mohammed ibn Musa Al-
Khowarizimi.
1-3
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.
Example 1: Making a milk 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:
a. Wash the sieve/drainer
b. Take out milk from refrigerator
c. Pour milk into the cup (3/4th 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 22-23, 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. Stop
1-4
Example 2: Finding whether number is even or odd.
1. Start.
2. Accept a number
3. Find reminder for division of the accepted number by 2.
4. If reminder is 0, print that number is even. Otherwise print that
number is odd.
5. Stop.
1.4.2 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 given below.
• Start / Stop
• Input / Output
• Process
• Decision
• Connector
• Refers to separate flowchart
• Manual Operation
• Arrows represent direction of flow of control
• Off page connector
1-5
One sample flowchart for finding whether number is even or odd is shown
below.
1.5 Basic 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: Basic Structure of C Program
Start
Accept a
number
rem=num mod 2
Is rem=0
Display that
number is even
Display that
number is odd
Stop
Y N
1-6
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. 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. User-defined functions can
be written either before or after the main( ) function.
1.6 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.
1.7 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”
)
;
1-7
getch
(
)
;
}
C has six types of tokens. They are shown in figure 1.2.
Figure 1.2: C Tokens
1.7.1 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.7.2 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.
Tokens
Keywords int do while
Constants -10 27.89
Strings"C Programming"
"Hello"
Identifiers main sum
Operators + - * /
Special Symbols
( ) [ ]
1-8
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
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 sequencesare given in table 1.2.
Table 1.2: Escape Sequences
Escape
Sequence
Meaning Escape
Sequence
Meaning
\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
1-9
The symbolic_name is defined using the rules same as that of identifier
(discussed in 1.7.4). 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”
1.7.3 Strings
It is discussed in 1.7.2 as string constants.
1.7.4 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).
Figure 1.3: Memory locations when variables x, y and z are declared
(Values are random/ garbage)
Figure 1.4: Values of variables x, y and z after execution of assignment
statements shown
• x30778
• y273
• z8721
•After execution of x=23;23
•After execution of y=-12;-12
•After execution of z=3564;3564
1-10
1.7.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 (require three operands).
1.7.5.1 Arithmetic Operators
C provides all the basic arithmetic operators. They are shown in
Table 1.3. These operators can operate on built-in data types of C.
Table 1.3: Arithmetic Operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo Division (used with only integers)
1.7.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.4.
Table 1.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).
1.7.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.5.
1-11
Table 1.5: Logical Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Truth table for above logical operators is shown in table 1.6.
Table 1.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
1.7.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.7.
Table 1.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;
1.7.5.5 Increment and Decrement Operators
These operators are used for increasing or decreasing value of a
variable by 1.
Table 1.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.
1.7.5.6 Conditional Operators
C provides a ternary conditional operator pair as „? :‟ which can be
used in the following form.
1-12
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.
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.
1.7.5.7 Bitwise Operators
C provides bit-wise operators for manipulation of data at bit-level.
These operators operate on integers.
Table 1.9: Bitwise Operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right
1.7.5.8 Special Operators
C also provides some special operators which are shown in Table
1.10.
Table 1.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.
1.7.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.11.
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-13
Table 1.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𝑥2 − 4𝑥 + 7 7*x*x – 4*x + 7
𝑝 ÷ 𝑞 p/q 1
2𝑏. 𝑙 1/2*b*l Or b*l/2
𝑎 + 𝑏 + 𝑐
𝑑 + 𝑒 (a+b+c) / (d+e)
1.7.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 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 1.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 1.12: Operator precedence and associativity
Operator Operation Associativity Priority
( )
[ ]
->
.
Function Call
Array element reference
Structure Operator
Structure Operator
Left to Right 1st
+
–
++
– –
!
~
*
&
sizeof
(type)
Unary plus
Unary minus
Increment
Decrement
Logical NOT
Ones complement
Pointer Indirection
Address of
Size of an object
Typecast (Conversion)
Right to Left 2nd
*
/
%
Multiplication
Division
Modulus
Left to Right 3rd
+
–
Addition
Subtraction Left to Right 4th
<<
>>
Left shift
Right shift Left to Right 5th
1-14
Table 1.12 Continued …
Operator Operation Associativity Priority
<
<=
>
>=
Less than
Less than or equal to
Greater than
Greater than or equal to
Left to Right 6th
==
!=
Equality
Inequality Left to Right 7th
& 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.8Data Types
C supports various data types. Basically there are three classes of data
types.
- Primary Data Types
- Derived Data Types
- User-defined Data Types
1.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.
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.
1-15
Figure 1.5: Basic Categories of Data
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 1.13 shows the list of data types supported in C along with their
size, range and format specifiers.
Table 1.13: Data Types in C (for 16-bit compiler like TC)
Category
of Data
Data Type Size in
Bytes Range
Format
Specifier
Character
Char
or
signed char
1 -128 to +127 %c
unsigned char 1 0 to 255 %c
Whole
Number
Int
or
signed int
2 -32768 to + 32767
%d (decimal)
%o (octal)
%x or %X
(hexadecimal)
unsigned int 2 0 to 65535 %u
short int
or
signed short int
2 -32768 to + 32767 %d
unsigned short int 2 0 to 65535 %u
long int
or
signed long int
4 -2147483648 to
+2147483647 %ld
unsigned long int 4 0 to 4294967295 %lu
Fractional
or Real
Numbers
Float 4 3.4e–38 to 3.4e+38 %f or %e
double 8 1.7e–308 to 1.7e+308 %lf or %g
long double 10 3.4e–4932 to 1.1e+4932 %Lf
Whole Numbers
int, unsigned int,
short int, unsigned short int,
long int, unsigned long int
Characters
char, unsigned char
Fractional Numbers
float, double, long doublevoid
1-16
1.8.2Derived Data Types
There are derived data types such as arrays (discussed in chapter #3),
functions (discussed in chapter #4), structures (discussed in chapter #4) and
pointers (discussed in chapter #5).
1.8.3Declaration 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 containsgarbage 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.
1.8.4User-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;
1.9Generating 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( )
1-17
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)
1.9.1Formatted 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 containfollowing 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_
1-18
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.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
𝑤 ≥ 𝑝 + 7).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
1-19
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
1.10Receiving 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>).
1-20
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.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 1.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).
1.10.1Formatted 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).
1-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).
Table 1.15: Some scanf( ) examples
scanf( ) statement Input by
user
Value
Assignment
Remarks
scanf(“%d%d”,&a,&b); 30275 765 a=30275
b=765
Normal integer
scanf(“%3d%5d”,&a,&b); 765 30275 a=765
b=30275
Width of first field set to 3
and second to 5
scanf(“%3d%5d”,&a,&b); 30275 765 a=302
b=75
As first field expects 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
b=62
54 will be skipped/
suppressed due to *.
scanf(“%d,%d”,&a,&b); 87,54 a=87
b=54
It expects , character 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-1
87
x=65.38
y=2.63
z=87.0
Normal float numbers
scanf(“%f %*f %f”,&x,&y) 65.38 26.3
82.12
x=65.38
y=82.12
26.3 will be skipped/
suppressed due to *.
scanf(“%d %f %s”,&a,&x,name); 12 87.33 Ram a=12
b=87.12
name=“Ram”
Data of different types can
be read in a single scanf( )
statement.
Conversion specification (or a control sequence) consists of a % symbol,
optional number specifying maximum field width (not for float) and a conversion
1-22
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.15 and table 1.16.
Table 1.16: Some scanf( ) examples for strings
scanf( )
statement
Input by user Value
Assignment
Remarks
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 Gil” Exactly 7 characters are
read.
scanf(“%[a-z]”,ad); Mumbai400051 ad=“Mumbai” Only a to z characters are
permitted.
scanf(“%[^\n]”,ad); MSBTE, 49, Kherwadi ad=“MSBTE, 49,
Kherwadi”
Newline character is 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 no end with a white space.
1.11 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 comment.
e.g.
/* This is a program for performing …………….. */
main( )
{
int a,b,c; /* a and b is used for input and c is used for storing result */
………………
}
1-23
1.12 Preprocessor Directives
In C, preprocessor processes the source program before giving it to a
compiler as shown in figure 1.6.
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 sources 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.
Questions
1. What is operator precedence? [2M]
2. State four arithmetic and four logical operators with their uses. [2M]
3. State four relational operators with meaning. [2M]
4. State arithmetic and logical operators. [2M]
5. Give syntax of conditional operator or conditional statement or conditional
expression. [2M]
6. State condition operator with syntax and example. [2M]
7. With suitable example explain what is meant by scope of a variable. [2M]
8. List any four keywords in C with their use. [2M]
9. Explain any two bitwise operators. [2M]
10. List all basic data types. [2M]
Or
State different data types supported by „C‟ language. [2M]
11. State various data types along with their memory sizes. [4M]
12. What are C tokens? Give suitable example. [4M]
13. State the rules of variable declaration. [2M]
14. Give syntax of input and output statement of C. [2M]
15. Define the following. [2M]
a. Bitwise operator
b. Logical operator
16. State four printf format codes. [2M]
17. Write any two advantages of C language. [2M]
18. Elaborate different sections of a C program. [4M]
19. Draw the structure of C program. Also give one example. [4M]
20. Write and explain structure of a C program. [4M]
21. Describe different data types supported by C language. [4M]
Source Program in C
Preprocessor CompilerObject
Program
1-24
22. What is algorithm? Explain in short [4M]
23. Write a program to shift the entered number by three bits left and display
the result. [4M]
24. Define following terms. [4M]
a. Identifier
b. Token
c. Operator
d. Data type
25. Write a program to shift the entered number by five bits right and display
the result.[4M]
26. Write a program to mask the most significant digit of the entered number.
Use AND operator. [4M]
27. State the use of increment and decrement operator and give its precedence
and associativity. [4M]
28. Write a program to enter two numbers and find the smallest out of them.
Use conditional operator. [4M]
29. Write a program to enter a number and carry out modular division
operation by 2, 3 and 4 and display the remainders. [4M]
30. Explain special operators of C with example. [4M]
31. Explain logical and relational operators of C. [4M]
32. Explain any four arithmetic operators and four logical operators with
example. [4M]
33. Attempt the program (5) with division operation and find the quotients.
34. Write a program to enter an integer number and display its equivalent
values in octal and hexadecimal. [4M]
35. Write a program to convert hexadecimal to decimal numbers. Enter the
numbers such as 0x1c, 0x18, 0xbc, 0xcd. [4M]
36. Write a program to find the average temperature of five sunny days.
Assume the temperature in Celsius. [4M]
37. Write a program to enter two numbers. Make a comparison between them
with a conditional operator. If the first number is greater than the second
perform multiplication otherwise division operation. [4M]
38. Write a program to calculate the total cost of the vehicle by adding basic
cost with (i) excise duty (15%) (ii) sales tax (10%) (c) octroi (5%) and (d)
road tax (1%). Input the basic cost. [4M]
39. Write a program to display ASCII equivalents of following. [2M each]
a. 'A', 'B','C' and 'a','b','c'.
b. 'a'-'C', 'b'-'A' and 'c' − 'B'.
c. 'a'+'c', 'b'*'a' and 'c'+12.
40. Write a program to print whether the number entered is even or odd. Use
conditional operator. [4M]
41. Explain keywords and constants. Give any four keywords. What are types
of constants? [4M]
42. Write a program to demonstrate all possible formatting specifiers. [4M]
43. Explain global and local variable. Write „C‟ program to explain global and
local variable.[4M]
44. What is formatted I/O? Explain any two user-defined data types of C. [4M]
45. Explain formatted input and formatted output. [4M]
46. For the following program fragment, derive the output generated by printf
statement. [4M]
1-25
int a, b, c, d;
a=15; b=10;
c=++a – b;
printf(“a = %d b = %d c = %d\n”,a,b,c);
d=b++ + a;
printf(“a = %d b = %d d = %d\n”,a,b,c);
printf(“a = %d b = %d c = %d d = %d\n”,a,b,c,d);
printf(“%d\n”,(c>d)?1:0);
printf(“%d\n”,(c<d)?1:0);
47. With suitable example and syntax explain how formatted input can be
obtained.[4M]
48. How will you add comments into your program? Explain with example.
[4M]
49. State logical and relational operator with its meaning. [4M]
50. Define the terms. [4M]
a. Keyword
b. Identifier
c. Variable
d. Constant
51. State use of increment and decrement operator. Give difference between
i++ and ++i statements with example. [4M]
52. Find out errors in the following program component and state how they
can be rectified.[4M]
main( )
}
int a = 5, b = 5;
printf(“%d”,a,b)
}
53. Which of the following are invalid variable names and why? [4M]
BASICSALARY _basic basic–hra
#MEAN group. 422
population in 2006 over time mindovermatter
FLOAT hELLO queue.
team‟svictory Plot # 3 2015_DDay
54. Dfdfdf
55. What would be the output of following program?
a. main( )
{
int i = 2, j = 3, k, l ;
float a, b ;
k = i / j * j ;
l = j / i * i ;
a = i / j * j ;
b = j / i * i ;
printf( "%d %d %f %f", k, l, a, b ) ;
}
b. main( )
{
int a, b ;
a = -3 - - 3 ;
1-26
b = -3 - - ( - 3 ) ;
printf ( "a = %d b = %d", a, b ) ;
}
c. main( )
{
float a = 5, b = 2 ;
int c ;
c = a % b ;
printf ( "%d", c ) ;
}
d. main( )
{
printf ( "nn \n\n nn\n" ) ;
printf ( "nn /n/n nn/n" ) ;
}
e. main( )
{
int a, b ;
printf ( "Enter values of a and b" ) ;
scanf ( " %d %d ", &a, &b ) ;
printf ( "a = %d b = %d", a, b ) ;
}
f. main( )
{
int i=12345;
float X=356.678;
printf(“%3d%5d%8d\n”,i,i,i);
printf(“%.3f%.10f%.13f\n”,X,X,X);
}
g. main( )
{
int p, q ;
printf ( "Enter values of p and q" ) ;
scanf ( " %d %d ", p, q ) ;
printf ( "p = %d q =%d", p, q ) ;
}
56. Write C program for the following
a. Ramesh‟s basic salary is input through the keyboard. His dearness
allowance is 40% of basic salary, and house rent allowance is 20% of
basic salary. Write a program to calculate his gross salary.
b. Distance between 2 cities (in km.) is input through keyboard. Write a
program to convert & print this distance in meters, feet, inches and cm.
c. If the marks obtained by a student in five different subjects are input
through the keyboard, find out the aggregate marks and percentage
marks obtained by the student. Assume that the maximum marks that
can be obtained by a student in each subject is 100.
d. Temperature of a city in Fahrenheit degrees is input through keyboard.
Write a program to convert this temperature into Centigrade degrees.
1-27
e. The length & breadth of a rectangle and radius of a circle are input
through the keyboard. Write a program to calculate the area &
perimeter of the rectangle, and the area & circumference of the circle.
f. Two numbers are input through the keyboard into two locations C and
D. Write a program to interchange the contents of C and D.
g. If a five-digit number is input through the keyboard, write a program to
calculate the sum of its digits. (Hint: Use the modulus operator „%‟) (h)
If a five-digit number is input through the keyboard, write a program to
reverse the number.
h. If a four-digit number is input through the keyboard, write a program to
obtain the sum of the first and last digit of this number.
i. In a town, the percentage of men is 52. The percentage of total literacy is
48. If total percentage of literate men is 35 of the total population, write
a program to find the total numberof illiterate men and women if the
population of the town is 80,000.
j. A cashier has currency notes of denominations 10, 50 and 100. If the
amount to be withdrawn is input through the keyboard in hundreds, find
the total number of currency notes of each denomination the cashier will
have to give to the withdrawer.
k. If the total selling price of 15 items and the total profit earned on them is
input through keyboard, write a program to find the cost of one item.
l. If a five-digit number is input through the keyboard, write a program to
print a new number by adding one to each of its digits. For example if
the number that is input is 12391 then the output should be displayed as
23402.