C Language

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

Written as per the revised ‘G’ Scheme syllabus prescribed by the Maharashtra State Board

of Technical Education (MSBTE) w.e.f. academic year 2012-2013

Programming in ‘C’
Computer Engineering Group

First Year Diploma


Semester - II

First Edition: November 2015

Salient Features
• Concise content with complete coverage of revised G-scheme syllabus.
• Simple and Lucid language.
• Illustrative programs with detailed explanation.
• MSBTE Theory Questions and Programming questions from Summer-2011 to
Winter-2015.
• MSBTE Question Papers of Summer, Winter - 2014 and 2015.
• Three Model Question Papers for practice.
• Important Inclusions: Additional Theory Questions, Practice Programs.

Printed at: Repro Knowledgecast Ltd., Mumbai

No part of this book may be reproduced or transmitted in any form or by any means, C.D. ROM/Audio Video Cassettes or electronic, mechanical
including photocopying; recording or by any information storage and retrieval system without permission in writing from the Publisher.

TEID : 970
PREFACE
In the case of good books, the point is not how many of them you can get through, but rather how many
can get through to you.
Target’s “Programming in C” is a complete and thorough book critically analysed and extensively
drafted to boost the students’ confidence. The book is prepared as per the revised scheme [G-scheme] of
MSBTE curriculum effective from June 2012.
Every chapter is divided into sub-topics as per the requirement of the syllabus. The arrangement of
the sub-topics are such that it helps the students in easy comprehension.
Each chapter includes the following features:
Theory is provided point-wise. Explanatory diagrams have been provided wherever required.
Definitions are in italic representation.
Illustrative Programs are provided with detailed explanation and programming comments which
lead to the smooth and detailed understanding of the program.

MSBTE Theory Questions covered in separate section to give a clear idea of the type of questions
asked. (Reference of answer to each question is provided.)
MSBTE Programming Questions till latest year are included along with its answers.

Additional Theory Questions help the students gain insight on the various levels of theory-based
questions.
Programs for Practice in every chapter for students to improve their programming skills.

MSBTE Question Papers of years 2014 and 2015 are added at the end to make students familiar with the
examination.
Three Model Question Papers are provided to prepare students for examination.
The journey to create a complete book is strewn with triumphs, failures and near misses. If you think
we’ve nearly missed something or want to applaud us for our triumphs, we’d love to hear from you.
Please write to us on : mail@targetpublications.org

A book affects eternity; one can never tell where its influence stops.

Best of luck to all the aspirants!


From,
Publisher
SYLLABUS

Topic and Contents Hours Marks


Topic 1 - Basics of C
Specific objectives:
 State rules for declaration of variables, constants and operators.
 Write simple program using formatted input and formatted output.

Contents:
 History of C, where C stands 08 18
 C character set, tokens, constants, variables, keywords, identifiers
 C operators- arithmetic, logical, assignment, relational, increment and
decrement, conditional, bit wise, special, operator precedence, C
expressions data types.
 Problem solving techniques : flowchart and algorithm.
 Formatted input, formatted output instructions.
Topic 2 - Decision making
Specific objectives:
 Write a simple program using decision making, branching statement,
looping statement.
 Describe use of break and continue statement. 10 28
2.1 Decision making and branching if-statement – if, if-else, else-if ladder,
nested if else, switch case statement, break statement [14 M]
2.2 Decision making and looping - while, do, do- while statement, for loop,
continue statement [14 M]

Topic 3 - Arrays and Strings


Specific objectives:
 Give syntax of single dimensional, multidimensional array and strings.
 Write a program using array and string.
3.1 Arrays Declaration and initialization of one dimensional, two Dimensional 10 18
and character arrays, accessing array elements. [10 M]
3.2 Declaration and initialization of string variables, string handling functions
from standard library – strlen(), strcpy(), strcat(), strcmp() [8 M]
Topic 4 - Functions and Structures
Specific objectives:
 State the scope of local and global variable.
 Understand the category of function call and function type and write
program.
 Write and execute the program using command-line argument.
 Write a program using structure.
4.1 Functions: Need of functions, scope and lifetime of variables, defining 14 24
functions, function call, call by value, call by reference, return values,
storage classes.
Category of function: No argument No return value, No argument with
return value, argument with return value, recursion, command line
arguments. [16 M]
4.2 Structures: Defining structure, declaring and accessing structure members,
initialization of structure, arrays of structure. [8 M]

Topic 5 – Pointers
Specific objectives:
 State the declaration syntax of pointer, pointer initialization
 Write the program using pointer arithmetic 06 12
Understanding pointers, declaring pointer variable, initialization of pointer
variable, accessing address of a variable, pointer expressions, pointers arithmetic

TOTAL 48 100
Contents
Chapter No. Topic Page No.
1 Basics of ‘C’ 1

2 Decision Making 35

3 Arrays and Strings 78

4 Functions and Structure 106

5 Pointers 151

Model Question Papers


Model Question Paper  I 169

Model Question Paper  II 171

Model Question Paper  III 174

MSBTE Question Papers


Question Paper – Summer 2014 176

Question Paper – Winter 2014 179

Question Paper – Summer 2015 189

Question Paper – Winter 2015 184

Appendix
ASCII Values of characters 186
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

Chapter

1 Basics of 'C'
1.1 History of C
1.2 The C Character Set
1.3 Tokens In C
1.3.(a) Semicolons and Comments
1.3.(b) Identifiers
1.3.(c) C Keywords
1.3.(d) Constants
1.3.(e) Type Qualifiers
1.3.(f) Variables
1.4 Basic Structure of a C Program
1.4.(a) C Header Files and Standard Library Functions
1.5 Input and Output
1.5.(a) Input Functions
1.5.(b) Output Functions
1.6 The First C Program
1.6.(a) Steps to compile and execute a C program
1.6.(b) C Instructions
1.7 C Operators
1.7.(a) Arithmetic Operators
1.7.(b) Relational Operators
1.7.(c) Logical Operators
1.7.(d) Assignment Operators
1.7.(e) Bitwise Operators
1.7.(f) Miscellaneous Operators
1.7.(g) Operators Precedence and Associativity in C
1.8 Formatted Input and Output
1.8.(a) Formatted Input
1.8.(b) Formatted Output
1.8.(c) Format Specifications
1.9 Problem Solving Techniques
1.9.(a) Algorithms
1.9.(b) Flowcharts
1
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

1.1 History of C
What is C ?
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was
designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the
more familiar languages of that time like PL/I, ALGOL, etc.
The C language is popular because it is reliable, simple and easy to use.
Historical development of C:
Year Language Developed by Remarks
1960 ALGOL International Committee Too general, too abstract
1963 CPL Cambridge University Hard to learn, difficult implement.
1967 BCPL Martin Richards at Could deal with only specific problems.
Cambridge University
1970 B Ken Thomson at AT & T Could deal with only specific problems.
1972 C Dennis Ritchie at AT & T Lost generality of BCPL and B restored. This is
the C language which we are going to study.
Some important features of C language are given below.
a. C language has several built-in functions and operators which can be used to write any complex
program.
b. The programs written in C language are portable, i.e. they can be run on all the compilers with
least or negligible modifications.
c. The C language also supports user-defined data types and user-defined functions which can be
designed as per the requirement of the programmer. Thus C has the ability to extend itself.
d. The C language is essentially an assembly level language with features of high-level language.

1.2 The C Character Set


A character denotes any alphabet, digit or special symbol used to represent information. The
following table shows the valid alphabets, numbers and special symbols allowed in C.
Alphabets A, B, ….., Y, Z
a, b, ……, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~`!@#%^&*()_-+=|\{}[]:;" '<>,.?/
1.3 Tokens In C
A C-program consists of various tokens. A token is a keyword, an identifier, a constant, a string
literal or a symbol. For example, consider the following C statement which consists of five different
tokens:
printf("Hello, World! \n");
The individual tokens in above statement are:
printf
(
"Hello, World! \n"
)
;
2
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

1.3.(a) Semicolons and Comments:


i. Semicolons: A semicolon is used as a statement terminator in C. This means, each
individual statement must be ended with a semicolon.
E.g. printf("Hello, World! \n");
int a;
scanf("%d",&a);
ii. Comments: Comments in C program are ignored by the compiler. These statements
allow other user to better understand the code. These statements also help while
debugging a program. They start with /* and terminates with the characters */
E.g. /* my first program in C */
/* Declaration */
Comments cannot be written within comments. Also they do not occur between a string
or character literals.
1.3.(b) Identifiers:
i. Any variable, function, data definition or anything that is defined by user is referred as
an identifier.
ii. An identifier is a combination of letters (A-Z, a-z, underscores) and digits (0 to 9) but
must begin with a letter.
iii. No special characters, such as semicolon, blank space, slash or comma are allowed in C.
iv. C is a case sensitive programming language. Hence ‘Number’ and ‘number’ are treated as
two different identifiers.
v. An identifier cannot be a keyword.
vi. Some examples of acceptable identifiers are given below:
roll_number, v1, add etc.
1.3.(c) C Keywords:
i. Keywords are the words that have predefined meaning in C.
ii. The keywords cannot be used as variable names.
iii. The keywords are also called ‘Reserved words’.
iv. There are 32 keywords available in C, which are listed below:
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
These keywords are used as per the requirement in a program.
v. For example, the keywords int, char, float are used to define the data type of a variable,
function and structure.
Similarly the keywords if, else, for are used as conditional statements.
3
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

1.3.(d) Constants:
A constant is a value that doesn’t change during the execution of a program. This value
can be stored at a location in the memory of a computer.
Types of C Constants:
C constants can be divided into two major categories:
a. Primary Constants b. Secondary Constants
These constants are further categorized as shown .
C constants

Primary constants Secondary constants

Integer constant Array


Real constant Pointer
Character constant Structure
Union
Enum, etc.
We will discuss only primary constants in this chapter. The secondary constants are discussed
in detail in next chapters.
Primary Constants are of three types, viz.,
i. Integer constants
ii. Real constants (Floating point constants)
iii. Character constants
i. Integer Constants:
a. An integer constant is a sequence of digits.
b. The following rules are followed, while constructing integer constants,
i. It must have at least one digit and should not contain a decimal point.
ii. It can be either positive or negative. If no sign precedes an integer constant it
is assumed to be positive.
iii. No commas or blanks are allowed within an integer constant.
iv. The allowable range for integer constants is 32768 to 32767 for a 16-bit
compiler. For a 32-bit compiler the range is –2,147,483,648 to
2,147,483,647.
c. Some examples of integer constants are 426, +782, 8000, 7605.
ii. Real Constants:
a. Real constants are often called Floating Point constants and are essentially
numbers with decimal point.
b. The real constants can be written in two forms  Fractional form and Exponential form.
c. The following rules are followed, while constructing real constants in fractional
form,
i. A real constant must have at least one digit.
ii. It must have a decimal point.
4
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

iii. It could be either positive or negative.


iv. The default sign of a real constant is positive.
v. No commas or blanks are allowed within a real constant.
vi. Some examples of real constants in decimal form are +325.34, 426.0, 32.76,
48.5792.
d. The following rules are followed, while constructing real constants in fractional form,
i. In exponential form the real constant is expressed in two parts separated by
letter ‘e’.
ii. The part appearing before ‘e’ is called the mantissa whereas the part
following ‘e’ is called the exponent.
iii. The mantissa can be a real number expressed in decimal notation or it can be
an integer.
iv. The mantissa can have either positive or negative sign. The default sign is
positive.
v. The exponent is an integer with either positive or negative sign. The default
sign of exponent is positive.
vi. Range of real constants expressed in exponential form is 3.4e38 to 3.4e38.
vii. Some examples of real constants in exponential form are +3.2e5, 4.1e8,
0.2e+3, 3.2e5.
iii. Character Constants:
a. A character constant can be a single alphabet, a single digit or a single special
symbol enclosed within single inverted commas.
b. The maximum length of a character constant should be 1 character.
c. Each character constant has an integer value known as ASCII value. The ASCII
values of all characters are given in the table of Appendix.
d. Some examples of character constants are 'a', 'A', 'B', '6', '='.

1.3.(e) Type Qualifiers:


In C language, every data type can be further qualified using type qualifiers. Thus, qualifier is
keyword which is applied to a data type and results in a qualified data type. There are total five
categories of qualifiers. Each category has a default qualifier which is applied when name of
qualifier is not mentioned along with the data type.
The various qualifiers used in C language are mentioned in the table below:
Qualifier Default qualifier
1. auto, register, static, auto extern, typedef auto
2. signed, unsigned signed
3. short, long not short, not long*
4. const not const*
5. volatile not volatile*

1.3.(f) Variables:
A variable is an entity that may change and take different values at different times during the
execution of the program. It is a name given to a memory location where a data is stored.
5
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

The following example demonstrates the idea of a variable. Here 3 is stored in a memory
location which is named as v. Then a new value 5 is assigned to the same memory location v.
This would overwrite the earlier value 3, since a memory location can hold only one value at a
time. This is shown below.
v=3 v=5
v 3 v 5
 
Memory location of v Memory location of v
(after assigning new
value)
i. Data types of C Variables:
The data types in C, specifies what type of data can be stored in a variable. Date types are
of the following three categories:
1. Primary data types 2. User-defined data types
3. Derived data types
The different primary data types are as follows:
a. Character (char) type:
The character (char) data type can be used to define any single character. It usually
takes 1 byte (8 bits) of space. They are of two types, viz.
1. signed 2. unsigned
The default type is signed char type.
E.g.: char a = 'A';
Here the character 'A' is assigned to the char variable a.
b. Integer (int) type:
The integer (int) data type is used to define a variable accepting any integer
number.
The int data type are of following types:
1. short int 2. int 3. long int
Each of the above three int data types can be either signed or unsigned. However
the default type is signed.
E.g.: int a = 20;
Here the integer value 20 is assigned to the int variable a.
The difference between the short int and long int is given below:
Short int Long int
i. Stores smaller value of integers Stores larger value of integer than int
than int data type. data type.
ii. Range is -128 to 127 for signed Range is -2,147,483,648 to
short int and 0 to 255 for 2,147,483,647 for signed long int and 0
unsigned short int to 4,294,967,295 for unsigned long int.
iii. Requires lesser memory space Requires more memory space than int.
than int data type.
iv. Memory space required is 8 bits Memory space required is 32 bits (4
(1 byte) bytes)
v. Syntax: short int a; Syntax: long int a;

6
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

c. Floating point (float) types:


The floating point (float) data type is used while dealing with real numbers
(decimals). Depending upon the accuracy of the value required, the float data type
has the following types.
1. float 2. double 3. long double
E.g.: float a = 1.25;
Here the float or real value 1.25 is assigned to the float variable a.
The different data types, the memory space required by them and their ranges are summarized
in the following table.
Size (bits)
Data type Range
[8 bits = 1 byte]
char or signed char 8 -128 to 127
unsigned char 8 0 to 255
int or signed int 16 -32,768 to 32,767
unsigned int 16 0 to 65535
short int or signed short int 8 -128 to 127
unsigned short int 8 0 to 255
long int or signed long int 32 -2,147,483,648 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 1.1E+4932
ii. Rules for Constructing Variable Names:
a. A variable name is a combination of letters, digits or underscores.
b. A variable name should be of maximum 8 characters in length. Some compilers
allow variable names whose length can be up to 247 characters.
c. A variable name should start with a letter or an underscore.
d. No commas, blanks or special symbols are allowed within a variable name.
For example, emp_sal, m, var_1 are valid variable names, whereas emp@15, var-1 are
not valid.
e. Keywords cannot be used as variable names.
f. It is a good programming practice to give meaningful variable names.
For example, if we want roll number of student then give variable name like
roll_no instead of a.
iii. Variable Declaration:
a. All variables must be declared before using them in a program.
b. A variable declaration consists of data type, followed by variable name and ending
with semicolon.
Syntax for variable declaration: data_type variable_name;
e.g.: int a;
char ch;
float b;
7
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

iv. Variable Initialization:


a. Initial values are assigned to variables at the time of declaration.
b. Initialization consists of data type, followed by a variable name, an equal to sign
(=) and the constant of the appropriate type, ended with semicolon.
e.g.: int a = 10;
char ch = 'p';
float f = 1.23;
v. Difference between Constant and Variable:
Constant Variable
1. It is a memory location where the It is a memory location where the value
saved value does not change can be changed during the program.
throughout a program.
2. It requires a prefix ‘const’ to be added It does not require any prefix. Its
before mentioning the data_type and declaration starts directly with
the constant name, in its declaration. data_type followed by variable name.
3. Syntax: Syntax:
const data_type name value data_type name;
4. E.g.: const float pi 3.14 E.g.: int x;
1.4 Basic Structure of a C Program
i. Documentation section: This section comprises of a set of comment lines which may include
the name of the program, name of the author and other details, which the programmer can use
later.
ii. Link section: The link section consists of header files which are instructions to the compiler to
link C standard library functions from the system library. The function prototype and
definitions are mentioned in their respective header files. For example, to use the printf( )
function, the header file <stdio.h> has to be included.
iii. Definition section: The definition section defines all symbolic constants. Symbolic constants
are generally named in CAPITAL letters and their value does not change during the entire
lifetime of the program.
iv. Global declaration section: This section defines the global variables which are used in more
than one user-defined function.
User-defined functions are functions which are defined as per the requirement of the program
and are in addition to the standard library functions which are included in the Link section.
The global declaration section also declares all the user-defined functions.
v. Main( ) function section: Every C program has one main function section. This section
contains two parts; declaration part and executable part.
All the other functions (standard library functions and user-defined functions) are called or
invoked through the main( ) function.
vi. Declaration part: The declaration part declares all the variables used in the executable part.
Sometimes the variables are also initialised with a certain value along with their declaration.

8
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

vii. Executable part: This part consists of minimum one executable statement. The executable part
uses all the global variables and local variables either directly or through the standard library
functions and the user-defined functions.
Both the Declaration part and the Executable parts appear between opening and closing braces
{ } which form the body of the main( ) function. The execution of the program begins at the
opening brace and logically ends at the closing brace of the main function.
viii. Subprogram section: The subprogram section consists of all the user-defined functions that
are called in the main( ) function and may have been declared in the global declaration section.
User-defined functions are generally placed immediately after the main( ) function, although
they may appear in any order.
1.4.(a) C Header Files and Standard Library Functions:
The C library consists of several pre-defined functions grouped under different header files,
which can be accessed and used as per the requirement in a C-program. As discussed in the
previous section, the header files are included in the link section of the program. Some of the
frequently used header files and the type of functions they give access to, are mentioned below.
C Header Files Type of functions under the header file
<stdio.h> Standard input and output functions
<conio.h> Console input output functions
<math.h> Mathematics functions
<string.h> String functions
<ctype.h> Character handling functions
<stdlib.h> General utility functions
i. Functions under <stdio.h>:
The header file stdio.h refers to the standard input/ output header file. It is a standard
library in C which contains constants, macros definitions and declarations of functions. It
includes data types required for all input and output operations.
Some of the frequently used functions under <stdio.h> header file are:
printf(), scanf(), getchar(), putchar(), etc.
Note: The printf() and scanf() functions are discussed in section 1.5.
ii. Functions under <conio.h>:
Some of the frequently used functions under <conio.h> header file and their use are given
below.
clrscr(): Used for clearing the old data from the output window before beginning of
program.
getch() and getche(): Both are used for accepting a character from user. The difference
between these two functions is as follows.
getch() getche()
1. It does not display the character entered The character entered by the user is
by the user on screen, but accepts it and displayed on screen at the cursor and
saves as per the statement. also accepts and saves it as per the
statement.
9
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

2. void main() void main()


{ {
char a; char a;
printf("\nEnter character: "); printf("\nEnter character: ");
a = getch(); a = getche();
printf("\nYou entered %c", a); printf("\nYou entered %c", a);
} }
3. Output of the above program is; Output of the above program is;
Enter character: Enter character: A
You entered A You entered A
iii. Functions under <math.h>:
Some of the frequently used functions under <math.h> header file are:
sqrt(), round(), log(), log10(), etc.
iv. Functions under <string.h>:
Some of the frequently used functions under <string.h> header file are:
strcat(str1, str2), strcpy(str1, str2), strlen(strl), strcmp(str1, str2), etc.

1.5 Input and Output


C language has a collection of library functions, which includes a number of input/output functions.
These functions allow the transfer of information between the computer and the input/output devices
(e.g., a keyboard and a monitor). For accessing these input-output functions the header file <stdio.h>
is included in the link section of the program.
1.5.(a) Input Functions:
Data entered by user through keyboard is accepted in the program using the input functions. These
functions are already defined in standard C library. Some examples of input functions are scanf( ),
getchar( ), getch( ), gets( ). The most commonly used input function is the scanf( ) function.
i. scanf( ) function:
a. The scanf function reads input from the standard input stream stdin and scans that
input according to format provided.
b. This function can be used to take input which is of type number (int, long, float or
double), character, string (set of characters) or of both.
c. Syntax: scanf("control string", argument list);
The control string consists of one or more than one group of control (or
conversion) characters followed by list of arguments. The control characters
depend upon the data type of the corresponding arguments where the data is to be
stored. Each control character (d, c, f, etc.) must be preceded by a percent sign (%).
d. The common conversion characters / format specifiers are listed in the table below:
Conversion Character /
Meaning
Format Specifiers
%c This indicates data item is a character
%d This indicates data item is integer
This indicates data item is floating point value
%e
(exponential)
10
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

This indicates data item is a floating point


%f
value
%h This indicates data item is a short integer
%o This indicates data item is a octal integer
This indicates data item is an unsigned
%u
decimal integer
This indicates data item is a hexadecimal
%x
integer
e. The arguments are variables, whose data types should match with corresponding
character group in the control string.
f. Each variable name must be preceded by an ampersand (&).
g. e.g.: scanf("%d", &a)
Here, the conversion character ‘%d’ is used to accept integer data type from
the user and is then saved in the integer variable having name ‘a’.
h. For accepting values for more than one variable, we can use separate scanf( )
statement for each variable as shown below.
scanf("%d", &a);
scanf("%d", &b);
scanf("%d", &c);
Alternatively, we can combine all the conversion characters and their
corresponding variables in one scanf( ) statement, as follows.
scanf("%d %d %d", &a, &b, &c);
1.5.(b) Output Functions:
Output functions are the functions through which the output is displayed on the standard
output devices like monitor. Some examples of output functions used by C programming are
printf( ), putchar( ), puts( ). The most commonly used output function is the printf( ) function.
i. printf( ) function: To display the data on an output device like monitor, the printf( )
function is used in C. The displayed output can be of two types, viz.,
a. Output without values of program variables.
b. Output with values of program variables.
a. To Display only Output: In this case printf() is used only to display some text as
output on monitor.
Syntax: printf("control string");
The text which is enclosed inside double quotes will be displayed on monitor.
For example, if we want to display “hello, this is my beginning of C Program”,
then we have to put this message in printf function in place of control string as:
printf("hello, this is my beginning of C Program");
The output for above statement will be:
hello, this is my beginning of C Program
b. To Display values of variables:
This function can be used to display values of variables of type integer, float,
character or any combination of number, single character and string on monitor.
11
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

Syntax: printf("control string", argument list);


The control string contains a formatting information similar to scanf( ) function and
list of arguments are the names of variables.
Note: The arguments in printf function are not preceded by ampersand (&).
Consider the following example
printf ("The integer value is : %d, The floating point value is : %f ", a,b);
Here, the statement between inverted commas ("…" is the format string and the
%d and %f will respectively print the integer and floating point values of their
corresponding variables a and b.
ii. Escape sequences (Backslash character constants):
Some backslash character constants are used in output functions of C so that the output is
displayed in the desired format. These are also known as escape sequences. Some of the
frequently used escape sequences and their meanings are given in the following table:
Constant Meaning
'\a' audible alert (bell)
'\b' back space
'\f' form feed
'\n' new line
'\r' carriage return
'\t' horizontal tab
'\v' vertical tab
'\'' single quote
'\" ' double quote
'\?' question mark
'||' backslash
'\0' null
1.6. The First C Program
A basic C program can be written with different combinations of the variables, constants and
keywords studied till now. The rules to be remembered before writing a C program are mentioned
below.
i. Every instruction in a C program is written as a separate statement. A logical series of these
statements comprises of a complete C program.
ii. The statements in a C program are executed in the same order as they appear in the program.
Only if the logic of the problem demands a deliberate ‘jump’ or transfer of control to a
statement, which is out of sequence, we can do so with the help of appropriate command.
iii. Blank spaces may be inserted between two words to improve the readability of the statement.
However, no blank spaces are allowed within a variable, constant or keyword.
iv. All statements are entered in small case letters.
v. C has no specific rules for the position at which a statement is to be written. That’s why it is
called a free-form language.
vi. Every C statement ends with a semicolon.

12
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

Illustrative Program

1. Write a program to print “Hello, World!”


/* Program to print "Hello, World!" */

#include<stdio.h> /* header file must be included */


int main() /* c program always starts from this function */
{
printf("Hello, World! \n");/* output statement */
return 0;
}

Output:
Hello, World!

1.6.(a) Steps to compile and execute a C program:


i. Start the compiler at C> prompt. The compiler (TC.EXE is usually present in
C:\TC\BIN directory).
ii. Select New from the File menu.
iii. Type the program.
iv. Save the program using F2 under a proper name (say Program1.c).
v. Use Alt + F9 to compile the program. Check for errors if any and rectify and save them
using F2.
vi. Use Ctrl + F9 to compile and execute the program.
vii. Use Alt + F5 to view the output
1.6.(b) C Instructions:
C instruction is an order given to a computer processor through the C program. There are
basically three types of instructions in C:
i. Type Declaration Instruction: They are used to declare the type of variable used in C
program.
e.g.: int a, b;
ii. Arithmetic Instruction: They are used to perform arithmetic operations between
constants and variables.
e.g.: c = a + b;
iii. Control Instruction: They are used to control the sequence of execution of various
statements in a C program.
e.g.: while(i < 5)
1.7 C Operators
In C language, an operator is a symbol which instructs the compiler to perform the specified
mathematical or logical operation on the mentioned variables or constants.
13
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

C language provides the following types of operators:


a. Arithmetic Operators b. Relational Operators
c. Logical Operators d. Assignment Operators
e. Bitwise Operators f. Miscellaneous Operators
1.7.(a) Arithmetic Operators:
These operators are used for carrying out arithmetic operations like addition, subtraction,
multiplication, division, etc on variables and constants. The results of these operations are
saved in variables of suitable data types.
Based on the number of operands required, arithmetic operators in C are categorised into two
types, viz.,
i. Binary operator ii. Unary operator
i. Binary Operators:
The arithmetic operators which require two operands (i.e. variables or constants) to
operate upon are called as binary operators. Following table shows all the binary
arithmetic operators supported by C language.
Let variable x contain the value 40 and variable y contain the value 10, then we have the
following results.
Operator Operator Name Description Example
+ Addition operator Adds two operands x + y will give 50
Subtracts second operand
– Subtraction operator x – y will give 30
from the first
* Multiplication operator Multiplies two operands x * y will give 400
Divides first operand by
/ Division operator x / y will give 4
second operand
Calculates remainder of
% Modulo operator x % y will give 0
an integer division

Illustrative Programs

1. Write a program to add two numbers.


/* Program to add two numbers */
#include<stdio.h>
void main( )
{
int x = 40, y = 10, z ; /* declaration and initialization of variables */
z = x + y; /* '+' operator adds the values saved in x and y and saves in z*/
printf("Addition of two numbers is: %d\n", z ); /* prints the value of addition
saved in z */
}
Output:
Addition of two numbers is: 50
14
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

Similarly, subtraction, multiplication and division operators are used.


Note: The result of division operation must be stored in a variable of data type float.
2. Write a program to find the remainder of the division of two integers.

/* Program to find the remainder of the division of two integers */

# include<stdio.h>
void main()
{
int x = 43, y = 10, z; /* declaration and initialization of variables */
z = x % y; /* calculates remainder of the division of 43 and 10 */
printf("Modulo of the two given numbers is: %d", z);
}
Output:
Modulo of the two given numbers is: 3
ii. Unary Operators:
The arithmetic operators which require only one operand/ variable to operate upon are
called as unary arithmetic operators. The two unary arithmetic operators supported by C
language are;

Operator Operator Name Description


Increases (increments) the value of variable by
++ Increment operator
1.
Decreases (decrements) the value of variable
-- Decrement operator
by 1.

a. Increment operator:
The increment operator increases (increments) the value of the associated variable
by one. The ++ operator is the increment operator.
Increment operators can either be pre-increment operator or post-increment
operator.
i. Pre increment Operator: This operator is used to increment the value of
variable before using it in the expression. The pre-increment operator first
increments the value and then it is used in the expression.
E.g.: y = ++ x ;
Here, x is first incremented and then the new value is associated to y.
ii. Post increment Operator: This operator is used to increment the value of
variable after executing expression completely in which post increment is
used. The post increment operator first uses the variable in the expression
and then increments it.
E.g.: y = x ++ ;
Here, the value of x is first associated to y and then x is incremented.
15
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

Illustrative Program

1. Write a program to demonstrate use of pre-increment and post-increment operators.

/* Program to demonstrate use of pre-increment and post-increment operators */

#include<stdio.h>
void main()
{
int x=10,y=10,v1,v2; /* variable declaration */
clrscr();
v1 = x++; /* post-increment */
v2 = ++y; /* pre-increment */
printf("Value of v1 : %d",v1);
printf("Value of v2 : %d",v2);
}

Output:
Value of v1 : 10
Value of v2 : 11
From the above program the difference between pre-increment (++i) operator and post-
increment (i++) operator can be summarized as follows:
Pre - Increment (++i) Operator Post - Increment (i++) Operator
i. It is used as prefix before the variable. It is used as postfix after the variable.
ii. This operator increases the value of the This operator increases the value of the
variable by 1, before execution of the C variable by 1, after the execution of the C
statement containing it. statement containing it.
iii. The C statement containing the operator The C statement containing the operator
and the following statements use the cannot use the incremented value of
incremented value of the variable. variable. It is available for use from the
next logical C statement.
iv. void main() void main()
{ {
int i = 10; int i = 10;
printf("i = %d", ++i); printf("i = %d", i++);
printf("\n Later i = %d", i); printf("\n Later i = %d", i);
} }

Output: Output:
i = 11 i = 10
Later i = 11 Later i = 11
b. Decrement operator:
The decrement operator decreases (decrements) the value of the associated variable
by one. The -- operator is the decrement operator.
16
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

Decrement operators can either be pre-decrement operator or post-decrement operator.


i. Pre decrement Operator: This operator is used to decrement the value of
variable before using it in the expression. The pre-decrement operator first
decrements the value and then it is used in the expression.
E.g.: y = -- x ;
Here, x is first decremented and then the new value is associated to y.
ii. Post decrement Operator: This operator is used to decrement the value of
variable after executing expression completely in which post decrement is
used. The post decrement operator first uses the operand in the expression
and then decrements it.
E.g.: y = x -- ;
Here, the value of x is first associated to y and then x is decremented.

Illustrative Program

1. Write a program to demonstrate use of pre-decrement and post-decrement operators.


/* Program to demonstrate use of pre-decrement and post-decrement operators */

#include<stdio.h>
void main()
{
int x=10,y=10,v1,v2; /* variable declaration */
clrscr();
v1 = x--; /* post-decrement */
v2 = --y; /* pre-decrement */
printf("Value of v1 : %d",v1);
printf("Value of v2 : %d",v2);
}
Output:
Value of v1 : 10
Value of v2 : 9

1.7.(b) Relational Operators:


These operators are used to test or check the relation between two values or variables. The
results of these tests are used to execute the appropriate statement.
Following table shows all the relational operators supported by C language.
Let variable x contain the value 40 and variable y contain the value 10, then we have,
Operator Operator name Description Example
Checks whether the values of two
(x = = y) is not
== Is equal to operands are equal or not. If yes then it
true.
returns true.
Checks if the values of two operands are
!= Is not equal to equal or not. If values are not equal then it (x ! = y) is true
returns true.
17
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

2. Write an algorithm to find largest among three numbers entered by the user.
Ans: The algorithm to read three numbers from user and find the largest among them is given below:
Step-1: Start
Step-2: Declare three variables ‘a’, ‘b’ and ‘c’.
Step-3: Accept values for ‘a’, ‘b’ and ‘c’ from user.
Step-4: Check as per the following:
If a > b
Then if a > c
Display ‘a’ is the largest number.
Else (i.e. if c > a)
Display ‘c’ is the largest number.
Else (i.e. if b > a)
Then if b > c
Display ‘b’ is the largest number.
Else (i.e. if c > b)
Display ‘c’ is the largest number.
Step-5: Stop

1.9.(b) Flowcharts:
Flowcharts are used in C programming due to the following reasons:
i. Visualizing the flow of program graphically is better than describing the same in words.
ii. It helps in understanding the method of coding and improves its efficiency wherever
possible.
iii. It is an easy method of explaining the methodology of a C program through symbols and
text to other programmers.
iv. It also helps in finding errors or debugging the program.
Flowcharts are usually drawn using standard symbols. However, some special symbols can also
be developed when required.
The standard symbols are listed below:
i. Terminator:
An oval flowchart shape indicates the start or end of the
process, usually containing the word “Start” or “End”.
ii. Process:
A rectangular shape indicates a branch in the process
flow step.
For example, "c=a+b", "i=i+1"
iii. Decision:
A diamond shape indicates a branch in the process flow.
This symbol is used when a decision is to be made,
commonly a YES/NO question or True/False test.
iv. Connector:
A small, labelled, circular flowchart used to indicate a
jump in the process flow. Connectors are usually used in
complex or multi-sheet diagrams.
28
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

v. Data:
A parallelogram that indicates data input or output (I/O)
for a process.
vi. Delay:
It is used to indicate a delay or wait in the process.
vii. Arrow:
Used to indicate the flow of control in a process.

Illustrative Program

1. Draw flowchart to print sum of two numbers.


Start

Declare variables num1, num2 and sum

Read num1 and


num 2

suma+b

Display sum

Stop

Note: Apart from the above mentioned techniques, some other problem solving techniques are also
used. Few of them are mentioned below:
i. Pseudocode: It is an informal high level description of the operating principle of a
computer program or other algorithm.
ii. Solve by analogy: Analogy is just a broader application of the strategy of looking for
things that are familiar.
iii. Means ends analysis: The strategy behind means and ends analysis is to define the ends
and then to analyze your means of getting between them.
iv. Divide and conquer: The principle behind this is to break up a large problem into
smaller pieces so that we can solve individually.
v. The building block approach: It is a combination of solve by analogy and divide and
conquer. The idea behind this is to see if any solutions for smaller pieces of the problem exist.
vi. Merging solution: The idea behind this is to combine existing solutions and merge them
on a step by step basis.
29
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

9. Define variable with syntax.


MSBTE Theory Questions
[W-11] [2 M]
1. Write the ‘C’ character set available in Ans: Refer 1.3.(f) (Only definition) and
C. [S-11] [2 M] 1.3.(f)-iii.b.
Ans: Refer1.2 10. Enlist C keywords. [W-11] [2 M]
2. List four types of qualifiers. OR
[S-11] [2 M] What is keyword? List any four
Ans: Refer last page 1.3.(e) – Only table keywords used in C.
3. What is conditional operator? [S-12, W-12] [2 M]
[S-11;W-15] [2 M] OR
OR List any four keywords used in C with
Give the syntax of conditional their use. [W-13] [2 M]
statement. [S-13] [2 M] Ans: Refer 1.3.(c)-iv, v.
Ans: Refer 1.7.(f)-iv.
11. Explain arithmetic and logical operator.
4. What is the purpose of stdio.h header [W-11,15] [4 M]
file? [S-11] [2 M] Ans: Refer 1.7.(a) and 1.7.(c)
Ans: Refer 1.4.(a)-i.
12. Explain formatted input and output in
5. State relational and logical operators brief. [W-11,15] [4 M]
with its meaning. [S-11] [4 M]
OR
OR
What is meant by formatted input and
List out C logical operators
output. [S-12] [2 M]
[W-12] [4 M]
OR OR
List out relational operators and state Explain formatted input-output.
their examples. [W-12] [4 M] [S-14] [4 M]
OR OR
State the logical and relational operators List the formatted input and output
available in C-language. [S-14] [2 M] instructions. [W-14] [2 M]
OR OR
Explain any two logical operators with Explain formatted input and formatted
example. [W-14] [4 M] output with example. [S-15] [4 M]
Ans: Refer 1.7.(b) and 1.7.(c) Ans: Refer 1.8.(a) and 1.8.(b).
6. Write the rules for constructing integer 13. What is operator precedence and
constant. [S-11, W-11] [4 M] associativity? [W-11] [4 M]
Ans: Refer 1.3(d)-i
OR
7. What is an operator? Explain unary and Write about operator precedence in C.
binary operator. [S-11] [4 M] [S-12] [4 M]
Ans: Refer 1.7.(a)-i and ii. OR
8. Define token and identifier. What is operator precedence?
[W-11,15] [2 M] [W-13] [2 M]
Ans: Refer 1.3 (Only definition) and 1.3(b)-i. Ans: Refer 1.7.(g)

30
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

14. Define following terms: Token 19. What is the difference between short int
Also give examples. [W-11] [4 M] and long int data types? [W-12] [2 M]
OR Ans: Refer 1.3.(f)-i-b (Table of difference
What are C tokens? Give suitable between short int and long int)
examples. [W-13] [4 M] 20. State examples of library functions.
OR [W-12] [2 M]
Enlist types of tokens available in C and Ans: Refer 1.4.(a)
give one example for each.
[S-15] [4 M] 21. State various bit wise operators with
Ans: Refer 1.3 examples. [W-12] [4 M]
OR
15. List bitwise operator used in C. List bit wise operators and explain any
[S-12] [2 M] two. [S-15] [2 M]
Ans: Refer 1.7.(e) (Table of operators and its Ans: Refer 1.7.(e)
meaning) 22. State the operation and difference
16. What are different data types used in between getch(); and getche();
‘C’? [S-12] [4 M] [W-12] [4 M]
OR Ans: Refer1.4.(a)-ii (Table)
List out primary data types and state 23. Explain formatted output statement for
their size in bits. [W-12] [4 M] any eight format codes. [W-12] [4 M]
OR Ans: Refer 1.8.(b)-i and 1.8.(c)-iii Table.
List all basic data types. [S-13] [2 M] 24. State arithmetic and logical operators.
OR [S-13] [2 M]
State various data types along with their Ans: Refer 1.7.(a)-i and ii Table
memory sizes. [W-13] [4 M] (for arithmetic operators) and
OR Refer 1.7.(c) Table (for logical operators)
State different data types in C.
[W-14] [2 M] 25. State the rules for variable declaration.
[S-13] [2 M]
Ans: Refer 1.3.(f)-i-c (Table of Data types,
Ans: Refer 1.3.(f)-iii
Size and Range)
17. Enlist relational operators used in ‘C’ 26. Give the syntax of input and output
also write C program that makes use of statement in C. [S-13] [2 M]
relational operation. [S-12] [4 M] Ans: Refer 1.8.(a) and 1.8.(b) syntax only.
Ans: Refer 1.7.(b) and the Illustrative 27. Draw the structure of C program. Also
Program following it. give one example. [S-13] [4 M]
OR
18. What is meant by increment and Write and explain the structure of a C
decrement operator? [S-12] [4 M] program. [W-13] [4 M]
OR OR
State use of increment and decrement Describe generic structure of 'C'
operators with examples. [W-14] [4 M] program. [S-14] [2 M]
OR OR
What is meant by increment and Explain structure in C with suitable
decrement operator? Explain with example. [W-14] [4 M]
example. [W - 15] [4 M] Ans: Refer 1.4 and Illustrative Program after
Ans: Refer 1.7.(a) - ii.a and ii.b 1.6
31
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

28. Define the terms: [S-13] [4 M] 35. Enlist different format specifier with its
i. Key word use. [S-14] [4 M]
Ans: Refer 1.3(c) (Only definition) Ans: Refer 1.5(a)-i.d
ii. Variable 36. Explain pre-increment and post
Ans: Refer 1.3.(f) (Only definition) increment operator. [W-14] [2 M]
iii. Identifier Ans: Refer 1.7.(a) - ii.a and ii.b
Ans: Refer 1.3(b) (Only definition) 37. State the four operators in C.
iv. Constant [W-14] [2 M]
Ans: Refer 1.3(d) (Only definition) Ans: Refer 1.7
29. State the use of increment and decrement 38. Distinguish between variable and
operator. Give difference between i++ and constant. [W-14] [4 M]
++i. [S-13, W-13] [4 M]
Ans: Refer 1.3.(f)-v
Ans: Refer 1.7.(a) - ii.a and ii.b
Refer 1.7.(a)-ii.a (Table giving 39. List types of constants. [S-15] [2 M]
difference between Pre-increment and Ans: Refer 1.3(d)
Post-increment Operator)
40. State four rules for choosing variable
30. State four arithmetic and four logical
name. [S-15] [2 M]
operators with their uses. [W-13] [2 M]
Ans: Refer 1.3.(f)-ii
Ans: Refer 1.7.(a) i and ii and 1.7.(c) (Table)
31. With suitable example and syntax, 41. Explain increment and decrement
explain how formatted input can be operator with examples. [S-15] [4 M]
obtained. [W-13] [4 M] Ans: Refer 1.7.(a)-ii
Ans: Refer 1.8.(a)
42. State the importance of flowcharts with
32. State two features of C-language. the symbols used for drawing flowchart.
[S-14] [2 M] [S-15] [4 M]
Ans: Refer 1.1 (List of features) Ans: Refer 1.9.(b)
33. Explain post increment-decrement
operator. [S-14] [4 M] 43. List and explain bitwise operator used in
Ans: Refer 1.7.(a)-ii (a-ii) and ii (b-ii) C. [W-15] [4 M]
Ans: Refer 1.7.(e)
34. State the constants and variables with
examples. [S-14] [4 M] 44. Explain special operator in C with
Ans: Refer 1.3(d) (Examples on the last line of example. [W-15] [4 M]
each i, ii and iii) and 1.3.(f)-i (Examples
Ans: Refer 1.7.(f)-i to iv.
on the last line of each a, b, c)

MSBTE Programming Questions

1. For the following program statement, derive the output generated by printf statement.
int val = 255;
float num = 79.54123;
printf("%d, %4d, %2.3f, %5.3", val, val, num, num); [S-11] [4 M]
Ans. The output of the given program is: 255, 255, 79.541, 79.541
32
Target Publications Pvt. Ltd. Basic PhysicsChapter
(F.Y.Dip.Sem.-1) of 'C'
01: BasicsMSBTE

2. Write down the output of the following program.


#include <stdio.h>
void main()
{int X = 10, Y = 20, Z = 5, i;
i = X < Y < Z;
printf("\n%d", i);
return 0;
} [W-11] [4 M]
Ans. The output of the given program is:
1

3. Write C assignment statements to evaluate the following equation.


2m1m2
i. area =  ½bh ii. torque = .9
m1  m2
iii. side = a 2 + b2 – 2 ab cos (x)
  Velocity  
iv. Energy  mass.  acceleration  height  2 [S-12] [4 M]
 2 
Ans. The required C assignments statements are as follows:
i. area = 0.5*b*h;
ii. torque = ((2*m1*m2)/(m1+m2))*9
iii. side = a+b^2-2*a*b*cos(x);
iv. energy = mass*((acceleration*height) + (velocity/2)*2)

4. Find out the errors in the following program component and state how it can be rectified.
main()
}
int a = 5, b = 5;
printf("%d", a, b)
} [W-13] [4 M]
Ans. The errors in the given program are mentioned below.
i. main()
}
The main function starts with a closing brace bracket, which will give syntax error.
ii. printf("%d", a, b)
The printf statement is not terminated with semicolon.

The corrected program code after eliminating errors is given below:


main()
{
int a = 5, b = 5;
printf("%d %d", a, b);
}
33
Target Publications Pvt. Ltd. Prog. in C (F.Y.Dip.Sem.-2) (Comp. Engg.) MSBTE

Additional Theory Questions

1. Explain printf( ) function.


Ans. Refer 1.8.(b)

2. Explain scanf( ) function.


Ans. Refer 1.8.(a)

3. Draw and explain any 4 flowchart


symbols.
Ans. Refer 1.9.(b)- Any 4 standard symbols
out of i to vii

4. Write down steps for executing C


program.
Ans. Refer 1.6.(a)
5. Explain any two problem solving
techniques.
Ans. Refer 1.9.(a) and 1.9.(b)

Programs for Practice

1. Write a program to multiply two


numbers.
2. Write a program to print average of two
numbers.
3. Write a Program to print the square of a
number.
4. Write a program to find cube of a
number.
5. Write a program to calculate area and
perimeter of a circle.
6. Write a program to accept distance in
kilometer and convert it into meter, cm,
inch and feet.
7. Write a program to print hexadecimal,
decimal, octal format of the entered
number.

34

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy