Introduction to Programming Basics
Introduction to Programming Basics
PROGRAMMING ENVIRONMENT
PROGRAMMING BASIC
* EXERCISE 23
* PROGRAMMING EXERCISE 28
COMPUTER SCIENCE-10 1
Chapter – 1 Introduction to Programming
Text Editor:
A text editor is a software that allows programmers to write and edit computer programs.
All IDEs have their own specific text editors. It is the main screen of an IDE where we
can write our programs.
COMPUTER SCIENCE-10 2
Chapter – 1 Introduction to Programming
Compiler:
Computers only understand and work in machine language consisting of 0’s and 1’s.
They require the conversion of a program written in programming language to machine
language, in order to execute it. This is achieved using a compiler. A compiler is a
software that is responsible for conversion of a computer program written in some high
level programming language to machine language code.
COMPUTER SCIENCE-10 3
Chapter – 1 Introduction to Programming
SHORT QUESTIONS
Q.1 Define computer program or computer software. (K.B)
Ans: Computers need to be fed a series of instructions by humans which tell them how to
perform a particular task. These series of instructions are known as a computer program
or software.
Q.2 Who is a programmer? (K.B)
Ans: The person who knows the detail about the syntax of the programming language and can
write a program is called a programmer.
Q.3 What are programming languages? (K.B)
Ans: Computer programs are written in languages called programming languages. Some
commonly known programming languages are
Java
C
C+ +
Python.
Q.4 Name any five programming language. (K.B)
Ans:
C language
C++
C#
JAVA
Python
Q.5 Define programming Environment. (K.B)
Ans: A collection of all the necessary tools for programming makes up a programming
environment. It is essential to setup a programming environment before we start writing
programs. It works as a basic platform for us to write and execute programs.
Q.6 Define IDE. (K.B)
Ans: A software that provides a programming environment which facilitates the programmer
in writing and executing computer programs is known as an Integrated Development
Environment (IDE).
Q.7 Name some commonly available IDE of C. (K.B)
Ans:
visual studio
code:: blocks
x code
Dev C ++
Turboo C
Q.8 Define Text editor. (K.B)
Ans: A text editor is a software that allows programmers to write and edit computer programs.
All IDEs have their own specific editors.
Q.9 Define compiler. (K.B)
Ans: A compiler is a software that is responsible for conversion of a computer program written
in some programming language to machine language code.
COMPUTER SCIENCE-10 4
Chapter – 1 Introduction to Programming
8. The grammatical rules of a natural language are similar to programming language. (K.B)
(A) Algorithm (B) Pseudo Code (C) Documentation (D) Syntax
9. A language that is understandable by computer is called: (K.B)
(A) Native Language (B) National
(C) Programming Language (D) Local Language
10. The use of computer programming language includes: (K.B+U.B)
(A) Write Program
(B) Use for Communication between User and Computer
(C) Use to Control System
(D) All of Above
11. The computer programming languages are classified into categories: (K.B)
(A) Two (B) Three (C) Four (D) Five
12. Some of the variable IDEs of ‘C’ are. (K.B)
(A) Visual Studio (B) X code (C) code block (D) All
13. A set of processes and programming tools used to develop computer program is called.
(K.B+U.B)
(A) Programming Environment (B) Programming Skills
(C) Programming Tools (D) Programming Techniques
14. To create, compile and run a program in programming language we use. (K.B)
(A) IDE (B) Standard Tools (C) GUI (D) Text Editor
15. In C language IDE consist of the modules: (K.B)
(A) Two (B) Four (C) Three (D) Five
16. A simple word processor that is used to create and edit source code of a program. (K.B)
(A) Text Editor (B) Word Processor (C) Microsoft Word (D) Spread Sheet
17. A computer software that translates ‘C’ language program into machine code. (K.B)
(A) Compiler (B) Interpreter (C) Linker (D) Assembler
18. Which one of the following is not an IDE of ‘C’? (K.B)
(A) Visual studio (B) X code (C) Dev C # (D) C #
19. GUI stands for (K.B+U.B)
(A) Graphical Use Internet (B) Good Using Interface
(C) Graphical User Interface (D) Graphical Using Internet
20. IDE allows a user to interact with it using windows and button for inputs and outputs. (K.B)
(A) GUI (B) CLI (C) MDI (D) All of these
21. provides an interface to a user. (K.B)
(A) IDE (B) Text Editor (C) Compiler (D) None of these
22. IDE is a combination of. (K.B+U.B)
(A) Text Editors (B) Compiler (C) Debuggers (D) All of these
23. Some commonly used programming languages are? (K.B)
(A) C (B) C++ (C) C# (D) All of these
24. C is a ______ language. (K.B)
(A) Basic (B) High level (C) Programming (D) Both B and C
25. allows a programmer to write and edit a program. (K.B)
(A) Text editor (B) compiler (C) IDE (D) All of these
26. All IDE’s have _____ text Editors. (K.B)
(A) Same (B) unique (C) Both A & B (D) None of these
27. is the main screen of IDE. (K.B)
(A) Text Editor (B) compiler (C) Debugged (D) None of these
COMPUTER SCIENCE-10 6
Chapter – 1 Introduction to Programming
{
printf (“Hello World!”);
}
In the above program the statement printf (“Hello World!”); uses a predefined function
printf to display the statement Hello World! on computer screen. We can also create
other functions in our program and use them inside the body of main () function.
SHORT QUESTIONS
Q.1 How many parts do a C program have? (K.B)
Ans: C program has three parts
1. Link section or header section
2. Main section
3. Body of main ( ) function
Q.2 Define Link section or header section. (K.B)
Ans: While writing programs in ‘C’ language, we make extensive use of functions that are
already defined in the language. But before using the existing functions, we need to
include the files where these functions have been defined. These files are called header
files. We include these header files in our program by writing the include statements at
the top of program.
General structure of an include statement is as follows:
#include<header_file_name>
Example:
# include <stdio.h>
Q.3 Define Main section of C program. (K.B)
Ans: It consists of a main () function. Every ‘C’ program must contain a main () function and it
is the starting point of execution.
Example:
void main ( )
Q.4 What is body of Main () function? (K.B)
Ans: The body of main () is enclosed in the curly braces {}. All the statements inside the curly
braces make the body of main function.
Example:
{
printf (“Hello World!”);
}
In the above program, the statement printf (“Hello World!”); uses a predefined function
printf to display the statement Hello World! on computer screen.
Q.5 What points should be kept in mind while developing a C program? (K.B+U.B)
Ans: Following points must be kept in mind in order to write syntactically correct C language
programs.
The sequence of statements in a C language program should be according to the
sequence in which we want our program to be executed.
C language is case sensitive. It means that if a keyword is defined with all small case
letters, we cannot capitalize any letter i.e. int is different from int. Former is a
keyword, whereas latter is not.
Each statement ends with a semi-colon(;) symbol.
COMPUTER SCIENCE-10 9
Chapter – 1 Introduction to Programming
SHORT QUESTIONS
Q.1 Define comments in a ‘C’ language program. (K.B)
Ans: Comments are the statements in a program that are ignored by the compiler and do not get
executed. Usually comments are written in natural language e.g. in English language, in order to
provide description of the code. Comments are used to increase the readability of the program.
TPES OF COMMENT:
Single-line comments
Multi-line comments
Q.2 What are single line comments? (K.B)
Ans: Start with //. Anything after // On the same line, is considered to be a comment. For
example, //This is a comment.
Example:
// This is a comment.
Q.3 What are multiple comments? (K.B)
Ans: start with /* and end at */. Anything between /* and */ is considered a comment, even on
multiple lines. For example,
Example:
/*This is
a multi-line Comment*/
Q.4 How many types of comments can be used in ‘C’? (K.B+U.B)
Ans: 1- Single-line comments
2- Multi-line comments
Q.5 Differentiate between single line and multiple comments. (K.B+U.B)
Ans: The differences between single line and multiline comment are as follows:
Single Line Comment Multiline Comment
The // is used as single line comment. The /*….*/ is used for multiple line comments.
The syntax of single line comment is: The syntax of multiline comment is:
// comment /*…………………………………..*/
Example: Example:
Comments comprise on one line. Comment can span to multiple lines:
// Hello to the world /* Welcome
To the C language This is my first program*/
Q.6 Write a program that uses comments. (A.B)
Ans:
EXAMPLE CODE
/*This program displays “I am a student of class 10”
on the output screen*/
#include <stdio.h>
void main( )
{ //body of main function starts from here
printf (“I am a student of class 10”);
} //body of main function ends here
COMPUTER SCIENCE-10 12
Chapter – 1 Introduction to Programming
Q.7 (A.B)
ACTIVITY 1.5
Tick valid comments among the following:
*comment goes here*
/comment goes here/ invalid
%comment goes here%
/* comment goes
here*/ valid
/* comment goes here/
//comment goes here*/
MULTIPLE CHOICE QUESTIONS
1. Which is related to ‘C’ comments? (K.B+U.B)
(A) Single Line (B) Multiple Line (C) Statement Terminator (D) Both ‘A’ & ‘B’
2. It is good programming practice to add in C program: (K.B)
(A) Comment/s (B) Question Marks (C) Variable (D) Constant
3. Which one of the following is used to show single line comments: (K.B+U.B)
(A) // (B) || (C)\\ (D) !
4. Multi line comment in C language represented as: (K.B+U.B)
(A) // (B) */*/ (C) /**/ (D) *//*
5. _____ are statements in a program that are ignored by the compiler. (K.B)
(A) Keywords (B) Reserve words (C) Comments (D) None of these
6. Compiler ignores _____. (K.B)
(A) Reserve words (B) Comments (C) Keywords (D) None of these
7. Comments are the statement that are ______. (K.B)
(A) not executed (B) ignored (C) Both ‘A’ & ‘B’ (D) Produced
8. Usually comments are written in ______. (K.B)
(A) English Language (B) Natural Language (C) Both ‘A’ & ‘B’ (D) None of these
9. Usually _____ are written in natural language. (K.B)
(A) Keywords (B) Reserve words (C) Comments (D) None of these
10. Comments provide ______. (K.B)
(A) Precaution of code (B) Description of code
(C) Syntax of code (D) All of these
11. There are _____ types of writing comments. (K.B)
(A) 2 (B) 3 (C) 4 (D) 5
12. ______ facilitate other programmers to understand own code. (K.B)
(A) Keywords (B) Reserve words (C) Comments (D) None of these
13. Comments are not executed as ______ may occur. (K.B)
(A) Routine error (B) Syntax error (C) Comments (D) None of these
14. Single-line comments starts with ___. (K.B+U.B)
(A) // (B) */ (C) / (D) *
15. _____ comments starts with // (K.B+U.B)
(A)Multiline comment (B) Single-line (C) Both ‘A’ & ‘B’ (D) None of these
COMPUTER SCIENCE-10 13
Chapter – 1 Introduction to Programming
COMPUTER SCIENCE-10 14
Chapter – 1 Introduction to Programming
SHORT QUESTIONS
Q.1 Define character set of ‘C’ language. (K.B)
Ans: Each language has a basic set of alphabets (character set) that are combined in an
allowable manner to form words, and then these words can be used to form sentences.
Similarly in C programming language we have a character set that includes:
1) Alphabets (A, B, ……, Y, Z), (a, b …. y, z)
2) Digits (0 – 9)
3) Special symbols ( '!@#% ^ & * ( ) _ - + = \ { } [ ] : ; " ' < > , . ? /)
Q.2 Define constants of ‘C’ language. (K.B)
Ans: Constants are the values that cannot be changed by a program e.g. 5, 75.7, 1500 etc. In C
language, primarily we have three types of constants:
Types of constant:
Integer constants
Real constants
Character constants
Q.3 Define Integer constant. (K.B)
Ans: These are the values without a decimal point e.g. 7, 1256, 30100, 55555, -54, -2349 etc.
They can be positive or negative. If the value is not preceded by a sign, it is considered as
positive.
Q.4 Define real constants. (K.B)
Ans: These are the values including a decimal point e.g. 3.14, 15.3333, 75.0, -1575.76, -
7941.2345 etc. They can also be positive or negative.
Q.5 Define character constant. (K.B)
Ans: Any single small case letter, upper case letter, digit, punctuation mark, special symbol
enclosed within ' ' is considered a character constant e.g. '5', '7', 'a', 'X', '! ', '; ' etc.
Q.6 Differentiate between real constant and integer constant. (K.B + U.B)
Ans:
Real Constant Integer Constant
These are the values including a These are the values without a
decimal point decimal point
They can also be positive or negative. They can be positive or negative.
If the value is not preceded by a sign,
it is considered as positive.
Example: Example:
3.14, 15.3333, 75.0, -1575.76, - 7, 1256, 30100, 55555, -54, -2349
7941.2345
ACTIVITY 1.6 (A.B)
Identify the type of constant for each of the following values.
Solution:
12 integer constant
1.2 real constant
‘*’ character constant
-21 integer constant
32.768 real constant
COMPUTER SCIENCE-10 15
Chapter – 1 Introduction to Programming
SHORT QUESTIONS
Q.1 Write down any three rules for naming a variable in ‘C’ language. (K.B)
Ans: Each variable must have a unique name or identifier. Following rules are used to name a variable.
1. A variable name can only contain alphabets (uppercase or lowercase), digits and
underscore ( _ )sign.
2. Variable name must begin with a letter or an underscore, it cannot begin with a digit.
3. A reserved word cannot be used as a variable name.
Q.2 ACTIVITY 1.7 (A.B)
ACTIVITY 1.7
Encircle the valid variable names among the following:
Hello, 1var roll_num valid Air23Bluevalid float
Case $car name valid =color Float
MULTIPLE CHOICE QUESTION
1. A variable name can only contain. (K.B)
(A) Digits (B) Alphabets (C) Underscore (D) All of these
2. We should give appropriate name to a variable that desirable its ____. (K.B)
(A) Evolution (B) Purpose (C) Order (D) Type
1.3.5 VARIABLE DECLARATION
SHORT QUESTIONS
Q.1 Define variable declaration. (K.B)
OR
What is variable declaration?
Ans: We need to declare a variable before we can use it in the program. Declaring a variable
includes specifying its data type and giving it a valid name. Following syntax can be
followed to declare a variable.
Some examples of valid variable declarations are as follows:
unsigned int age;
float height;
int salary;
char marital_status;
MULTIPLE CHOICE QUESITONS
1. We need to declare a variable _____ it use. (K.B+U.B)
(A) After (B) Before (C) Compile (D) None of these
2. Declaring a variable includes specifying its_______. (K.B)
(A) Data Type (B) Valid Name (C) Both A & B (D) None of these
3. Multiple variable of _____ data type many also be declared in a single standard. (K.B)
(A) Different (B) Same (C) Both A & B (D) None of These
4. A variable cannot be declared unless we mention its _____. (K.B)
(A) Format (B) Data Type (C) Range (D) None of these
5. After declaring a variable, its data type _____ be changed. (K.B+U.B)
(A) Can (B) Cannot (C) Both A & B (D) None of these
COMPUTER SCIENCE-10 20
Chapter – 1 Introduction to Programming
COMPUTER SCIENCE-10 21
Chapter – 1 Introduction to Programming
Q.3 Write a program that declares variables of appropriate data types to store your
personal data. Initialize these variables with the following data: (A.B)
Initial letter of your name
Initial letter of your gender
Your age
Your marks in 8th class
Your height
Ans:
ACTIVITY 1.8
Solution
#include < stdio.h>
#include < conio.h>
void main ()
{
char name = ‘A’; // initial letter of your name
char gender = ‘M’; // initial letter of your gender
int age = 26; // your age
int marks = 500; // marks in 8th class
float height =5.8; // your height
}
COMPUTER SCIENCE-10 22
Chapter – 1 Introduction to Programming
his own variables are known as _____. (K.B+U.B) Formatted: Line spacing: single
(A) Auto Words (B) Reserved Words (C) Restricted Words (D) Predefined Words Formatted: Line spacing: single, Tab stops: 0.5", Left
5) Include statements are written in _____ section. (K.B) + 6.5", Right
(A) Header (B) Main (C) Comments (D) Print Formatted: Line spacing: single
6) _____ are added in the source code to further explain the techniques and algorithms
Formatted: Line spacing: single, Tab stops: 0.5", Left
used by the programmer. (K.B)
+ 6.5", Right
(A) Messages (B) Hints (C) Comments (D) Explanations
7) _____ are the values that do not change during the whole execution of program. (K.B) Formatted: Line spacing: single
(A) Variables (B) Constants (C) Strings (D) Comments Formatted: Line spacing: single, Tab stops: 0.5", Left
8) A float uses___ bytes of memory. (K.B) + 6.5", Right
(A) 3 (B) 4 (C) 5 (D) 6 Formatted: Line spacing: single
9) For initializing variable, we use ____ operator. (K.B) Formatted: Line spacing: single, Tab stops: 0.5", Left
(A) (B) = (C) @ (D)? + 6.5", Right
10) _____ can be thought of as a container to store constants. (K.B) Formatted: Line spacing: single
(A) Box (B) Jar (C) Variable (D) Collection
Formatted: Line spacing: single, Tab stops: 0.5", Left
ANSWER KEY + 6.5", Right
1 C 6 C Formatted: Line spacing: single
2 A 7 B Formatted: Line spacing: single, Tab stops: 0.5", Left
3 B 8 B + 6.5", Right
4 B 9 B Formatted: Line spacing: single
5 A 10 C
Formatted: Line spacing: single, Tab stops: 0.5", Left
Q.2 True of False + 6.5", Right
1) An IDE combines text editors, libraries, compilers and debuggers in a single interface. (K.B) T/F
Formatted: Line spacing: single
2) Computers require the conversion of the code written in program file to machine language
in order to execute it. (K.B+U.B) T/F Formatted: Line spacing: single
3) Column in reserved word in C programming language. (K.B) T/F Formatted: Justified, Indent: Before: 0", Hanging: 0.5",
4) *comment goes here* is a valid comment. (K.B) T/F Line spacing: single, Tab stops: 0.5", Left + 6.5", Right
5) Float can store a real number upto six digits or precision. (K.B) T/F
Q.3 Define the following. (K.B) Formatted: Line spacing: single, Tab stops: 0.5", Left
1) IDE + 6.5", Right
Ans: A software that provides a programming environment, which facilitates the programmer in writing Formatted: Line spacing: single
and executing computer programs, is known as an Integrated Development Environment (IDE).
2) Compiler
Ans: A compiler is a software that is responsible for conversion of a computer program written
in some programming language to machine language code and vice versa.
COMPUTER SCIENCE-10 23
Chapter – 1 Introduction to Programming
3) Reserved Words
Ans: Every programming language has a list of words that are predefined. Each word has its
specific meaning already known to the compiler. These words are known as reserved
words or keywords. If a programmer gives them a definition of his own, it causes a
syntax error. Table shows the list of reserved words in C programming language. There
are 32 reserved words 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
4) Main section of a program
Ans: It consists of a main () function. Every C program must contain a main () function and it
is the starting point of execution.
5) char data type
Ans: To declare character type variables in C, we use the keyword char. It takes up just 1 byte
of memory for storage. A variable of type char can store one character only.
Q.4 Briefly answer the following questions. (K.B+U.B)
1) Why do we need a programming environment?
Ans: In order to correctly perform any task, we need to have proper tools. For example, for
gardening we need gardening tools and for painting we need a collection of paints,
brushes and canvas. Similarly, we need proper tools for programming. A collection of all
the necessary tools for programming makes up a programming environment. It is
essential to setup a programming environment before we start writing programs. It works
as a basic platform for us to write and execute programs.
2) Write the steps to create a C program file in the IDE of your lab computer.
Ans: A software that provides a programming environment to facilitate programmers in
writing and executing computer programs is known as an Integrated Development
Environment (IDE). An IDE has a graphical user interface (GUI), meaning that a user can
interact with it using windows and buttons to provide input and get output. An IDE
consists of tools that help a programmer throughout the phases of writing, executing and
testing a computer program. This is achieved by combining text editors, compilers and
debuggers in a single interface. Some of the many available IDEs for C programming
language are:
1. Visual Studio
2. Xcode
3. Code::Bocks
A text editor is a software that allows programmers to write and edit computer programs. All
IDEs have their own specific text editors. It is the main screen of an IDE where we can write
our programs. Computers only understand and work in machine language consisting of 0s
and 1s. They require the conversion of a program written in programming language to
machine language, in order to execute it. This is achieved using a compiler. A compiler is a
software that is responsible for conversion of a computer program written in some high level
programming language to machine language code.
COMPUTER SCIENCE-10 24
Chapter – 1 Introduction to Programming
PROGRAMMING EXERCISE
Exercise 1
With the help of your teacher open the IDE installed on your lab computer for writing
C programs.
Write the following program in the editor and save it as “welcome.c”.
#include <stdio.h>
#include <conio.h>
void main ()
{
//A simple C language program
printf (“Welcome to C language”);
getch ( );
}
Run the program to see Welcome to C language printed on the screen as [Link]:
#include <stdio.h>
#include <conio.h>
void main()
{
/* A simple C language program*/
printf("welcome to C Language");
getch();
}
COMPUTER SCIENCE-10 28
Chapter – 1 Introduction to Programming
Exercise 2
Write a program that declares variables of appropriate data types to store the personal
data about your best friend. Initialize these variables with the following data:
Initial letter of his name
Initial letter of his gender
His age
His height
Solution:
#include <stdio.h>
#include <conio.h>
void main()
{
char name; // Declare a variable of character data type for name
name='A'; // Initialize variable by giving firs character of name
char gender; //Declare a variable of character data type for gender
gender='M'; //Initialize a variable by giving first character of gender
int age=26; // Declare and Initialize a integer data type variable for age
float height=5.8; //Declare and Initialize a float data type variable for height
getch();
}
COMPUTER SCIENCE-10 29
Chapter – 1 Introduction to Programming
ANSWER KEY
1.1 PROGRAMMING EVIRONMENT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
A D B A D A A D C D A D A A C A
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
A D C A A D D D A B A A A A A B
1.2 PROGRAMMING BASIC
1 2 3 4
A A A A
1.2.1 RESERVED WORDS
1 2 3 4
D B D C
1.2.2 STRUCTURE OF C PROGRAM
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
D D B D A B D B C C A A A D A A
17 18 19 20 21 22 23
B B A B B B B
1.2.3 COMMENTS IN C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
D A C C C B C B C B A C B D A B
1.3 CONTANTS AND VARIABLE
1.3.1 CONTANTS
1.3.2 VARIABLES
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
C D B A B C C C A A B D A C D C
17 18 19 20 21
B A D A D
1.3.3 DATA TYPES OF A VARIABLE
1 2 3 4 5 6 7 8
C D D B C C D B
1.3.4 NAME OF A VARIABLE
1 2
D B
1.3.5 VARIALE DECLARATION
1 2 3 4 5
B C B B B
1.3.6 VARIABLE INTILIZATION
1 2
B C
COMPUTER SCIENCE-10 30
Chapter – 2 User Interface
OPERATORS
* PROGRAMMING TIME 52
* SOLVED ACTIVITIES 54
* EXERCISE 57
* PROGRAMMING EXERCISES 64
2.1.1 PRINTF ()
2.1.2 FORMAT SPECIFIERS
2.1.3 SCANF ()
2.1.4 GETCH ()
2.1.5 STATEMENT TERMINATOR
2.1.6 ESCAPE SEQUENCE
LONG QUESTIONS
1. Explain printf ( ) function with some examples. (K.B+U.B+A.B)
Ans. printf is a built-in function in ‘C’ programming language to show output on screen. Its
name comes from “Print formatted” that is used to print the formatted output on screen.
All data types can be displayed with printf function.
Syntax:
printf (control string, list of arguments) The control string consists of the following:
Text
The format specifier
The escape sequence.
Text is written within double quotes. It specifies the message that is to be printed along
with the values. Format specifier specifies the format according to which a value is to be
printed. Escape sequence controls the printing on the output device. List of arguments
consists of a list of variables or arithmetic expressions, separated by commas, whose values
are to be printed. The values are printed according to the corresponding format specifier. The
first format specifier applies to the first argument, the second to the second argument and so
on. The arguments the printf ( ) function are optional. When printf ( ) function is used to
print only a message, then the arguments are omitted.
Example:
# include <stdio. h>
void main ()
{
printf (“Hello World”);
}
Output:
Hello World
In this example, printf function is used to display Hello World on computer screen.
Whatever we write inside the double quotes (“ ”) in the printf () function, gets displayed
on computer screen.
2. Explain format specifier in C language in detail. (K.B+U.B)
Ans: A format specifier is computer code that tells about the data type, field width and the
format according to which a value is to be printed or read from an input device. A list of
commonly used format specifiers is given below.
%d (decimal integer)
%i (integer)
%1d (long decimal integer)
COMPUTER SCIENCE-10 32
Chapter – 2 User Interface
COMPUTER SCIENCE-10 35
Chapter – 2 User Interface
COMPUTER SCIENCE-10 37
Chapter – 2 User Interface
#include <stdio.h>
int main( )
{
int i = -3;
int k = i % 2’
printf(“%d\n”, k);
}
(A) Compile Time Error (B) -1
(C) 1 (D) Implementation Defined
16. What will be the output of following ‘C’ code? (K.B+U.B+A.B)
#include <stdio.h>
int main( )
{
int i = 5;
i = i / 3;
printf(“%d/n”, i);
return 0;
}
(A) Compile Time Error (B) 3
(C) 1 (D) Implementation Defined
17. A symbol used in ‘C’ with scanf( ) function: (K.B+A.B)
(A) # (B)! (C) & (D) i
18. Which one of the following symbol is used as a statement terminator? (K.B)
(A) : (B) # (C) ; (D) }
19. A computer code that tells about data type field width and function is called ______.(K.B)
(A) Reserve Word (B) Format Specifier (C) Escape Sequence (D) String Field
20. Which format specifier is used for decimal integer data? (K.B+A.B)
(A) % (B) % Id (C) %d (D) %C
21. A format specifier use for integer________. (K.B+A.B)
(A) %d (B) i% (C) %f (D) %c
22. A format specifier use for long decimal integer ________. (K.B+A.B)
(A) %d (B) %i (C) %id (D) %f
23. Format specifier used for string variable ________. (K.B+A.B)
(A) %s (B) %c (C) %e (D) %g
24. A format specifier used for floating point exponential notation ________. (K.B+A.B)
(A) %e (B) %g (C) %c (D) %f
25. A format specifier is used for single character ________. (K.B+A.B)
(A) %c (B) %s (C) %e (D) %
26. The special character used in C language to control printing on output devices are called
________. (K.B+A.B)
(A) Format Specifier (B) Escape (C) String Format (D) Control String
27. Which Escape sequence is used to produce a test (bell) sound? (K.B+A.B)
(A) \a (B) \b (C) \n (D) \r
28. A escape sequence used to move cursor back word by one position. ______. (K.B+A.B)
(A) \b (B) \n (C) \r (D) \t
29. Which escape sequence is used to move cursor to the beginning? (K.B+A.B)
COMPUTER SCIENCE-10 39
Chapter – 2 User Interface
COMPUTER SCIENCE-10 43
Chapter – 2 User Interface
Ans: DIFFERENTIATION
Following are the differences between relational and logical operators:
Relational Operator Logical Operator
Relational operators are used to Logical operators are used for building
compare two values of the same types. compound conditions.
After evaluation of a relational These operator always evaluates results in
expression, the result produced is either the form of true and false.
True or False.
Relational operator include ==, !=, <, Logical operators include, AND (&&), OR
>, <= and >=. (||), and NOT (!).
Q.8 Enlist name of Relational operators. (K.B)
Ans: RELATIONAL OPERATORS
Relational Operator Description
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than equal to
<= Less than equal to
Q.9 Enlist name of logical operators. (K.B)
Ans: LOGICAL OPERATORS
There are three types of logical operators. These are described below.
Operator Definition
&& AND
|| OR
! NOT
Q.10 Draw Table for AND Operator. (K.B)
Ans: AND OPERATOR
Expression Result
FALSE && FALSE FALSE
FALSE && TRUE FALSE
TRUE && FALSE FALSE
TRUE && TRUE TRUE
Q.11 Draw Table for OR Operator. (K.B)
Ans: OR OPERATORS
Expression Result
FALSE || FALSE FALSE
FALSE || TRUE TRUE
TRUE || FALSE TRUE
TRUE || TRUE TRUE
Q.12 Draw Table for NOT Operator. (K.B)
COMPUTER SCIENCE-10 44
Chapter – 2 User Interface
COMPUTER SCIENCE-10 46
Chapter – 2 User Interface
#include <stdio.h>
int main( )
{
int y = 3;
int x = 5 % 2 * 3 / 2;
printf(:Value of x is %d:, x);
}
(A) Value of x is 1 (B) Value of x is 2
(C) Value of x is 3 (D) Compile Time Error
16. The precedence of arithmetic operators is (from Highest to Lowest): (K.B+U.B+A.B)
(A) %, *, /, +, - (B) %, +, /, *, - (C) +, -, %, *, / (D) %, +, -, *, /
17. Which one of the following is not an arithmetic operation? (K.B+U.B+A.B)
(A) a*=10; (B) a/=10; (C) a != 10; (D) a%=10;
18. Which one of the following data type will throw an error on modulus operation (%)?(K.B+U.B+A.B)
(A) Char (B) Short (C) int (D) float
19. Which one of the following are the fundamental arithmetic operators?(K.B+U.B+A.B)
(A) +, - (B) +,-,% (C) +,-,*,/ (D) +,-,*,/,%
20. What will be the output of following ‘C’ code? (K.B+U.B+A.B)
#include <stdio.h>
int main( )
{
int a = 10;
double b = 5.6;
int c;
c = a + b;
printf(“%d”, c);
}
(A) 15 (B) 16 (C) 15.6 (D) 10
21. What will be the output of following ‘C’ code? (K.B+U.B+A.B)
#include <stdio.h>
int main( )
{
int a = 10, b = 5 , c = 5;
int d;
d = a == (b+c);
printf(“%d”, d);
(A) 1 (B) 5 (C) 5 (D) 25
22. What will be the output of following ‘C’ code? (K.B+U.B+A.B)
#include <stdio.h>
void main( )
{
int x = 1, y= 0,, z=5;
int a = x && y | | z++;
printf(“%d”, z);
}
(A) 6 (B) 5 (C) 0 (D) Varies
23. What will be the output of following ‘C’ code? (K.B+U.B+A.B)
COMPUTER SCIENCE-10 47
Chapter – 2 User Interface
#include <stdio.h>
void main( )
{
int x = 1, z= 3;
int y = x << 3;
printf(“%d\n”, y);
}
(A) -2147483648 (B) -1 (C) 1 (D) Runtime Error
24. Result of a logical or relational expression in C language is: (K.B+U.B+A.B)
(A) True or False
(B) 0 or 1
(C) 0 If Expression is False and any Positive Number if Expression is True
(D) Both a & b
25. What will be the value of d in the following C program? (K.B+U.B+A.B)
#include <stdio.h>
int main( )
{
int a = 10, b = 5 , c = 5;
int d
d = b + c == a;
printf(“%d”, d);
}
(A) 1 (B) 10 (C) 10 (D) 25
26. Which among the following is NOT a logical or relational operator? (K.B+U.B+A.B)
(A)! = (B) == (C) || (D) =
27. Relational operators cannot be used on: (K.B+U.B+A.B)
(A) Structure (B) Long (C) String (D) float
28. What will be the output of following C code? (K.B+U.B+A.B)
#include <stdio.h>
int main( )
{
int x = 2, y = 0;
int z = (y++) ? 2 : y == 1 && x ;
printf(“%d\n”, z);
return 0;
}
(A) 0 (B) 1 (C) 2 (D) Undefined Behavior
29. What will be the output of following C code? (K.B+U.B+A.B)
#include <stdio.h>
int main( )
{
int y = 2;
int z = y +(y = 10);
printf(“%d\n”, z);
}
(A) 12 (B) 20 (C) 4 (D) Either 12 or 20
30. What will be the output of following C code? (K.B+U.B+A.B)
COMPUTER SCIENCE-10 48
Chapter – 2 User Interface
#include <stdio.h>
void main( )
{
int b = 5 & 4 & 6;
printf(“%d”, b);
}
(A) 3 (B) 4 (C) 5 (D) 6
31. What will be the output of following C code? (K.B+U.B+A.B)
#include <stdio.h>
void main( )
{
int b = 5 & 4 | 6;
printf(“%d”, b);
}
(A) 0 (B) 4 (C) 1 (D) 6
32. What will be the output of following C code? (K.B+U.B+A.B)
#include <stdio.h>
void main( )
{
int b = 5 + 7 * 4- 9 * (3, 2);
printf(“%d”, b);
}
(A) 6 (B) 13 (C) 15 (D) 21
33. What will be the output of following C code? (K.B+U.B+A.B)
#include <stdio.h>
void main( )
{
int h = 8;
int b = 4 * 6 + 3 * 4 < 3 ? 4 : 3;
printf(“%d\n”, b);
}
(A) 3 (B) 33 (C) 34 (D) 11
34. What will be the output of following C code? (K.B+U.B+A.B)
#include <stdio.h>
void main( )
{
int a = 2 + 3 - 4 + 8 – 5 % 4;
printf(“%d\n”, a);
}
(A) 0 (B) 8 (C) 9 (D) 11
35. What will be the output of following C code? (K.B+U.B+A.B)
COMPUTER SCIENCE-10 49
Chapter – 2 User Interface
#include <stdio.h>
void main( )
{
chr a = ‘0’;
chr b = ‘m’;
int c = a && b | | ‘1’;
printf(“%d\n”, c);
}
(A) 0 (B) 1 (C) a (D) m
36. What will be the output of following C code? (K.B+U.B+A.B)
#include <stdio.h>
void main( )
{
chr a = ‘A’;
chr b = ‘B’;
int c = a + b % 3 - * 2;
printf(“%d\n”, c);
}
(A) 58 (B) 59 (C) 64 (D) 65
37. The variable on which the operations performed are called _______. (K.B+U.B)
(A) Product (B) Expression (C) Operands (D) Operators
38. _____ operators gives the remainder. (K.B+U.B)
(A) Division (B) Modulus (C) Integral (D) None of these
39. If both operands are type the remainder is ______ to give answer in integer. (K.B+U.B)
(A) Repeated (B) Truncated (C) Both A & B (D) None of these
40. The symbol for Modulus operator in C is ________. (K.B+U.B)
(A) * (B) % (C) ! (D) Wood
41. The symbol for multiplication in C is _______. (K.B+U.B)
(A) X (B) x (C) * (D) None of these
42. Relational operators are used to perform operations on _________. (K.B+U.B)
(A) Numeric (B) Characters (C) Strings (D) Both A & B
43. _______ can also be used to show result of relational expression. (K.B+U.B)
(A) printf( ) (B) scanf ( ) (C) Both A & B (D) None of these
44. The symbol used for ‘Equal To’ operators is ______. (K.B+U.B+A.B)
(A) = (B) == (C) Both A & B (D) None of these
45. The symbol used for ‘Not Equal To’ operator is _______. (K.B+U.B+A.B)
(A)!= (B) \= (C) ≠ (D) None of these
46. In AND operator’s expression FALSE & FALSE results. (K.B+U.B+A.B)
(A) True (B) False (C) Can be both (D) None of these
47. FALS || FALSE always return ____ in OR operator. (K.B+U.B)
(A) False (B) True
(C) can be true or false (D) None
48. ____ is also known as invertor. (K.B)
(A) AND (B) NOT (C) OR (D) None of these
49. The operator which is applied on single operands called ______. (K.B)
(A) Unity Operator (B) Unary operator (C) Binary (D) None of these
50. ____ operator require three operands. (K.B)
COMPUTER SCIENCE-10 50
Chapter – 2 User Interface
ACTIVITY 2.1
Write down the output of following code:
#include <stdio.h>
void main ()
{
printf ("I am UPPERCASE and this is lowercase");
}
Output: I am UPPERCASE and this is lowercase
ACTIVITY 2.2
Write a program that shows your first name in Uppercase and you last name in lower case
letters on screen
Solution:
#include <stdio.h>
void main()
{
printf("IMRAN khan");
}
Output: IMRAN khan
ACTIVITY 2.3
Write a program that takes roll number, percentage of marks and grade form user as input.
Program should display the formatted output like following:
Roll No : input value
Percentage : input value%
Grade : input value
ACTIVITY 2.4
Write a program that takes as input the length of one side of a square and calculates the area of
square.
Solution:
# include <stdio.h>
void main ()
{
int Area, Side;
printf ("enter the length of one side = ");
scanf ("%d”, & Side);
Area = Side * Side; // calculate area of square
printf ("Area of square = %d" , Area);
}
ACTIVITY 2. 5
COMPUTER SCIENCE-10 54
Chapter – 2 User Interface
Write a program that takes as input the number of balls in jar A and the number of balls in jar
B. The program calculates and displays the total number of balls.
Solution:
# include <stdio.h>
void main ()
{
int jar_A, jar_B, Sum;
printf ("Enter number of balls in Jar A = ");
scanf ("%d", & jar_A);
printf ("Enter number of ball in Jar B = ");
scanf ("%d", & jar_B);
Sum = jar_A + jar_B;// calculate sum Write print (“sum of jar A and jar B= %d”,sum);
printf("Sum of jar A and jar B = %d" , Sum);
}
ACTIVITY 2.6
Write a program should display the original price of shirt, discount on price and price after
discount.
Solution:
# include <stdio.h>
void main ()
{
int original_prince, price, discount_pre; float discounted_price;
printf ("Enter the original price of shirt ");
scanf ("%d", &original_prince);
printf ("enter the discount percentage ");
scanf ("%d", &discount_pre);
discounted_price = original_prince * discount_pre /100;
printf ("original price of shirt = %d discount on price %d and price after discount = %d",
original_prince, discount_pre, discounted_price);
}
ACTIVITY 2.7
Write a program that takes 2 digit number from user, computers the product of both digits and
show the output.
Solution:
# include <stdio.h>
void main ()
{
int num, rem, prod =1;
printf ("Enter a number " );
scanf ("%d" , &num);
while (num!=0)
{
rem = num % 10; // get the right most digit
prod = prod * rem; // calculate product of digits
num = num /10; // remove the right most digit
}
printf ("%d", prod);
}
COMPUTER SCIENCE-10 55
Chapter – 2 User Interface
ACTIVITY 2.8
Write a program that takes second as input and calculates equivalent number of hours, minutes
and seconds.
Solution:
#include <stdio.h>
void main()
{
int sec, hour, min, S;
printf ("input seconds:");
scanf ("%d", & sec);
hour = sec/3600;
min = (sec-/3600 * hour)160;
s= (sec - (3600*hour) - (min *60))
printf ("hour: min:s-;%d: %d:%d\n", hour, min, s);
}
ACTIVITY 2.9
Convert the following algebraic expressions into C expressions.
x 6y z x 6* y z
x yz 3 3 y x y * z * z * 3* y
y2
z x z x y * y / 3* x
3x
z x 2 3 y x * x 2* x * 2 2* 2 3* y
2
3z
x 3* z / 2 z * z * z x / z
x
y x z3
2 x
ACTIVITY 2.10
Consider the variable x = 3, y =7. Find out the Boolean result of following expression.
(2 + 5) > y (x + 4) == y
x! = (y - 4) (y / 2) > = x
-1 < x (x * 3) < = 20
ACTIVITY 2.11
Assume the following variable values x 4, y = 7 z = 8. Find out the resultant expression.
x = = 2 || y = = 8 7 > = y && z < 5
z > = 5 || x < = -3 y = = y && !(true)
x! = y || y < 5 !(z > x)
ACTIVITY 2.12
Find out the results of the following expression:
Expression Result
16 / (5 + 3) 2
7 + 3 * (12 + 12) 79
25 %3 * 4 4
34 – 9 * 2 / (3 * 3) 32
18 / (15 – 3 * 2) 2
COMPUTER SCIENCE-10 56
Chapter – 2 User Interface
EXERCISE
Q1. Multiple Choice Questions.
1) ‘printf’ is used to print __________ type of data. (U.B+A.B)
A) int B) float C) char D) All of these
2) ‘scanf’ is a __________ in C programming language. (U.B+A.B)
A) Keyword B) Library C) Function D) None of these
3) getch() is used to take __________as input from user. (U.B+A.B)
A) int B) float C) char D) All of these
4) Let the following part of code, what will be the value of variable ‘a’ after execution:
int a = 4; (U.B+A.B)
float b = 2.2;
a = a * b;
A) 8.8 B) 8 C) 8.0 D) 8.2
5) Which one of the following is a valid line of code. (U.B+A.B)
A) int = 20; B) grade = ‘A’;
C) line = this is a line; D) none of these
6) Which operator has highest precedence among the following: (K.B+U.B)
A) / B) = C) > D) !
7) Which one of the following is not a type of operator: (K.B+U.B)
A) Arithmetic operator B) Relational operator
C) Check operator D) Logical operator
8) The operator % is used to calculate __________. (K.B+U.B)
A) Percentage B) Remainder C) Factorial D) Square
9) Which one of the following is a valid character: (K.B+U.B)
A) here B) “a” C) ‘9’ D) None of these
10) What is true about C language: (K.B+U.B)
A) C is not a case sensitive language
B) Keywords can be used as variable names
C) All logical operators are binary operators
D) None of them
ANSWER KEY
1 2 3 4 5 6 7 8 9 10
D C C B B D B B C D
Q2. True or False
1) Maximum value that can be stored by an integer is 32000. (K.B) T/F
2) Format specifiers begin with a ‘%’ sign. (K.B) T/F
3) Precedence of division operator is greater than multiplication operator. (K.B) T/F
4) getch is used to take all types of data input from user. (K.B+A.B) T/F
5) scanf is used for output operations. (K.B+A.B) T/F
Q3. Define the following. (K.B)
1) Statement Terminator
Ans: STATEMENT TERMINATOR
A statement terminator is an identifier for compiler which identifies end of a line. In C
language semicolon (;) is used as statement terminator. If we do not end each statement
with a statement terminator it result into error. Error: Missing statement
COMPUTER SCIENCE-10 57
Chapter – 2 User Interface
2) Format Specifier
Ans: FORMAT SPECIFIER
A format specifier is computer code that tells about the data type, field width and the
format according to which a value is to be printed or read from an input device
A list of commonly used format specifiers is given below:
%d decimal integer
%i integer
%ld long decimal integer
%f floating-point (decimal notation)
%g floating-point (exponential notation)
%e floating-point (%f of %g, whichever is shorter)
%c single character
%s string
3) Escape Sequence
Ans: ESCAPE SEQUENCE
The special characters used in C language to control printing on the output device are
called escape sequences. Escape sequences are used in print function inside the “and.”
they force printf() to change its normal behavior of showing output. These characters are
not printed. These are used inside the control string.
4) scanf()
Ans: SCANF () FUNCTION
scanf ()is a built-in function in C language that takes input from user into the variables.
We specify the expected input data type in scanf function with the help of format
specifier. If user enters integer data type, format specifier mentioned in scanf must be %d
or %i.
Syntax:
scanf (“control string”, list of variables);
5) Modulus Operator
Ans: MODULUS OPERATOR
Modulus operator (%) performs division of left operand by the right operand and returns
the remainder value after division. Modulus operator works on integer data types.
int REM = 14 % 3;
As, when we divide 14 by 3, we get a remainder of 2, so the value stored in variable REM is 2.
Q4. Briefly answer the following questions. (U.B)
1) What is the difference between scanf and getch?
Ans:
scanf( ) function getch( ) FUNCTIONS
scanf is a built-in function in C language that getch() function is used to read a character
takes input from user into the variables. We from user. The character entered by user does
specify the expected input data type in scanf not at displayed on screen. This function is
function with the help of format specifier. If generally used to hold the execution of
user enters integer data type, format specifier program because the program does not
mentioned in scanf must be %d or %i. continue further until the user types a key.
Syntax: Syntax:
scanf(“control string”, list of variables getch();
seperrated with commas);
COMPUTER SCIENCE-10 58
Chapter – 2 User Interface
Operator Precedence
() 1
! 2
*,/,% 3
+,- 4
>,<,>= ,<= 5
==,!= 6
&& 7
|| 8
= 9
Q5. Write down output of the following code segments.
Code Output
a. # include<stdio.h>
void main ()
{
int x = 2, y = 3, z = 6;
int ans1, ans2, ans3;
ans1= x / z * y; 079
ans2 = y + z / y * 2;
ans3 = z / x +x * y;
printf(“%d %d %d”, ans1, ans2, ans3);
}
COMPUTER SCIENCE-10 61
Chapter – 2 User Interface
b. # include<stdio.h> nn
void main ()
{ nnn
printf (“nn \n\n nnn \nn\nt\t”); n
printf (“nn /n/n nn/n/n”); t
} nn/n/n nn/n
c. # include<stdio.h>
void main ()
{
int a = 4, b;
9
float c = 2.3;
b=c*a;
printf(“%d”,b);
}
d. # include<stdio.h>
void main ()
{
5
int a = 4 * 3 / (5+1) + 7 % 4;
printf(“%d”,a);
}
e. # include<stdio.h>
void main ()
1
{
printf(“%d”,(( (5 > 3 ) && (4 > 6) ) | | (7 > 3)) );
}
Q6. Identify errors in the following code segments.
Code Identified Error/s Correct Syntax
a. # include<stdio.h> Trace error in line #3 (body printf(“Value of b is :
void main () of function) “closing” %d” , b);
{ inverted commas missing
int a , b = 13;
b = a% 2;
printf(“Value of b is :
%d , b);
}
b. # include<stdio.h> Trace error in closing brace Use curly braces }
void main () of body of function instead of that ]
{
int a , b , c,
printf(“Enter First
Number: ” );
scanf(“%d”, &a);
printf(“Enter Second
Number: ” );
scanf(“%d”, &b);
a + b = c;
]
COMPUTER SCIENCE-10 62
Chapter – 2 User Interface
COMPUTER SCIENCE-10 63
Chapter – 2 User Interface
COMPUTER SCIENCE-10 64
Chapter – 2 User Interface
Exercise 3
Write a program that displays the following output using single printf statement:
* * * *
1 2 3 4
Solution:
# include <stdio.h>
void main ( )
{
printf("*\t*\t*\t*\n1\t2\t3\t4");
}
Exercise 4
Write a program that displays the following output using single printf statement:
I am a Boy
I live in Pakistan
I am a proud Pakistani
Solution:
# include <stdio.h>
void main ( )
{
printf ("I am a boy\nI live in Pakistan\nI am a proud Pakistani");
}
Exercise 5
A clothing brand offer 15% discount on each item. A lady buys 5 shirts from this brand.
Write a program that calculate total price after discount and amount of discount availed by
the lady. Original prices of the shirts are:
Shirt1 = 423
Shirt2 = 320
Shirt3 = 270
Shirt4 = 680
Shirt5 = 520
Note: Use 5 variables to store the prices of shirts.
Solution:
# include <stdio.h>
void main( )
{
int shirt1=423, shirt2=320, shirt3=270, shirt4=680, shirt5=520;
float Total_Price, Total_Discount, Final_Price;
printf("First Shirt price= %d \t\tDiscount is %.2f \tPayable price= %.2f\n",shirt1, (shirt1*0.15),
(shirt1-(shirt1*0.15)));
printf("Second Shirt price= %d \tDiscount is %.2f \tPayable price= %.2f\n",shirt2,
(shirt2*0.15), (shirt2-(shirt2*0.15)));
printf("Third Shirt price= %d \t\tDiscount is %.2f \tPayable price= %.2f\n",shirt3,
COMPUTER SCIENCE-10 65
Chapter – 2 User Interface
(shirt3*0.15), (shirt3-(shirt3*0.15)));
printf("Fourth Shirt price= %d \tDiscount is %.2f \tPayable price= %.2f\n",shirt4,
(shirt4*0.15), (shirt4-(shirt4*0.15)));
printf("Fifth Shirt price= %d \t\tDiscount is %.2f \tPayable price= %.2f\n",shirt5,
(shirt5*0.15), (shirt5-(shirt5*0.15)));
printf("\n\n----------------------------------------------------------------------------------------------------
---------\n");
Total_Price= shirt1 + shirt2 + shirt3 + shirt4 + shirt5;
Total_Discount=(shirt1*0.15)+(shirt2*0.15)+(shirt3*0.15)+(shirt4*0.15)+(shirt5*0.15);
Final_Price = (shirt1-(shirt1*0.15))+(shirt2-(shirt2*0.15))+(shirt3-(shirt3*0.15))+(shirt4-
(shirt4*0.15))+(shirt5-(shirt5*0.15));
printf("Total price: %.2f \tTotal Discount is %.2f \tFinal price: %.2f\n",Total_Price,
Total_Discount, Final_Price);
}
Exercise 6
Write a program that swaps the values of two integer variables without help of any third variable.
Solution:
# include <stdio.h>
void main( )
{
int a, b;
printf("Enter a\n");
scanf("%d", &a);
printf("Enter b\n");
scanf("%d", &b);
a = a - b;
b = a + b;
a = b - a;
printf("After swapping, a = %.2d\n", a);
printf("After swapping, b = %.2d", b);
}
Exercise 7
Write a program that takes a 5-digit number as input, calculates and displays the sum of
first and last digit of number.
Solution:
# include <stdio.h>
void main( )
{
int number;
printf("Enter a number with length 5 digits=\n");
scanf("%d",& number);
printf("The sum of first and 5th digit is=%d", (number/10000)+(number%10));
}
COMPUTER SCIENCE-10 66
Chapter – 2 User Interface
Exercise 8
Write a program that takes monthly income and monthly expenses of the user like
electricity bill, gas bill, food expense. Program should calculate the following:
Total monthly expenses
Total yearly expenses
Monthly savings
Yearly saving
Average saving per month
Average expense per month
Solution:
# include <stdio.h>
void main()
{
float monthly_income, electricity_bill, gas_bill, food_expense, monthly_Expenses,
monthly_savings;
printf("Please enter your Monthly Income=");
scanf("%f",&monthly_income);
printf("Please enter you Monthly Expenses=");
printf("\n\n\tYour Electricity Bill=");
scanf("%f",&electricity_bill);
printf("\tYour Gas Bill=");
scanf("%f",&gas_bill);
printf("\tYour Food Expense=");
scanf("%f",&food_expense);
monthly_Expenses=electricity_bill+gas_bill+food_expense;
printf("\n\n\tTotal Monthly Expenses are=%f", monthly_Expenses);
printf("\n\tTotal Yearly Expenses are=%f", (monthly_Expenses)*12);
monthly_savings =monthly_income-monthly_Expenses;
printf("\n\n\tYour Monthly savings is=%f", monthly_savings);
printf("\n\tYour Monthly savings is=%f", monthly_savings*12);
printf("\n\n\tAverage saving per month=%f", monthly_savings);
printf("\n\tAverage expense per month=%f", monthly_Expenses);
}
Exercise 9
Write a program that takes a character and number of steps as input from user. Program
should then jump number of steps from the character.
Sample output:
Enter character: a
Enter steps: 2
New character: c
COMPUTER SCIENCE-10 67
Chapter – 2 User Interface
Solution:
# include <stdio.h>
void main( )
{
char c;
int steps,x;
printf("Enter character=");
scanf("%c",&c);
printf("Enter Steps=");
scanf("%d",&steps);
x = c + steps;
printf("New Character: %c",x);
}
Exercise 10
Write a program that takes radius of a circle as input. The program should calculate and
display the area of circle.
Solution:
# include <stdio.h>
void main( )
float r, Area;
scanf(“%f”,&r);
Area = 3.14*r*r;
COMPUTER SCIENCE-10 68
Chapter – 2 User Interface
ANSWER KEY
2.1.1 PRINTF ()
2.1.2 FORMAT SPECIFIERS
2.1.3 SCANF ()
2.1.4 GETCH ()
2.1.5 STATEMENT TERMINATOR
2.1.6 ESCAPE SEQUENCE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A D D A A C B B D C A C D A B
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
A C C B C B C A D A B A A C A
31 32 33 34 35 36 37 38
B B C B B C B A
COMPUTER SCIENCE-10 69
Chapter – 3 Conditional Logic
SELECTION STATEMENTS
3.2.1 IF-Statement
3.2 3.2.2 If-Else Statement 72
3.2.3 Nested If-Else Structures
3.2.4 Solved Examples Problems
* PROGRAMMING TIME 80
* SOLVED ACTIVITIES 85
* EXERCISE 88
* PROGRAMMING EXERCISES 93
SHORT QUESTIONS
Q.1 Define Control Statement. (K.B)
Ans: CONTROL STATEMENT
“Control Statement controls the flow of execution of a program” Sometimes we need to
execute one set of instructions if a particular condition is TRUE and another set of
instructions if the condition is FALSE. Moreover, sometimes we need to repeat a set of
statements for a number of times. We can control the flow of program execution through
control statements. There are three types of control statements in C language.
1) Sequential Control Statements
2) Selection Control Statements
3) Repetition Control Statements
Q.2 Name Types of Control Statement. (K.B)
Ans: TYPES OF CONTROL STATEMENT
There are three types of control statements in C language.
1. Sequential Control Statements
2. Selection Control Statements
3. Repetition Control Statements
Sequential Control:
Sequential control is the default control structure in C language. According to the
sequential control, all the statements are executed in the given sequence.
Selection Statements:
The statements which help us to decide which statements should be executed next, on the
basis of conditions, are called selection statements.
Two types of selection statements are:
1. If statement
2. If-else statement
Repetition Control:
The control structure which keeps on repeating a statement or a set of statements upto a
fixed number of time or until an associated condition remains true.
Two types of repetition statements are:
1. FOR statement
2. WHILE statement
3. DO-WHILE statement
MUTLIPLE CHOICE QUESTIONS
1. ______ is the default control structure: (K.B)
(A) Sequence (B) Selection (C) Repetition (D) None of these
2. In _______ control structure the instructions are executed according to ascending
order. (K.B)
(A) Sequence (B) Selection (C) Repetition (D) None of these
3. ________ statement are executed on basis of condition. (K.B+U.B)
(A) Sequential (B) Selection (C) both (D) None of these
4. Condition is always written in _________. (K.B)
(A) Quotes “ ” (B) Parentheses () (C) Braces{} (D) None of these
5. A condition can be _____ expression. (K.B)
(A) Relational (B) Logical (C) Arithmetic (D) All of these
3.2 SELECTION STATEMENTS
COMPUTER SCIENCE-10 71
Chapter – 3 Conditional Logic
3.2.1 IF STRUCTURE
3.2.2IF-ELSE STRUCTURE
3.2.3NESTED SELECTION STRUCTURES:
LONG QUESTIONS
1. Define Selection Statement. Explain IF Statement in detail with an example. (K.B+U.B)
Ans: SELECTION STATEMENTS
The statements which help us to decide which statements should be executed next, on the
basis of conditions, are called selection statements.
Two types of selection statements are:
1 if statement
2 if-else statement
If statement:
C language provides if statement in which we specify a condition, and associate a code
to it. The code gets executed if the specified condition turns out to be true, otherwise the
code does not get executed.
Structure of if statement:
if statement has the following structure in C language:
if (condition)
Associated Code
1. In the given structure, if is a keyword that is followed by a condition inside
parentheses ( ).
2. A condition could be any valid expression including arithmetic expressions, relational
expressions, logical expressions, or a combination of these.
Example:
Here are a few examples of valid expressions that can be used as condition.
a- 5 (TRUE)
b- 5 + 4 (TRUE)
c- 5 – 5 (FALSE)
Any expression that has a non-zero value calculates to true, e.g. expressions a and b
above produce a true value, but the expression c produces a false value. The expression
can also include variables, in that case values inside the variables are used to calculate the
true/false value of the expression.
3. The associated code is any valid C language set of statements. It may contain one or
more statements. The following flow chart shows the basic flow of an if statement.
COMPUTER SCIENCE-10 72
Chapter – 3 Conditional Logic
If we want to associate more than one statements to an if statement, then they need to be
enclosed inside a { } block, but if we want to associate only one statement, then although
it may be enclosed inside { } block, but it is not mandatory.
Example:
#include < stdio.h>
void main ( )
{
int a = 12;
if (a % 2 = = 0)
{
printf (“The variable a contains an even value.”);
printf (“\nYou are doing a great job.”);
}
}
Output:
The variable a contains an even value.
You are doing a great job.
2. Define Selection Statement. Explain IF-ELSE Statement in detail with an example.(K.B+U.B)
Ans: SELECTION STATEMENTS
The statements which help us to decide which statements should be executed next, on the
basis of conditions, are called selection statements.
Two types of selection statements are:
1) if statement
2) if-else statement
IF-ELSE STATEMENT
“if-else statement executes the set of statements under if statement if a condition is true
and executes the set of statements under else otherwise”
General structure of the if-else statement is as follows:
if (condition)
Associated Code
else
Associated Code
Associated code of if statement is executed if the condition is TRUE, otherwise the code
associated with else statement is executed. Following flow chart shows the structure of if-
else statement.
An if statement may not have an associated else statement, but an else statement must
have an if statement to which it is associated. Before else keyword, if there are multiple
statements under if, then they must be enclosed inside the { } block, otherwise compiler
issues an error.
COMPUTER SCIENCE-10 73
Chapter – 3 Conditional Logic
Example:
#include < stdio.h>
void main ( )
{
int a = 15;
if (a % 2 == 0)
{
printf (“The variable a contains an even value.”);
printf (“/nYou are doing a great job.”);
}
else
printf (“The variable a contains an odd value.”);
}
Output:
The variable a contains an odd value.
3. Define nested selection structure. Explain it with suitable examples. (K.B+U.B)
Ans Conditional statements within conditional statements are called nested selection structure.
All the following structures are valid nested selection structures.
if (condition1 is true) if (condition1 is true)
if (condition2 is true) if (condition2 is true)
Associated code Associated code
else else
Associated code if (condition3 is true)
Associated code
Example:
An electricity billing company calculates the electricity bill according to the following
formula.
Bill Amount = Number of Units Consumed X Unit Price
There are two types of electricity users i.e. Commercial and Home Users. For home users the
unit price varies according to the following:
COMPUTER SCIENCE-10 74
Chapter – 3 Conditional Logic
The code associated with an if statement or with an else statement can be any valid ‘C’ language
set of statements. It means that inside an if block or inside an else block, we can have other if
statements or if-else statements. It also means that inside those inner if statement or if-else
statements we can have even more if statements or if-else statements and so on.
COMPUTER SCIENCE-10 75
Chapter – 3 Conditional Logic
SHORT QUESTIONS
Q.1 What are selection statements? (K.B)
Ans: SELECTION STATEMENTS
The statements which help us to decide which statements should be executed next, on the
basis of conditions, are called selection statements. Two types of selection statements are:
1. if statement 2. if-else statement
Q.2 Write the name of types of selection statements. (K.B)
Ans: TYPES SELECTION STATEMENTS
Two types of selection statements are:
1. if statement [Link]-else statement
Q.3 Define Condition. (K.B)
Ans: A condition could be any valid expression including the arithmetic expressions, relational
expressions, logical expression, or a combination of these. Condition always evaluates in
TRUE or FALSE.
Q.4 Define IF statement. (K.B)
Ans: IF STATEMENT
“if-else statement executes the set of statements under if statement if a condition is TRUE
and executes the set of statements under else otherwise”
Syntax:
if (condition)
Associated Code
Q.5 Give Syntax of IF Statement. (K.B+U.B+A.B)
Ans: SYNTAX OF IF STATEMENT
if statement has the following structure in C language:
if (condition)
Associated Code
Q.6 What do you know about associated code? (K.B+U.B)
Ans: ASSOCIATED CODE
The associated code is any valid C language set of statements. It may contain one or more statements.
Q.7 Make a Flow chart to explain IF structure. (K.B+U.B)
Ans:
.
.
.
.
.
else if (condition N)
code to execute if all previous conditions are false but condition N is true;
else
Code to execute if all the conditions are false;
Q.14 Give Syntax of IF-ELSE-IF Statement. (K.B+U.B)
Ans: SYNTAX OF IF-ELSE-IF STATEMENT
General syntax of the if-else-if statement is as follows:
if (condition 1)
Code to execute if condition 1 is TRUE;
else if (condition 2)
Code to execute if condition 1 is FALSE but condition 2 is TRUE;
.
.
.
.
.
else if (condition N)
code to execute if all previous conditions are FALSE but condition N is TRUE;
else
Code to execute if all the conditions are FALSE;
Q.15 Define Nested Selection Structure. (K.B)
Ans: SELECTION STRUCTURE
Conditional statements within conditional statements are called nested selection structures.
Q.16 Write the syntax of nested selection structure. (K.B)
Ans: SYNTAX OF NESTED SELECTION STRUCTURE
All the following structures are valid nested selection structures.
if (condition1 is true) if (condition1 is true)
if (condition2 is true) if (condition2 is true)
Associated code Associated code
else else
Associated code if (condition3 is true)
Associated code
if (condition1 is true) if (condition1 is true)
if (condition2 is true) if (condition2 is true)
Associated code Associated code
else else
Associated code Associated code
else else
if (condition3 is if (condition3 is true)
true) Associated code
Associated code else
Asscoted code
COMPUTER SCIENCE-10 78
Chapter – 3 Conditional Logic
When 67.3 is entered as an input, “PASS” gets printed on console because condition
is true, as 67.3 is greater than 50.
COMPUTER SCIENCE-10 81
Chapter – 3 Conditional Logic
COMPUTER SCIENCE-10 82
Chapter – 3 Conditional Logic
COMPUTER SCIENCE-10 83
Chapter – 3 Conditional Logic
{
float length;
printf (“Enter Length: ”);
scanf (“%f”, &length);
volume = length * length * length;
printf (“Volume is %f”, volume);
}
else if (choice == 2)
{
float length1, radiusl;
printf (“Enter Length: ”);
scanf (“%f”, &length1);
printf (“Enter Radius: ”);
scanf (“%f”, &radius1);
volume = 3.142 * radius1 * radius1 * length1;
printf (“Volume is %f”, volume);
}
else if (choice == 3)
{
float radius;
printf (“Enter Radius: ”);
scanf (“%f”, &radius);
volume = 3.142 * radius * radius * radius;
printf (“Volume is %f”, volume);
}
else
printf (“Invalid Choice”);
}
COMPUTER SCIENCE-10 84
Chapter – 3 Conditional Logic
ACTIVITY 3.4
The eligibility criteria of university for its different undergraduate student programs is
as follows:
BSSE Program : 80% or more marks in Intermediate
BSCS Program : 70% or more marks in Intermediate
BSIT Program : 60% or more marks in Intermediate
Otherwise the university do not enroll a student in any of its programs.
Write a program that takes the percentage of Intermediate marks and tells for which
programs the student is eligible to apply.
Solution
# include <stdio.h>
void main ( )
{
float marks_percentage;
printf(“Enter the percentage of intermediate marks”);
scanf(“%f”,&marks_percentage);
if(marks_percentage>=80)
printf(“You are eligible for BSSE program”);
else if(marks_percentage>=70&&marks_percentage<80)
printf(“you are eligible for BSCS program”);
else if(marks_percentage>=60&&marks_percentage<70)
printf(“You are eligible for BSIT”);
else
printf(“You are not Eligible for any program”);
}
ACTIVITY 3.5
Write a program that takes two integers as input and asks the user to enter a choice from
1 to 4. The program should perform the according to the given table
CHOICE OPERATION
1 Addition
2 Subtraction
3 Multiplication
4 Division
Solution
# include <stdio.h>
void main ( )
{
int num_1,num_2;
int choice;
printf(“Enter first number”);
scanf(“%d”,&num_1);
printf(“Enter second number”);
scanf(“%d”,&num_2);
printf(“Enter your choice press 1 for Addition press 2 for Subtraction
press 3 for Multiplication press 4 for Division”);
if(choice==1)
printf(“Addition=%d”,num_1+num_2);
else if(choice==2)
printf(“Subtraction=%d”,num_1-num_2);
else if(choice==3)
printf(“Multiplication=%d”,num_1*num_2);
else if(choice==4)
printf(“Division=%d”,num_1/num_2);
else
printf(“Invalid Input”);
}
COMPUTER SCIENCE-10 86
Chapter – 3 Conditional Logic
ACTIVITY 3.6
Write a program that finds and display s area of a triangle, parallelogram, rhombus or
trapezium according to the choice of user.
Solution
# include <stdio.h>
void main ( )
{
int choice;
printf(“Enter your choice to find the area of figure\n 1 for Triangle\n 2 for Parallelogram\n 3
for Rhoumbus\n 4 for Trapezium”);
scanf(“%d”, &choice);
if(choice==1)
{ //This block will calculate the area of triangle
float b,h,area;
printf(“Enter the base & height of Triangle”);
scanf(“%f%f”, &b,&h);
area=1/2*b*h;
printf(“The area of figure=%f”,area);
}
else if(choice==2)
{ //This block will calculate the area of Parallelogram
float b,h,area;
printf(“Enter the base & height of Parallelogram”);
scanf(“%f%f”, &b,&h);
area=b*h;
printf(“The area of figure=%f”,area);
}
else if(choice==3)
{ //This block will calculate the area of Rhoumbus
float b,h,area;
printf(“Enter the base & height of Rhoumbus”);
scanf(“%f%f”, &b,&h);
area=b*h;
printf(“The area of figure=%f”,area);
}
else if(choice==4)
{ //This block will calculate the area of Trapezium
float h,side1,side2,area;
printf(“Enter the height,side1 & side 2 of Trapezium”);
scanf(“%f%f%f”,&h,&side1,&side2);
area=1/2*(side1+side2)*h;
printf(“The area of figure=%f”,area);
}
else
printf(“You have enter the wrong choice”);
}
COMPUTER SCIENCE-10 87
Chapter – 3 Conditional Logic
EXERCISE
Q1. Multiple Choice Questions.
1) Conditional logic helps in ________. (K.B)
(A) Decisions (B) Interactions (C) Traversing (D) All of these
2) ________ statements describe the sequence in which statements of the program
should be executed. (K.B)
(A) Loop (B) Conditional (C) Control (D) All of these
3) In if statement, what happens of condition is false? (K.B)
(A) Program crashes (B) Index Out of Bound Error
(C) Further code executes (D) Compiler asks to change condition
4) int a = 5 ; (K.B)
If (a < 10)
a++ ;
else
if (a > 4)
a --;
Which one of the following statements will execute?
(A) a++ (B) b--; (C) both (A) and (B) (D) None of these
5) Which of the following is the condition to check ‘a’ is a factor of ‘c’? (K.B+U.B)
(A) a % c = = 0 (B) c % a = = 0 (C) a*c = = 0 (D) a + c = =0
6) A condition can be any ________ expression. (K.B+U.B)
(A) arithmetic (B) relational
(C) logical (D) arithmetic, relational or logical
7) An if statement inside another if statement is called ________ structure. (K.B)
(A) nested (B) boxed (C) repeated (D) decomposed
8) A set of multiple instruction enclosed in braces is called a _______. (K.B+U.B)
(A) box (B) list (C) block (D) job
ANSWER KEY
1 2 3 4 5 6 7 8
A D C A B D A C
Q2. Define the following terms. (K.B)
1) Control Statements
Ans: CONTROL STATEMENTS
“Control Statement controls the flow of execution of a program”
Sometimes we need to execute one set of instructions if a particular condition is true and
another set of instructions if the condition is false. Moreover, sometimes we need to
repeat a set of statements for a number of times. We can control the flow of program
execution through control statements. There are three types of control statements in C
language.
1. Sequential Control Statements
2. Selection Control Statements
3. Repetition Control Statements
2) Selection Statements
Ans: SELECTION STATEMENTS
The statements which help us to decide which statements should be executed next, on the
basis of conditions, are called selection statements.
Two types of selection statements are:
1. if statement
2. if-else statement
COMPUTER SCIENCE-10 88
Chapter – 3 Conditional Logic
3) Sequential Statements
Ans: SEQUENTIAL STATEMENTS
Sequential control is the default control structure in C language. According to the
sequential control, all the statements are executed in the given sequence.
4) Condition
Ans: A condition could be any valid expression including the arithmetic expressions, relational
expressions, logical expression, or a combination of these. Condition always evaluates in
true or false.
5) Nested Selection Structure
Ans: NESTED SELECTION STRUCTURE
A selection statement within another selection statements is known as Nested Selection
Structure. The general structure of an if-else statement given below:
if (condition)
Associated Code
else
Associated Code
Q3. Briefly Answer the Following. (K.B+U.B)
1) Why do we need selection statements?
Ans: SELECTION STATEMENTS
The selection statements help us to decide which statements should be executed next, on
the basis of conditions. These statements allows us to choose between the alternative
program statements.
2) Differentiate between sequential statements and selection statements.
Ans: STATEMENTS AND SELECTION STATEMENTS
Sequential Statements Selection Statements
Sequential control is the default control The selection statements help us to decide
structure in C language. According to the which statements should be executed next, on
sequential control, all the statements are the basis of conditions. These statements
executed in the given sequence. allows us to choose between the alternative
program statements.
3) Differentiate between IF statements and IF-ELSE statement with an example.
Ans: IF STATEMENTS AND IF ELSE STATEMENT
IF STATEMENT IF ELSE STATEMENT
if statement: if-else Statement:
Definition Definition
C language provides if statement in which we “if-else statement executes the set of
specify a condition, and associate a code to it. statements under if statement if a condition is
The code gets executed if the specified TRUE and executes the set of statements
condition turns out to be TRUE, otherwise the under else otherwise”
code does not get executed. Structure of if else statement:
Structure of if statement: General structure of the if-else statement is as
If statement has the following structure in C follows:
language: if (condition)
If (condition) Associated Code
Associated Code else
۔1 In the given structure, if is a keyword that is Associated Code
followed by a condition inside parentheses ( ). Associated code of if statement is executed if
A condition could be any valid expression the condition is TRUE, otherwise the code
including arithmetic expressions, relational associated with else statement is executed.
expressions, logical expressions, or a Following flow chart shows the structure of
combination of these. if-else statement.
COMPUTER SCIENCE-10 89
Chapter – 3 Conditional Logic
Example: Example:
#include < stdio.h> #include < stdio.h>
void main ( ) void main ( )
{ {
int a = 12; int a = 15;
if (a % 2 = = 0) if (a % 2 == 0)
printf (“The variable a contains an even {
value.”); printf (“The variable a contains an even
printf (“\nYou are doing a great job.”); value.”);
} printf (“/nYou are doing a great job.”);
} }
else
printf (“The variable a contains an odd
value.”);
}
4) What is the use of nested selection structures?
Ans: SELECTION STRUCTURES
Definition:
Conditional statements within conditional statements are called nested selection
structures.
Format of Nested Selection Structure
if (condition 1 is TRUE)
if (condition 2 is TRUE)
associated code
else
associated code
else
5) Write the structure of if statement with brief description
Ans: STRUCTURE OF IF STATEMENT
If statement has the following structure in C language:
If (condition)
Associated Code
In the given structure, if is a keyword that is followed by a condition inside parentheses ( ).
A condition could be any valid expression including arithmetic expressions, relational
expressions, logical expressions, or a combination of these.
COMPUTER SCIENCE-10 90
Chapter – 3 Conditional Logic
Q4. Identify the errors in following code segments. Assume that variables have already
been declared. (K.B+U.B+A.B)
Ans:
Sr # Program Errors
(a) if(x≥10) Error expected in if statement we cannot
printf(“Good”); write expression ≥ like that instead of that
we have to write >=
(b) if (a<b && b<(C); Error expected in if statement we cannot
sum = a+b+c; use statement terminator; at the end of if
else statement.
multiply= a*b*c;
(c) if(a < 7 < (B) Error expected in if statement Logical
printf(“7”); operator (&& / ||) is not used in if
statement.
(d) if(a ==b &| x==y) Error expected in if statement syntax of
flag = true; AND operator is not right logical operator
else cannot be write &| like that instead of that it
flag = false; can be write && like that.
COMPUTER SCIENCE-10 91
Chapter – 3 Conditional Logic
COMPUTER SCIENCE-10 92
Chapter – 3 Conditional Logic
2500 20%
5000 35%
10000 50%
COMPUTER SCIENCE-10 93
Chapter – 3 Conditional Logic
Write a program that takes total bill as input and tells how much discount the user has got
and what the discounted price is.
# include <stdio.h>
void main( )
{
float total_bill , discount;
printf("Enter your Total bill.");
scanf("%f", & total_bill);
if(total_bill>=1000 && total_bill<2500)
{
discount=total_bill*10/100;
printf("discounted price=%f", discount);
}
else if(total_bill>=2500 && total_bill<5000)
{
discount=total_bill*20/100;
printf("discounted price=%f", discount);
}
else if(total_bill>=5000 && total_bill<10000)
{
discount=total_bill*35/100;
printf("discounted price=%f", discount);
}
else if(total_bill>=10000)
{
discount=total_bill*50/100;
printf("discounted price=%f", discount);
}
}
EXERCISE 4
Write a program that takes as input, the original price and sale price of a product and tells
whether the product is sold on profit or loss. The program should also tell the profit/loss
percentage.
#include <stdio.h>
void main()
{
float cost_price,selling_price, amount;
float profit_per, loss_per;
printf("Enter cost price: ");
scanf("%f", &cost_price);
printf("Enter selling price: ");
scanf("%f", &selling_price);
if(selling_price > cost_price)
{
amount = selling_price - cost_price;
profit_per=((amount*100)/cost_price);
printf("Profit = %f", amount);
printf("\nProfit_prcentage = %f", profit_per);
COMPUTER SCIENCE-10 94
Chapter – 3 Conditional Logic
}
else if(cost_price > selling_price)
{
amount = cost_price - selling_price;
loss_per=((amount*100)/cost_price);
printf("Loss = %f", amount);
printf("Loss_prcentage = %f", loss_per);
}
else
{
printf("No Profit No Loss.");
}
}
EXERCISE 5
Write a program that takes as input, the lengths of 3 sides of a triangle and tells whether it
is a right-angle triangle or not. For a right-angled triangle,
Hypotenuse2= base2 + height2
# include <stdio.h>
void main ( )
{
float side1,side2,side3;
printf("Enter three sides of a triangle ");
scanf("%f%f%f", &side1, &side2, &side3);
if(side1*side1 == side2*side2+side3*side3|| side2*side2 == side1*side1+side3*side3||
side3*side3==side1*side1+side2*side2)
printf("yes");
else
printf("No");
}
EXERCISE 6
Following is the eligibility criteria for admission in an IT University.
At least 60% marks in Matric.
At least 65% marks in Intermediate (Pre-Engineering or ICS)
At least 60% marks in entrance test
Write a program that takes as input, the obtained and total marks of Matric, Intermediate
and Entrance Test. The program should tell whether the students is eligible or not.
# include <stdio.h>
void main ( )
{
float obt_marks_matric, total_marks_matric;
float obt_marks_inter, total_marks_inter;
float obt_marks_entry_test, total_marks_entry_test;
float matric_prc, inter_prc, entry_test_prc;
printf("Enter Total marks of matric exams");
scanf("%f", &total_marks_matric);
printf("Enter obtained marks of matric exams");
scanf("%f", &obt_marks_matric);
printf("Enter Total marks of Intermediate exams");
scanf("%f", &total_marks_inter);
COMPUTER SCIENCE-10 95
Chapter – 3 Conditional Logic
ANSWER KEY
3.1 CONTROL STATEMENT
1 2 3 4 5
A A B B D
COMPUTER SCIENCE-10 97
Chapter– 4 Data and Repetition
4.1.1 Array
Loop Structure
* EXERCISE 117
COMPUTER SCIENCE-10 98
Chapter– 4 Data and Repetition
SHORT QUESTIONS
Q.1 Define Data Structure. (K.B)
Ans: Data structure is a container to store collection of data items in a specific layout.
Q.2 How many forms do data structure have? (K.B)
Ans: There are generally four forms of data Structures:
Linear: arrays, lists.
MULTIPLE CHOICE QUESTIONS
1. _________ structure is a container to store data items. (K.B)
(A) Data (B) Control (C) Selection (D) Loop
2. Data structure is a container to store data in ________ layout. (K.B)
(A) Specific (B) Irregular (C) Alternative (D) None of these
3. __________ is type of data structure: (K.B)
(A) Array (B) List (C) Both A & B (D) None of these
4.1.1 ARRAY
4.1.2 ARRAY DECORATION
4.1.3 ARRAY INITIALIZATION
4.1.4 ACCESSING ARRAY ELEMENTS
4.1.5 USING VARIABLES AS ARRAY INDEXES.
LONG QUESTION
1. Briefly Explain Array in detail. (K.B+U.B)
Ans: Definition
An array is a data structure that can hold multiple values of same data type e.g. an ‘int’
array can hold multiple integer values, a ‘float’ array can hold multiple real values and so
on. An important property of array is that it stores all the values at consecutive locations
inside the computer memory.
Array Declaration:
In C language, an array can be declared as follows:
Array Initialization:
Assigning values to an array for the first time, is called array initialization. An array can
be initialized at the time of its declaration, or later. Array initialization at the time of
declaration can be done in the following manner.
Data_type array_name[N] = {value1, value2, value3,……, value N};
Char vowels [5] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}
If we do not initialize an array at the time of declaration. Then we need to initialize the
array elements one by one. It means that we cannot initialize all the elements of array in a
single statement.
Elements of Array:
COMPUTER SCIENCE-10 99
Chapter– 4 Data and Repetition
Each element of an array has an index that can be used with the array name as array-
name [index] to access the data stored at that particular index.
First element has the index 0, second element has the index 1 and so on. Thus height [0]
refers to the first element of array height, height [1] refers to the second element and so
on. Figure shows graphical representation of array height initialized in the last section.
Example:
Write a program that stores the ages of five persons in an array, and then displays on
screen.
Solution:
#include<stdio.h>
void main()
{
int age [5];
/* Following statements assign values at different indices of array age, we can see that the
first value is stored at index 0 and the last value is stored at index 4 */
age [0] = 25;
age [1] = 34;
age [2] = 29;
age [3] = 43;
age [4] = 19;
/* Following statement displays the ages of five persons stored in the array *\
printf(“The ages of five persons are: %d, %d, %d, %d, %d”, age [0], age [1], age
[2], age [3], age [4]);
SHORT QUESTIONS
Q.1 Define Array. (K.B)
Ans: An array is a data structure that can hold multiple values of same data type e.g. an ‘int’
array can hold multiple integer values, a ‘float’ array can hold multiple real values and
so on. An important property of array is that it stores all the values at consecutive
locations inside the computer memory.
Data_type array_name[N] = {value1, value2, value3,……, value N};
Q.2 Draw a diagram to show array declaration. (K.B+U.B+A.B)
Ans:
Flowchart:
In order to understand the for loop structure let’s look at the following flow chart.
Using loops, we can easily take input in arrays. If we want to take input from user in an
array of size 10, we can simply use a loop as follows:
Example:
int a [10];
for (int i =0, i < 10; i++)
scanf(“%d”, &a[i]);
2. Reading values from Arrays using Loops:
Loops help us in reading the values from array. The following code can be used to
display the elements for an array having 100 elements:
Example
for (int i = 0; i < 100; i++)
printf(“%d”, a[i]);
SHORT QUESTIONS
Q.1 Define Loop. (K.B)
Ans: “Loop is a control structure that repeats a statement or set of statements up to a fix
number of times of until a specific condition is satisfied”
Q.2 Write the names of different types of loops. (K.B)
Ans: C language provides three kind of loop structure:
1. for loop
2. while loop
3. do while loop
Q.3 Define ‘for’ Loop. (K.B)
Ans: “for" loop is a type of loop which keeps on repeating a statement or a set of statements
up to a fixed number of times”
Q.4 Write down the syntax of ‘for’ loop. (K.B+U.B)
Ans: In C programming language, ‘for’ loop has the following general syntax.
for (initialization; condition; increment/decrement)
{
Code to repeat
}
Q.5 Draw flowchart to explain ‘for’ loop. (K.B+U.B+A.B)
Ans:
Q.6 Write a program to print “Pakistan” three times using ‘for’ loop. (A.B)
Ans:
for(int i = 0; i < 3; i++)
{
COMPUTER SCIENCE-10 103
Chapter– 4 Data and Repetition
printf(“Pakistan\n”);
}
Q.7 Write a program to display the values from 1 to 10 on screen. (A.B)
Ans:
for (int i = 1; i < = 10; i++)
{
printf(“%d\n”, i);
}
Q.8 Write a program that displays the table of 2. (A.B)
Ans:
#include <stdio.h>
void main()
{
int n=2,j;
for(j=1;j<=10;j++)
{
printf("%d X %d = %d \n",n,j,n*j);
}
}
Q.9 What will happen if condition don’t return false in any case of ‘for’ loop? (K.B+U.B)
Ans: If the condition in loop do not gets false at some point then the loop repeats for infinity
and never terminates
Q.10 Define iteration. (K.B)
Ans: Each run of loop is called an iteration
Q.11 Define Nested ‘for’ Loop. (K.B)
Ans: A loop in a loop is known as nested loop.
Q.12 Write down the structure of Nested ‘for’ loop. (K.B)
Ans: for (initialization; condition; increment/decrement)
{
for (initialization; condition; increment/decrement)
{
Code to repeat
}
}
Q.13 Write a program that shows the working of nested ‘for’ loop. (A.B)
Ans:
#include<stdio.h>
void main()
for(int i =1; i < = 5; i++)
{
for(int j =1; j < = i; j++)
{
printf(“*”);
}
printf(“\n”);
COMPUTER SCIENCE-10 104
Chapter– 4 Data and Repetition
}
}
Q.14 Write a program that displays the table of 2, 3, 4, 5 and 6. (A.B)
Ans:
#include <stdio.h>
void main()
{
int n=2,j;
printf(“TABLE OF 2”);
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
n=3;
printf(“\nTABLE OF 3”);
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
n=4;
printf(“\nTABLE OF 4”);
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
n=5;
printf(“\nTABLE OF 5”);
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
n=6;
printf(“\nTABLE OF 6”);
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
}
Q.15 How loops can be used to read and write values in arrays. (K.B+U.B)
Ans: Writing values in Array using Loops:
Using loops, we can easily take input in arrays. If we want to take input from user in an
array of size 10, we can simply use a loop as follows:
int a [10];
COMPUTER SCIENCE-10 105
Chapter– 4 Data and Repetition
printf(“%d”, i);
(A) 10 (B) 0123456789 (C) 0 (D) Syntax Error
11. What will be the output of following C code? (K.B+U.B+A.B)
for(i=0; i++; i<15)
printf(“%d ”, i);
(A) 10 11 12 13 14 (B) 9 10 11 12 13
(C) Infinite Loop (D) 10 11 12 13 14 15 16
12. What will be the final value of the variable ‘digit’? (U.B+A.B)
void main()
{
int digit = 0;
for( ; digit < = 9; )
digit++;
digit *= 2;
digit;
}
(A) -1 (B) 17 (C) 19 (D) 26
13. Which one of the following is not a loop statement? (K.B)
(A) for (B) if (C) while (D) do – while
14. When number of iterations of execution are known in advance, which is the best
choice of programmer? (K.B+U.B)
(A) for (B) do – while (C) while (D) None of These
15. How many expressions are used in for Loop? (K.B)
(A) 2 (B) 4 (C) 5 (D) 3
16. Which are the mandatory part of for Loop? (K.B+U.B)
(A) Initialization (B) Condition
(C) Increment/Decrement (D) All of these
17. The for loop expressions are enclosed in: (K.B+U.B)
(A) ( ) (B) { } (C) [ ] (D) None of These
18. Which of the following expression is executed only once in the for Loop? (K.B+U.B)
(A) Condition Loop Control (B) Increment/Decrement
(C) Initialization (D) None of These
}
Description:
Consider the example program given above.
First of all, the value of i is set to 1 and then condition is checked.
As the condition is true (1<= 10) so loop body executes. As in the loop body,
we are displaying the value of the counter variable, so 1 is displayed on
console.
After increment, the value of i becomes 2. The condition is again checked. It
is true as(2<=10) so this time 2 is printed.
The procedure continues till 10 is displayed and after increment the value of i
becomes 11. Condition is checked and it turns out to be false (11>10) so the
loop finally terminates after printing the numbers from 1 to 10.
Programming Time 4.4
Write a program that calculates the factorial of a number input by user.
Program Logic:
When we want to solve a problem programmatically, first we need to know exactly
what we want to achieve. In this example, we are required to find the factorial of a
given number, so first we need to know the formula to find factorial of a number.
N! = 1 * 2 * 3 * 4 * ..... * (N-1) * N
We can see the pattern that is being repeated, so we can solve the problem using for
loop.
Program:
#include<stdio.h>
void main()
{
int n, fact = 1;
printf(“Please enter a positive number whose factorial you want to find”);
scanf("%d, &n);
for(int I = 1; i <=n; i++)
{
fact = fact * i;
}
printf(“The factorial of input number %d is %d, n, fact);
}
Description:
Following table shows the working of program, if the input number is 5. It
demonstrates the changes in the values of variables at each iteration.
Iteration Value of counter Condition Loop body Result
fact=1
1 i=1 TRUE(1<=5) fact = fact*i fact=1*1=1.
2 i=2 TRUE(2<=5) fact = fact*i fact=1*2=2
3 i=3 TRUE(3<=5) fact = fact*i fact=2*3=6
}
Output:
Here is the output of above program.
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Description:
As we understand the working of inner loop, so here let's focus on outer loop.
1- For the value i = 1, condition in outer loop is checked which is true (1 < = 5),
so whole inner loop is executed and numbers from 1 – 10 are displayed.
2- When control gets out of inner loop, printf("\n”); is executed which inserts a
new line on console.
3- Then i is incremented and it becomes 2. As it is less than 5, so condition is
true. The whole inner loop is executed, and thus numbers from 1 – 10 are
again displayed on screen. Coming out of the inner loop new line is inserted
again.
4- After five times displaying the numbers from 1 – 10 on screen, the value of i
gets incremented to 6 and condition of outer loop turns false. So outer loop
also terminates.
Programming Time 4.6
Problem:
Write a program to display the following pattern of stars on screen.
*
**
***
****
*****
******
Program:
#include<stdio.h>
void main ( )
{
for(int i = 1; i <= 6; i++)
{
for(int j = 1; j <= i; j++)
printf(“*”);
printf(“\n”);
}
}
Description:
Here is the description of above code.
1- As we have to display 6 lines containing stars, so we run the outer loop from
1 to 6.
2- We can observe that in the given pattern we have 1 star on 1st line, 2 stars on
2nd line, 3 stars on 3rd line and so on. So, the inner loop is dependent on the
outer loop, i.e. if counter of outer loop is 1 then inner loop should run 1 time,
COMPUTER SCIENCE-10 112
Chapter– 4 Data and Repetition
if the counter of outer loop is 2 then inner loop should run 2 times and so on.
So, we use the counter of outer loop in the termination condition of inner loop
i.e. j <= i.
3- When outer loop counter i has value 1, inner loop only runs 1 time, so only 1
star is displayed. When outer loop counter is 2, the inner loop runs 2 times, so
2 stars are displayed and the process is repeated until six lines are complete.
Programming Time 4.7
Problem:
Write a program that counts multiples of a given number lying between two
numbers.
Program:
#include <stdio.h>
void main ()
{
int n, lower, upper, count = 0;
printf (“Enter the number: ”);
scanf (“%d", &n);
printf (“Enter the lower and upper limit of multiples:\n");
scanf (“%d%d”, &lower, &upper);
for(int i = lower; i <= upper; i++)
if(i%n == 0)
count++;
printf ("Number of multiples of %d between %d and %d are %d”, n, lower,
upper, count);
}
Programming Time 4.8
Problem:
Write a program to find even numbers in integers ranging from n1 to n2 (where nl is
greater than n2).
Program:
#include <stdio.h>
void main ( )
{
int n1, n2;
printf (“Enter the lower and upper limit of even numbers: \n”)
scanf (“%d%d", &n2, &n1);
if(n1 > n2)
{
for (int i = n1; i > = n2; i--)
{
COMPUTER SCIENCE-10 113
Chapter– 4 Data and Repetition
if(i % 2 == 0)
printf (“%d”, i);
}
}
}
Programming Time 4.9
Problem:
Write a program to determine whether a given number is prime number or not.
Program:
#include <stdio.h>
void main ( )
{
int n;
int flag = 1;
printf (“Enter a number: ”);
scanf (“%d”, &n);
for (int i = 2; i < n; i++)
{
if (n % i == 0)
flag = 0;
}
if (flag == 1)
printf (“This is a prime number”);
else
printf (“This is not a prime number”);
}
Programming Time 4.10
Problem:
Write a program to display prime numbers ranging from 2 to 100.
Program:
# include<stdio.h>
int main ()
{
int flag;
for (int j = 2; j <= 100; j++)
{
flag = 1;
{
printf("%d X %d = %d \n",n,j,n*j);
}
}
ACTIVITY 4.2
Write a program that displays the table of 2,3,4,5 and 6.
Solution:
#include <stdio.h>
void main()
{
int n=2,j;
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
n=3;
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
n=4;
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
n=5;
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
n=6;
for(j=1;j<=10;j++)
{
printf("%d x %d = %d \n",n,j,n*j);
}
}
ACTIVITY 4.3
Write a program that takes as input the marks obtained in matriculation by 30 students
of a class. The program should display the average marks of the class.
Solution:
#include<stdio.h>
void main()
{
int i;
int Avg;
int maks[30]; //Array Declaration
int sum=0;
for( i=0 ; i<=29 ; i++)
{
printf(" Enter Marks/n ");
scanf("%d" , &marks[i] ); // Store Data in Array
}
for( i=0 ; i<=29 ; i++ )
{
Sum = sum + marks[i]; // Read Data from an Array
Avg = Sum/30;
printf(" Average Marks = %d\n" , Avg);
}
}
EXERCISE
Q1. Multiple Choice Questions
1) An array is a__________structure. (K.B)
A) Loop B) Control C) Data D) Conditional
2) Array elements are stored at ________ memory locations. (K.B)
A) Contiguous B) Scattered C) Divided D) None
3) If the size of an array is 100, the range of indexes will be ________. (K.B)
A) 0-99 B) 0-100 C) 1-100 D) 2-102
4) _______ structure allows repetition of a set of instructions. (K.B+U.B)
A) Loop B) Conditional C) Control D) Data
5) _______ is the unique identifier, used to refer to the array. (K.B)
A) Data Type B) Array Name C) Array Size D) None
6) Array can be initialized ________ declaration. (K.B)
COMPUTER SCIENCE-10 117
Chapter– 4 Data and Repetition
Ans: No Loop is not a data structure. Loop is a type of control structure which repeats a
statement of set of statements. While Data Structure is a container to store collection of
data items in a specific layout.
2) What is the use of nested loops?
Ans: When we use a loop inside another loop, it is called nested loop structure. We use nested
loops to repeat a pattern multiple time.
General Structure
for (initialization; condition; increment/decrement)
{
for (initialization; condition; increment/decrement)
{
Code to repeat
}
}
3) What is the advantage of initializing an array at the time of declaration?
Ans: If we do not initialize an array at the time of declaration. Then we need to initialize the
array elements one by one. It means that we cannot initialize all the elements of array in a
single statement. This is demonstrated by the following example.
Example:
The compiler generates an error on the above example code, as we try to initialize the
whole array in one separate statement after declaring it.
4) Describe the structure of a for loop.
Ans: for (initialization; condition; increment/decrement)
{
Code to repeat
}
Step 1. Initialization is the first part to be executed in a for loop. Here we initialize our
counter variable and then move to the condition part.
Step 2. Condition is declared and checked, and if it turns out to be false, then we come out of
loop.
Step 3. If the condition is true, then body of the loop is executed.
Step 4. After executing the body of loop, the counter variable is increased or decreased
depending on the used logic, and then we again move to the step 2.
5) How can you declare an array? Briefly describe the three parts of array declaration.
Ans: In C language, an array can be declared as follows:
KLMN
(A) (B)
# include<stdio.h> #include <stdio.h>
void main ( ) int main( )
{ {
int i,j; int i,j,rows=5;
for(i=1;i<=3;i++) char alphabet='A';
{ printf("\nHere your pattern\n");
for(j=1;j<=i;j++) for(i=1; i<=rows; i++)
{ {
printf(“*****”); for(j=1; j<=i; j++)
}
{
printf(“\n”); printf(alphabet++);
}
} printf(“\n”);
} }
}
EXERCISE 2
Write a program that takes two positive integers a and b as input and displays the value of ab.
# include <stdio.h>
int main ( )
{
int a,b,result=1;
printf("Enter a:");
scanf ("%d",&a);
printf("Enter b:");
scanf ("%d",&b);
for (int i=1;i<=b;i++)
{
result=result*a;
}
printf("result=%d^%d=%d",a,b,result);
}
EXERCISE 3
Write a program that takes two numbers as input and displays their Greatest Common
Divisor (GCD) using Euclidean method.
# include <stdio.h>
void main( )
{
int m, n,r;
printf("Enter-two integer numbers: ");
scanf ("%d %d", &m, &n);
for (;n > 0;)
COMPUTER SCIENCE-10 122
Chapter– 4 Data and Repetition
{
r = m % n;
m = n;
n = r;
}
printf ("GCD = %d \n",m);
}
EXERCISE 4
Write a program to display factorials numbers from 1 to 7. (Hint: Use Nested Loops)
# include<stdio.h>
void main ( )
{
int i,j,fact=1;
for(i=1;i<=7;i++)
{
for(j=1;j<=i;j++)
{
fact=fact*j;
}
printf(“\n%d”,fact);
fact=1;
}
}
EXERCISE 5
Write a program that takes 10 numbers as input in an array and displays the product of
first and last element on console.
# include<stdio.h>
void main ( )
{
int i,arr[10],mult;
printf(“Enter 10 elements:”);
for(i=0;i<10;i++)
scanf(“%d”,&arr[i]);
mult=arr[0]*arr[9];
printf(“Result of first and last element =%d”,mult);
}
EXERCISE 6
Write a program that declares and initializes an array of 7 elements and tells how many
elements in the array are greater than 10.
# include <stdio.h>
void main ( )
{
int counter=0,arr[ ]={3,54,22,67,34,29,19};
for(int i=0;i<7;i++)
{
if(arr[i] > 10)
COMPUTER SCIENCE-10 123
Chapter– 4 Data and Repetition
counter++;
}
printf(“The total number of elements greater than 10 are %d”,counter);
}
ANSWER KEY
4.1 DATA STRUCTURE
1 2 3
A A C
4.1.1 ARRAY
4.1.2 ARRAY DECRORATION
4.1.3 ARRAY INITIALIZATION
4.1.4 ACCESSING ARRAY ELEMENTS
4.1.5 USING VARIABLES AS ARRAY INDEXES.
1 2 3 4
A A B C
4.2 LOOP STRUCTURE
4.2.2 FOR LOOP
4.2.3 NESTED LOOP
4.2.5 ARRAY AND LOOPS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A B A A A A A A A D A A D C A
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
C B C C C C B D D C A A C A B
31 32 33
A A C
FUNCTIONS
* EXERCISE 132
5.1 FUNCTIONS
COMPUTER SCIENCE-10 124
Chapter– 5 Functions
Dividing the program into multiple functions, improves the readability of the program.
3. Define Functions. How can a function be defined? (K.B+U.B)
Ans: “A function is a block of statements which performs a particular task”
The function signature does not describe how the function performs the task assigned to
it. Function definition does that.
General Syntax of a Function:
A function definition has the following general structure.
return_type function_name (data_type var1, data_type var2,..,data_type varN)
{
Body of the function
}
Body of the function is the set of statements which are executed in the function to
perform the specified task.
We need to call a function, so that it performs the programmed task. Following is the
general structure used to make a function call.
function_name (value1, value2,.., valueN);
There may be multiple return statement in a function but as soon as the first return
statement is executed, the function call returns and further statements in the body of
function are not executed. Return is a keyword that is used to return a value to the calling
function. Output of the function is called its return value. A function cannot return more
than one value. If we try to get more than one value then compiler gives an error. There
may be multiple return statement in a function but as soon as the first return statement is
executed, the function call returns and further statements in the body of function are not
executed.
Example:
void show pangram ()
{
printf (“\nA quick brown fox jumps over the lazy dog. \n”);
}
As the above function does not return anything thus return type of the function is void.
SHORT QUESTIONS
1. Define Divide and Conquer Rule. (K.B)
Ans: In divide and conquer rule the problem is decomposed into sub problems. Rather on
concentrating the bigger problem as a whole we try to solve each sub problem separately.
This leads to a simple solution.
2. Define Functions. (K.B)
Ans: A function is a block of statements that performs a particular task, e.g. printf is function that
is used to display anything on computer screen, scanf is another function that is used to take
input from the user. Each program has a main function which performs the tasks
programmed by the user. Similarly, we can write other functions and use them multiple
times.
3. Give general syntax of Functions. (K.B+U.B+A.B)
Ans: A function definition has the following general structure.
return_type function_name (data_type var1, data_type var2,..,data_type varN)
{
Body of the function
}
4. Write down the name of types of Functions. (K.B)
COMPUTER SCIENCE-10 126
Chapter– 5 Functions
A functions that takes three integers as input and returns the largest value int largest (int,
among them. int, int);
A function that takes radius of a circle as input and returns the area of float area
circle. (float);
A function that takes a character as input and returns 1, if the character is a int isvowel
vowel, otherwise returns 0. (char);
13. How can a function be called? (U.B)
Ans: Calling a function is the set of statements which are executed in the function to fulfil the
specified task. Calling a function means to transfer the control to that particular function.
During the function call, the values passed to the function are called arguments. We can
call a user-defined function from another user defined function, same as we call other
functions in main function.
14. What is the purpose of the keyword ‘return’? (K.B)
Ans: return is a keyword that is used to return a value to the calling function. Output of the
function is called its return value. A function cannot return more than one value. If we
try to get more than one value, then compiler gives an error. There may be multiple return
statement in a function but as soon as the first return statement is executed, the function
call returns and further statements in the body of function are not executed.
15. Define arguments. (K.B)
Ans: The values passed to the function are called arguments.
16. Define parameters. (K.B)
Ans: The variables in the function definition that receive these value is called parameters of
the function.
17. Write down the difference between arguments and parameters. (K.B+U.B)
Ans: The values passed to the function are called arguments, whereas variables in the function
definition that receive these value are called parameters of the function.
18. What points should be kept in mind for the arrangement of function? (K.B+U.B)
Ans: Following points must be kept in mind for the arrangement of function in a program.
1. If the definition of called function appears before the definition of called function,
then function signature is not required.
2. If the definition of called function appears after the definition of calling function, then
function signature of called function must be written before the definition of calling
function.
MULTIPLE CHOICE QUESTIONS
1. Instead of solving the whole problem at once we try to apply ______ approach. (K.B+U.B)
(A) Divide & Conquer (B) Reusability
(C) Readability (D) None of these
2. _______ is a block of statements, which performs a particular task. (K.B)
(A) Program (B) Function (C) Both A & B (D) None of these
3. There are ______ type of function: (K.B)
COMPUTER SCIENCE-10 128
Chapter– 5 Functions
(A) Input (B) Output (C) Both A & B (D) None of these
}
else
printf(“You entered a negative number.”);
}
EXERCISE
Q1. Multiple Choice Questions
1. Function could be built-in or __________. (K.B)
A) Admin Defined B) Server Defined C) User Defined D) Both A & C
2. The functions which are available in C Standard Library are called_________. (K.B)
A) User-Defined B) Built-In C) Recursive D) Repetitive
3. The values passed to a function are called__________. (K.B+U.B)
A) Bodies B) Built-In C) Arrays D) Arguments
4. Char cd() {return ‘a’}. in this function “char” is__________. (K.B)
A) Body B) Return Type C) Array D) Arguments
5. The advantages of using functions are__________. (K.B)
A) Readability B) Reusability C) Easy Debugging D) All
6. If there are three return statements in the function body, __________ of them will
be executed. (K.B+U.B)
A) One B) Two C) Three D) First & Last
7. Readability helps to __________ the code. (K.B)
A) Understand B) Modify C) Debug D) All
8. __________ means to transfer the control to another function. (K.B)
A) Calling B) Defining C) Re-Writing D) Including
ANSWER KEY
1 2 3 4 5 6 7 8
C B D B D A D A
Q2. Define the following terms. (K.B)
1) Functions.
Ans: A function is a block of statements that performs a particular task, e.g. printf is function
that is used to display anything on computer screen, scanf is another function that is used to
take input from the user. Each program has a main function which performs the tasks
programmed by the user. Similarly, we can write other functions and use them multiple
times.
2) Built-in functions.
Ans The functions which are available in C standard Library are called built-in Functions. These
functions perform commonly used mathematical calculations, string operations, input/ output
operations etc. For example, printf and scanf are built-in functions.
3) Functions Parameters.
Ans: A function is a block of statement that gets some inputs and provides some output. Inputs
of a function are called parameters of the function. A function can have multiple
parameters, but it cannot return more than one values.
4) Reusability.
Ans: Functions provide reusability of code. It means that whenever we need to use the
functionality provided by the function, we just call the functions. We do not need to write
int main ()
{
int p = xyx(5);
p = xyz(p);
printf(“%d “,p);
}
b) void abc (int a, int b, int c)
{
int sum = a + b + c;
}
int main()
4 7 23
{
int x = 4, y = 7, z = 23, sum1 = 0;
abc (x, y, z);
printf (“%d %d %d” x, y, z);
}
c) int aa (int x)
{
int p = x / 10;
x++;
p = p + (p*x);
return p; We got 260
}
int main()
{
printf (“we got %d “, aa(aa(23)));
}
d) float f3(int n1, int n2)
{
n1 = n1 + n2;
n2 = n2 – n1;
return 0;
} 0.000000
0.000000
int main()
{
printf(“%f\n”, f3(3, 2));
printf(“%f\n”, f3(10, 6));
}
int main()
{
printf("Enter a Number to Find Factorial: ");
printf("\nFactorial of a Given Number is: %d ",fact());
return 0;
}
int fact()
{
int i,fact=1,n;
scanf("%d",&n);
for(i=1; i<=n; i++)
{
fact=fact*i;
}
return fact;
}
Exercise 4
Write a function which takes values for three angles of a triangle and prints whether the
given values make a valid triangle or not. A valid triangle is the one, where the sum of three
angles is equal to 180.
Solution:
#include <stdio.h>
int main( )
{
int side1, side2, side3;
printf("Enter the Lengths of Three Sides of a Triangle\n");
scanf("%d %d %d", &side1, &side2, &side3);
if((side1 + side2 > side3)&&(side2 + side3 > side1) &&(side3 + side1 > side2))
{
printf("It is a Valid Triangle\n");
}
else
{
printf("It is an invalid Triangle");
}
return 0;
}
Exercise 5
Write a function which takes the amount and the interest percentage and return the
interest amount.
Solution:
#include<stdio.h>
// function declaration
double calculateInterest(double p, double r);
// main function
int main()
{
// declare variables
double p, r, interest;
// take input from end-user
printf("Enter principal amount and rate:");
scanf("%lf %lf",&p,&r);
// calculate interest
interest = calculateInterest(p, r);
// display result
printf("Interest=%lf\n", interest);
return 0;
}
// function to calculate interest value
double calculateInterest(double p, double r)
{
return (p*r)/100;
}
Exercise 6
Write a function which takes a number as input and displays its digits with spaces in
between.
Solution:
#include <stdio.h>
#define MAX 100
// Function to print the digit of number N
void printDigit(int N)
{
// To store the digit of the number N
int arr[MAX];
int i = 0;
int j, r;
// Till N becomes 0
while (N != 0) {
// Extract the last digit of N
r = N % 10;
// Put the digit in arr[]
arr[i] = r;
i++;
// Update N to N/10 to extract next last digit
N = N / 10;
}
// Print the digit of N by traversing arr[] reverse
for (j = i - 1; j > -1; j--)
{
printf("%d ", arr[j]);
}
}
int main()
{
int N = 3452897;
printDigit(N);
return 0;
}
Exercise 7
Write a function to print the table of a number.
#include<stdio.h>
int table(int n);
int main()
{
int n=0;
printf("Enter Number: ");
scanf(“%d”,&n);
table(n);
}
int table(int n)
{
int t=1;
printf("Table of %d is:\n ",n);
for(int i=1; i<=10; i++)
{
t=n*i;
printf(“\n%d x %d=%d”,n,i,t);
}
return 0;
}
ANSWER KEY
5.1 FUNCTIONS
5.1.1 TYPES OF FUNCTIONS
5.1.2 ADVANTAGES OF FUNCTIONS
5.1.3 SIGNATURE OF A FUNCTION
5.1.4 DEFINING A FUNCTION
COMPUTER SCIENCE-10 139
Chapter– 5 Functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
C A B B B A C A A D D C A A A
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
B C B A A A A C C C C D B A A
31 32 33 34 35
C B B C A
C functions enable task separation by encapsulating specific functionality within individual blocks, or functions, that can be separately defined and iterated. This modular structure means each function can be developed, tested, and maintained independently, simplifying program updates and learning curves. Task separation particularly aids in large project management by organizing code logically and reducing the interdependencies that often complicate debugging and enhancements .
Functions promote code reusability by allowing code blocks to be defined once and reused multiple times across a program. This means that to perform a certain task, we just need to call the associated function instead of rewriting code. Functions also aid in separating tasks by isolating specific tasks into distinct functions. This modularity enables easier debugging, as issues can be isolated within a particular function rather than the entire program, reducing complexity and improving readability .
A 'for' loop is structured with initialization, condition, and increment parts, which control the sequence of numbers it generates. For example, to print numbers from 1 to 10, use: for (int i = 1; i <= 10; i++) { printf('%d\n', i); }. This loop begins at 1, checks if the current number is less than or equal to 10, outputs it, and then increments the number by 1, continuing until the condition fails .
Loops efficiently manage arrays by iterating through each element for reading or writing. Using a 'for' loop, an array can be populated with values from user input or predefined calculations by accessing each index in sequence. For example, you can initialize an array with user inputs using: for (int i = 0; i < 10; i++) scanf('%d', &a[i]); Similarly, loops can be used to read array values, such as printing array elements: for (int i = 0; i < 100; i++) printf('%d', a[i]); This approach reduces redundancy and manual coding errors .
Nested loops, which involve placing one loop inside another, are often used for multidimensional data structures like matrices. They enable operations over rows and columns by iterating through each element comprehensively. However, care must be taken with nested loops as they can significantly increase the computational load and complexity of a program, leading to performance issues. Efficient break conditions and careful design can prevent infinite loops and manage resource usage effectively .
Relational operators are used to compare two values and determine the relationship between them, returning TRUE or FALSE based on the comparison. Examples include '==', '!=', '<', '>', '<=', and '>='. Logical operators, on the other hand, are used for forming compound conditions by combining multiple expressions, also resulting in TRUE or FALSE. Examples include AND (&&), OR (||), and NOT (!). While relational operators focus on direct comparison, logical operators handle the combination and inversion of logical expressions .
Functions improve readability by breaking down programs into smaller, distinct blocks with defined tasks, making it easier to follow the code's logic. This separation also enhances debugging processes by localizing errors to specific areas, thereby reducing the time spent identifying and resolving issues. By focusing on individual functions, programmers can concentrate on solving one problem at a time, facilitating a clearer understanding and maintenance of code .
Operator precedence determines the order in which operations are executed in expressions without parentheses. Higher precedence operators are evaluated before lower precedence ones, which can significantly alter the outcome of an expression if not properly managed. For example, in the expression 3 + 4 * 5, multiplication (*) has a higher precedence than addition (+), so the expression evaluates as 3 + (4 * 5), resulting in 23 rather than 35. Misunderstanding precedence can lead to logical errors in code execution .
Loops reduce code redundancy by allowing a block of code to execute repeatedly without manually writing it numerous times, particularly useful in tasks like iterating over arrays or handling repeated data entry. 'For', 'while', and 'do-while' loops provide different mechanisms to handle iteration based on condition checks. By managing a specified number of iterations or continuing until conditions are met, loops simplify complex data processing tasks, enhance program efficiency, and ensure concise code structure .
The NOT operator negates the value of a Boolean expression, returning TRUE if the input is FALSE and FALSE if the input is TRUE. The AND operator returns TRUE only if both operands are TRUE; otherwise, it returns FALSE. The OR operator returns TRUE if at least one of the operands is TRUE. For instance, with the AND operator: FALSE && FALSE yields FALSE, TRUE && TRUE yields TRUE. With the OR operator: FALSE || TRUE yields TRUE, TRUE || FALSE yields TRUE, and TRUE || TRUE yields TRUE. The NOT operator example: !(TRUE) yields FALSE .