0% found this document useful (0 votes)
431 views42 pages

Computer Class 10th Notes 1

Uploaded by

kaka0071sa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
431 views42 pages

Computer Class 10th Notes 1

Uploaded by

kaka0071sa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPUTER

SCIENCE
TH
CLASS 10
EASY NOTES

BY MUHAMMAD DANISH ROOMAN KHAN


MCS (GOLD MEDALIST), [Link]
SST-IT GHS NO.5 DIKHAN
UNIT 1

PROGRAMMING TECHNIQUES

Q2. Give short answers to the following questions.

i. Define Problem analysis?


Problem Analysis
Problem is an obstacle, difficulty or challenge that requires resolution.
Problem analysis means to investigate or identify a situation or problem and to establish
the causes and effects related to that problem in order to allow the researcher to fully
understand the problem and comes up with its possible solutions.

ii. How the solution of the problem is planned?


After problem analysis, the solution of problem is planned. There can be various
solutions for a problem but the proposed solution should be cost-effective, time-
effective, speedy and less complex.

iii. Define Candid solution of a problem?


There may be several alternatives for solving the problem however finding the best and
the most suited solution is called candid solution of the problem.

iv. Define any three problem solving techniques?


The following are three useful problem solving techniques
Abstraction: solving the problem in a model of the system before applying it to the real
system.
Analogy: using a solution that solved analogous (similar) problem.
Trial and error: testing possible solutions until the right one is found.

v. List various factors for selecting the best solution of any problem.
The following factor are very important in selecting the best solution of any problem.
a. Speed
b. Cost
c. Complexity

2
a. Speed
To develop an efficient solution for solving the problems, the time it uses is the
major measure of the efficiency of that solution.
b. Cost
Cost of a solution includes, space and other hardware and software requirements.
The solution will be considered to be the best of if it gives optimal desired result
with minimum cost.
c. Complexity
Complexity of the solution means the resources required by the solution, most
commonly known as time – how many steps it needs and the space – how much
memory it takes.

Q3. Define an algorithm and explain the role of algorithm in problem


solving?

Algorithm

An Algorithm is a well-defined list of steps for solving a particular problem. It is a well-


defined computational procedure that takes some value, or set of values, as input and
produces some value or set of values as output. Thus it is sequence of computational steps
that transform the input into the output.

Role of Algorithm in Problem Solving

Algorithm plays and important role in developing solution to a problem. For example, if we
have a complex situation which requires a lot of information to be gathered and a lot of data
to be processed. Then by dividing each activity of this information gathering and data
processing into steps will make the problem solution an easy task. “Divide and Rule” a very
famous rule that makes the problem solving an easy task.

For example, consider we find the average of 20 numbers. If this process is defined in small
discrete steps then we can make the solution very easily.

1. Select any 20 numbers


2. Add all the numbers
3. Divide the result of step 2 by total no of observations i.e., 20
4. The average will be calculated

3
Q4. Describe the criteria for measuring efficiency of an algorithm on the basis of:
a. Inputs needed
b. Processing to be completed
c. Decision to be taken
d. Outputs to be provided

Criteria for measuring efficiency of an Algorithm

Efficiency of an algorithm describes properties of an algorithm relating to how much of


various types of resources it consumes. The two most frequently measurable metrics of an
algorithm are:

 Speed or running time – the time it takes for an algorithm to complete, and
 ‘Space’ the memory used by the algorithm during its operation.
The efficiency of an algorithm can be also measured on the basis of following factors:
a. Inputs needed
The amount of time an algorithm takes depends on how large in the input on which
the algorithm most operate. For example, multiplying huge matrices takes longer than
multiplying small ones, etc. An algorithm might take different amounts of time inputs
of the same size.
b. Processing to be completed
The time required to complete the operation is a measure for efficiency of an
algorithm. The process completion time is composed of cycle time, wait time and
processing time.
c. Decision to be taken
Problem solving and decision-making are important skills to improve the efficiency of
an algorithm and get optimal result.
d. Outputs to be provided
An Algorithm is said to be correct if, for every important instance, it ends with the
correct output.

4
Q5. What is flowchart? Explain flowchart symbols in detail.

Flowchart
Flowchart is a diagrammatic or symbolic representation of algorithm which is used to
analyze, improve, document and manage a process or program. It is a type of diagram
representing a process using different symbols containing information about steps in a
problem. Each of the symbols is linked with arrows to illustrate the flow direction of the
process towards a solution.

Symbol Name Function

Oval Oval represents a start and end of a flowchart

Arrow lines used to show the flow of control from one step
to the other. They also indicate progress from one step to
Arrow lines another

Parallelogram used to represent input/output. For


Parallelogram example, INPUT N, READ A, PRINT N, DISPLAY B,
etc.

Rectangle represents a process activity or step. For


Rectangle example, X = 25, EXP = A2 + B2, etc.

Diamond is used when there is a decision to be made or


question to be answered, such as Yes/No or True/False.
Diamond The path to be taken is determined by the answer to
question. For example,
IS A > B?, IS X = 10, etc.

5
Q6. Write an algorithm to calculate the factorial of a given number and draw flowchart
for it?

Algorithm:
Start
This algorithm is used to calculate
factorial of a given number.

Step 1. Read NUM


Input NUM
Step 2. Set FR = 1, k = 1

Step 3. Repeat Step 4 and 5


K=1
While k < = NUM FR = 1
Step 4. Set FR = FR * k

Step 5. k = k + 1
FR = FR * K
[End of While loop] K= K + 1

Step 6. Write FR

Step 7. Exit
IS
YES
K < = NUM

NO

Output FR

Stop

6
Q6. Write an algorithm and draw a flowchart to resolve quadratic
equation?

Algorithm:
Start
This algorithm is used to resolve the
quadratic equation

Step 1. Read A, B, C
Input A, B, C
Step 2. Set D = SQRT(B x B - 4 x A x C)

Step 3. Set X = – B + D / 2A

Step 4. Set Y = – B – D / 2A D = SQRT (B x B – 4 x A x C)

Step 4. Write X, Y

Step 5. Exit
X = - B + D / 2A

Y = - B – D / 2A

Output X, Y

Stop

7
Q8. Write an algorithm and draw a flowchart to find average marks of
eight subjects for a student.

Algorithm:
Start
This algorithm is used to find average
marks of eight subjects for a student.

Given: M1, M2, M3, M4, M5, M6, M7,


M8 are the marks of eight subjects and Input
AVG is average of these marks. M1, M2, M3, M4, M5, M6,
M7, M8
Step 1. Read M1, M2, M3, M4, M5,
M6, M7, M8

Step 2. Set SUM = M1 + M2 + M3 +


M4 + M5 + M6 + M7 + M8

Step 3. Set AVG = SUM / 8


SUM = M1 + M2 + M3 + M4 + M5 +
Step 4. Write AVG M6 + M7 + M8
Step 5. Exit

AVG = SUM / 8

Output AVG

Stop

8
UNIT 2

PROGRAMMING IN C

Q2. Give short answers to the following questions.

i. Differentiate between program syntax and program semantic?


Program Syntax
Program syntax refers to the rules of a programming language that defines and control
the structure of symbols, punctuation marks and words according to which the
statements of a program are to be written. It is also called grammar of a programming
language.
For example: output in C Language can be presented by using printf ( ) function,
Its syntax can be:
printf (“string message to be displayed” );
Program Semantic
Program semantic describes the meaning of the statement of a programming language.
Program semantic also describes the sequence of steps to be performed by the computer
when executing the statements of a program. For example
int product = x * y;
Above is the statement written in C program that multiply two variable “x” and “y” and
then store its result in third variable “product” of data-type integer.
ii. Differentiate between high level and low level languages?
Low Level Language High Level Language
Instructions are written in binary form or
1 Instructions are written in English language
mnemonics (for Assembly Language)

Low level language can directly access computer High level languages cannot directly access the computer hardware
2
hardware and comprised of mnemonics. and it is comprised of functions, modules, classes and GUI etc.

3 Low level languages are machine dependent. High level languages are cross platform.

Expert hardware knowledge are required to Expert arithmetic and logical skills are required to program in high
4
program in low level languages. level languages.
Examples: Machine Language and Assembly
5 Examples: C, C++, Java, C#, Python and JavaScript etc.
Language etc.

9
iii. What is IDE?
IDE (Integrated Development Environment)
IDE stands for Integrated Development Environment, it is a programming language
development tool used to create, compile, debug and run the computer program. IDE is a
computer software that include editor, compiler, linker, loader, debugger, library
functions and processes to develop a computer program in one environment. Modern
IDE have GUI based user friendly interface.
For example; Turbo C, C-Free, Visual studio are the IDE’s used for C Languages.

iv. What is OOP?


OOP (Object Oriented Programming)
OOP stands for Object Oriented Programming. In object oriented programming the
program is developed by using a set of objects and classes. An object is a component of
program that has a set of modules (functions) and data while classes are the abstract data
type or template for the objects, objects are also an instance of the class. OOP provides
clean code structure and makes it possible to create full reusable applications with less
code and shorter development time.
C++, Java and C# are the examples of OOP Languages.
v. What are the characteristics of High Level Language?
Characteristics of High Level Languages
Following are the main characteristics of high level languages;
1. High level languages are easier to learn and understand because the statements written for a
program are similar to English language.
2. High level language provides Rapid Access Development (RAD), new programs can
easily be written in very short time.
3. The errors in a program can easily be detected and removed during compilation of a
program.
4. High level language provides a large number of built-in functions or procedure.

vi. Differentiate between Compiler and Interpreter?


Compiler
A Compiler is a system software which is used to translate the high level programming
language code into low level language code at once and if there is any error in the
program then it generates a list of errors.

10
In C language if a program is successfully compiled (translated) then compiler
generates its object file with an extension of .obj that contains the machine or
intermediate code and an executable (.exe) file that is linked with the object file and
next time run the program directly from the executable file.
Languages like C, C++ and Java etc. uses compiler.
Interpreter
An Interpreter is also a system software and high level language translator which is
used to translate the high level programming language code into low level language
code statement by statement (line by line) and if there is any error occurs it stops the
translation and display the error in that line. It doesn’t generate any object and
executable file. Interpreter translates the code every time when program runs.
Languages like Basic, JavaScript and Python etc. uses interpreter.

vii. What is header file?


Header files are collection of standard library functions to perform different task. Header
file contains different types of predefined functions and many header files can be
included in one program.
General Syntax for including the header file
#include <headerfile.h>.
The extension of a header file is .h. The “#include” preprocessor directive is used to
include header file in program.
For example:
#include <stdio.h>
“stdio.h” header file contains declarations of standard input and output functions
available in C which is used to get the input and print the output.

11
viii. Differentiate between source program and object program?
Source Program Object Program

A collection of computer instructions A sequence of statements ibn binary that


written using a human readable is generated after compiling the source
programming language. program.

Source Program contains English oriented


words according to the syntax of the Object program Contains binary ( 0 or 1)
programming language.

Source code is another name for source Object code is another name for object
program. program.

Programmer can read the source program. Machine can read the object program.

Programmer creates the source program. Compiler creates the object program.

The object program is saved after


In C-language is source program is saved
compilation with extension “.obj” i.e.
with extension “*.C” i.e. “computer10.c”
[Link]

ix. What are reserved words?


The words that are used or reserved by the language for special purpose are called
reserved words or keywords. Each keywords has fixed meaning and that cannot be
changed by user. Every keywords exists in lower case letter like auto, break, case,
double, continue and int etc. C Language supports 32 keywords.

x. Write rules for variable names?


Following are the rules for writing variable name;
1. Variable names begin with letter, although some systems permit underscore as the
first character.
2. The length of a variable name depends upon the compiler of C.
3. Blank space is not allowed.
4. A variable should not be keyword.
5. It should not contain special character like, #, ^ etc.
6. A variable name declared for one data-type cannot be used for a different data-type.

12
xi. What is purpose of const qualifier?
Const qualifier – const (constant)
The const qualifier is used to define a constant. The constant must be initialized by
specifying its name, data type and some values. The initialized value cannot be changed
during program execution.
The General Syntax of declaring constant with const qualifier is as follow:
Const data type identifier = value;
Where
Const: is a keyword used to define a constant.
Data type: indicate the data type of the constant.
Identifier: represent the name of the constant.
Value: represent the value with which the constant is initialized.
Example:
const int N = 100;
const float R = 3.5;
The same can be achieved using #define preprocessor as:
#define N 100
#define R 3.5

Q3. What is programming language? Explain different types of low level


language?
Programming Language
A programming language is a computer language used by programmers to develop
software programs. It contains set of words, symbols and codes as an instructions. These
languages are used to solve business problems, scientific problems.
Programming languages can be classified into two types;
1. Low level languages
2. High level languages

Low level languages


Low-level languages are designed to operate, manage and manipulate the computing
hardware and components. Computer can understand these languages easily. Writing a

13
program in low level language requires a deep knowledge of the internal structure of
computer hardware.
There are two types of low-level language.
i. Machine language
ii. Assembly Language

i. Machine language
A type of programming language in which instructions are written in binary form
is called machine language. Program written in machine language can be
executed rapidly by the computer. Machine language is represented inside the
computer by string of binary digits (bits) 0 and 1. The symbols 0 stand for the
absence of an electric and the 1 stands for the presence of an electric pulse.
Machine language is also known as first generation language.
ii. Assembly language
Assembly language is a low level language. It is one step higher than machine
language, symbols are used instead of binary code. These symbols are called
mnemonics. For example, sub instruction is used to subtract two numbers.
It is also called symbolic language. The instruction of the assembly language are
converted to machine code by a language translator called assembler and then
they are executed by the computer. Assembly language is also known as second
generation language.

Q4. What is high level language? Explain any five types of high level
languages?
A high-level language generally independent of the computer`s hardware architecture
and enables the development of a computer programs in more user-friendly
programming context.

Following are the five types of high-level programming language ;

i. C Language
C is a general-purpose computer programming language developed in 1972 by
Dennis Richie at AT&T Bell Laboratories USA. C is a simple and structure oriented
procedural programming language. It is highly portable among platforms and

14
therefore widely used in industry and among computer professionals. The operating
system UNIX was written in C.
ii. C++ Language
C++ is an extension of C language. It is an Object-Oriented Programming (OOP)
language. C++ includes all the elements of the C language and it has additional
features for working with objects, classes, events and other object-oriented
concepts. Most of the application program, such as word processers and
spreadsheets are developed in C++.
iii. Visual Programming Languages
The term visual programming refers to creating or developing Window-based
application or Graphical User Interface (GUI) applications. The visual programming
language are also called fifth-generation language based on object-oriented
programming. Some popular and widely used visual programming languages are
Visual Basic (VB) and Visual C++, C#, AND java.
iv. C# language
C# or C-sharp is an object-oriented programming language. It was developed in
2000 by Microsoft Corporation. It is based on C++ with elements from Visual Basic
and Java. It is used to write web applications that can be used across the Internet.
ALL types of programming including games, utilities, operating systems, compilers,
business applications and web based application can be developed in C#.
v. JAVA Language
Java is a high-level object oriented-programming language developed by Sun
Microsystems in 1991. It is very similar to C++ but it is especially used for web
page designing. APPLETS are Java program that are embedded into web pages to
rotate images, for animation and to access database on the internet.

Q5. What is the basic structure of C-program? Also explain different


types of preprocessor directives?
Basic structure of C Program
C program consist of following three main parts.
i. Preprocessor Directives
ii. The main () functions
iii. Body of main { }

15
i. Preprocessor directives
The instructions that are given to the compiler before the start of the actual
program are called Preprocessor directives. These are also known as Compiler
directives. These preprocessor directives normally start with hash sign # and the
keyword include or define, e.g., #include, #define, etc.
The #include directives allows external header file to be processed by the
compiler. For example #include<studio.h>
ii. The main( ) function
The main function must be present in every C program. it is the Point where C
program starts execution. If main function is not included in the program then
compiler gives error message.
The word main is followed in the by a pair of parenthesis ( ).
The Syntax of the main ( ) function is:
void main ( )
{
Program statements;
}
iii. Body of main function
After parenthesis of main function, the body of main function starts with an
opening curly “{” braces and ends with a closing curly brace “}”. When main
function is executed, the instructions written in it perform their task. . Inside the
body of main function, C programming statement are written to perform a specific
tasks.

Q6. Explain different data types used in C – language with example?


Data Types used in C Language
All C compilers accept the following fundamental data types to be assigned to
variable.
i. Integer ( int )
ii. Floating Point ( float ) and Double precision floating point (double)
iii. Character ( char )

16
i. Integer (int, long ) Type
Integer are whole number with a machine dependent range of values. C has 3 classes
of integer storage namely short, int and long variable. General Syntax for declaring
int variable
int variable_name ;
Generally, the number of bytes set aside by the compiler for the above Datatype are as
given in the table.

Variable Declaration No. of Bytes Range

-32,768 to +32,767
int 2
-2,147,483,648 + 2,147,483,647
long 4
0 to 65,535
Unsigned int 2

ii. Floating Point (float, double, long double) Types


Floating point number represents a real number with 7 digits precision. Floating
point numbers are denoted by the keywords float. When the accuracy of the floating
point number is insufficient, we can use the double and long double to define the
number.
Float variable declaration statement has the form:
float variable;
Variable Declaration No, of Bytes Range

Float 4 3.4 x10-38 to 3.4 x 1038

Double 8 1.7 x 10-308 to 1.7x 10308

Long double 10 3.4 x 10-4932 to 1.1x104932

iii. Character (char) Type


A character variable can only store one character. An example of declaration of
character variables is Char variable_name. The C compiler set aside one byte of
memory for storing a character in character variable.

17
Q7. What are constants and variables? Differentiate them with example?
Variables
Variable are the containers for storing data values. It
represents a storage or memory location in the
computer memory. The data stored in variables is
temporary which can be used or processed only during
the execution of the program. The data stored in
variables automatically removed when program ends.
In C language a variable can be numeric or character.

Constant
A constant is a quantity that cannot be changed during program execution. A
literal constant is a value that is typed directly in program. It appears in the program
wherever it is needed. For example, the following statement contains string constant:
“Pakistan Zinda Bad”
used as a label in printf function
printf(“Pakistan Zinda Bad”);
Similarly, in the following statement.
int age = 19;
Age is an integer variable and 19 is a literal constant.

Q8. How variables are declared and initialized in C-language? Give


examples?
Declaration of Variables
Assigning the name and data type that a variable can hold is called declaration of the
variable. General syntax to declare a variable in C – Language is;
DataType List_of_variable_names;
Where,
Data Type specifies data type of variable. For example, int, float, etc.
List of variables names specifies a list of variables separated by commas.
For example, to declare variable “pi” of float data type. The statements is written as:
float pi; (pi variable name of float datatype)
char gender; (gender variable of character datatype)

18
Declaration of Variables
Assigning a known value to variable at the time of its declaration is called initialization of
the variable. General Syntax for initialization of a variable is
DataType variable_Name = value;

Q9. What is type casting?


Type casting
The process of converting one data type into another data type during execution is known
as type casting. Type casting perform in two ways
i. Implicit type casting
ii. Explicit type casting

i. Implicit type casting


Implicit type casting is performed automatically by the C
compiler. The operand in arithmetic operation must be of long double
similar types. If the data type of operand is different, the
value with lower data type is converted into higher data type.
double
For example,

int x = 2; float
float y = 3, z;
z = x + y;
Unsiged long int

x is lower data type but float is higher datatype their sum is


also stored into higher data type. long int

ii. Explicit type casting


Explicit casting is performed by programmer. It is performed unsigned int
by using Cast operator. The cast operator tells the computer
to convert the data type of a value. int
Syntax of using cast operator is:
(type) expression;
Type: it shows the data type to which operand is to be char, short int
converted.
Expression: it shows the constant, variable or expression
whose data type is to be converted
For example; for calculating percentage of marks;
int marks = 432;
float percentage = (float) marks * 100 / 550;

19
UNIT 3

INPUT AND OUTPUT HANDLING


Q2. Give short answers to the following questions.

i. What is the use of format specifiers? Give examples.


The Format specifier is a string which is used to tell the compiler what type of the
data is in a variable both on input or output functions. it is always represented by "%"
in C language.
A list of commonly used format specifiers is given as follows
Format specifier Purpose
Signed integer
% d or % i
Long integer
% ld
Floating point (decimal notation)
%f
Floating point(exponential notation)
%g
Floating point(exponential notation)
%e
Single character
%c
String
%s

ii. Why escape sequence are used? Give example.


An escape sequence in C language is a sequence of characters used to control printing
on the output devices. These are the combination of characters written in double
quotes beginning with a back slash \ followed by letters or special symbol. Escape
sequences are used to format the output and can be used inside string constants or
independently for example;
“\n” used for new line and “\t” use for horizontal tab (space).

iii. What is the purpose of gets ( ) functions?


The gets functions is used for the input operations to read the entire string until user
presses the Enter key.
General Syntax:
gets(Array_Name);

20
iv. Differentiate between getch ( ) and getche ( ) functions?
getch ( ) Function:
The getch ( ) is used to read a single character from the keyboard without
displaying it on the screen.
General Syntax:
ch = getch ( );

getche ( ) Function:
The getche ( ) is used to read a single character from the keyboard with echo
i.e. echoing (displaying) it on the screen.
General Syntax:
ch = getche( );

v. Evaluate the following expressions.


a) 9-5*(6+2)
Solution:
= 9-5*8
= 9-40
= 31

b) 60/10*24+3
Solution:
= 6*24+8
= 144+8
= 152
c) 100%50-100%3
Solution:
= 0 - 100%3
=0-1
= -1

vi. Differentiate between simple and compound assignment operators.


Simple Assignment Operator
The assignment operator (=) is used to assign numeric or character values to a
variable, The general syntax of assigning the value to a variable using assignment
operator are follows:
Variable = Character / constant / variable / Expression
For example:
int rollNo = 103;
char gender = ‘M’;

21
Compound Assignment Operator
C language provides a compound assignment operator that combine assignment
operator with arithmetic operators which are used to perform mathematical operations
more easily. The general syntax of compound operators are follows:
DataType Variable = expression;
For example:
a +=10 – is equivalent to a = a + 10;
a –=10 – is equivalent to a = a – 10;
a *=10 – is equivalent to a = a * 10;

Q3. What are operators? Explain different type of operators with examples?
Operators
Operators are the symbols that are used to perform certain operations on the data. C
language provides following types of operators;
a. Arithmetic Operators
b. Assignment Operators
c. Relational Operators
d. Logical Operators

a. Arithmetic Operators
Arithmetic operator is a symbol that performs mathematical operation on numeric
data. C language provides many arithmetic operators. The following are the list of
arithmetic operators used in C.
Operation Symbol Description
Addition + Add two values
Subtraction - Subtracts one value from another value
Multiplication * Multiplies two values.
Division / Divides one values by another value
Modulus % Gives remainder of division of two integers.

b. Assignment Operator
The assignment operator = is used to assign values to variables. It is used to assign
a numeric or character value to a variable. It has following General Syntax:
variable = Character_constant / variable / Expression;
For example;
int rollNo = 103;
char gender = ‘M’;
area = 3.14 * r * r ;

22
c. Relational Operator
The relational operator are used to specify conditions in a program. A relational
operators compares two values or a conditions and produces the result as true or
false. The relational operator are also called conditional or comparison operators.
C / C++ provides following relational operators:
Operator Description Example
> Greater than a>b
operator (return true if a is greater than b, otherwise
return false)
< Less than a<b
operator (return true if a is less than b, otherwise
return false)
== Equal to a == b
operator (return true if a and b are equal, otherwise
return false)
>= Greater than or a >= b
equal to (return true if a is greater than or equal to
operator b, otherwise return false)
<= Less than or a<=b
equal to (return true if a is less than or equal to b,
operator otherwise return false)
!= Not equal to a != b
operator (return true if a is not equal to b, otherwise
return false)

d. Logical Operator
The logical operators are used to evaluate compound conditions. There are three
logical operator in C Language.

Logical Description Example


Operator
AND && Logically AND operator, A = 12 and B = 14
produces result true if both (A>10) && (B > 10)
conditions are true Result true
otherwise false.
OR | | Logically OR operator, A = 100 and B = 50
produces result true if (A>50) | | (B > 50)
either of the condition is Result true
true otherwise false.
NOT ! Logically NOT operator is If (A==B) is true
used to reverse the result of Then !(A==B) is false.
a condition i.e. true to false
and false to true.

23
Q4. What is output function? Describe in detail different type of output functions?
Output function
Functions that are used to receive the data from the computer memory and then display it
to the output devices is called output functions.
C – Language offers the following output functions
 printf ( )
 puts ( )
 cout
a. printf ( ) function
printf ( ) is the most commonly used output function in C language. It is used to
display the data (i.e. messages, value of a variable or result of an expression) on the
output screen. It has the following general syntax
printf ([“escape sequence / format specifier”], “variable / Expression / String”);
(Note: escape sequence or format specifier is optional)
Example:
printf(“I Love Pakistan”);
printf(“%d”, a);
b. puts ( ) Function
puts ( ) function is used to display the string on the screen. It has the following general
syntax
puts (“string”);
Example:
puts (“Hello world!”);
c. cout
cout is generally used in C++ for obtaining the output on the screen. cout is basically
an object that can used by insertion operator <<. It has the following general syntax
cout<< Variable or constant or expression or string of character.
Example: cout<< “Hello this is my first program”;

Q5. Discus different format specifiers and escape sequences used in printf ( ) function?
Format Specifier used in printf ( )
The Format specifier in printf ( ) function is a string that is used according to the format
of output values. The format string always starts with a '%' character.
A list of commonly used format specifiers is given as follows
Format specifier Purpose
Signed integer
% d or % i
Long integer
% ld
Floating point (decimal notation)
%f
Floating point(exponential notation)
%e
Single character
%c
String
%s

24
Escape sequences used in printf ( )
An escape sequence are special non printed characters used to control the printing on
output devices. These are the combination of characters begin with back slash \ and
followed by a letter or special symbol. It can be used anywhere in the function to format
the output.

Escape
Purpose Example Output
Sequences
Used to move the Hello
\n printf(“Hello\nWorld”);
control to the New line World
\t Horizontal tab printf(“Hello\tWorld”); Hello World
Produce Bell or Beep Produce a beep
\a printf(“\a”);
sound sound
Backspace (used to
\b move cursor one space printf(“Foodo\bWorld”); FoodWorld
back after printing)

Q6. Explain different type of input functions with examples.


C programming language provides built-in functions to perform input operations. The
input operations are used to read user values (input) from the keyboard and assign those
values to a variable. The c programming language provides the following built-in input
functions.
 scanf ( )
 getch ( )
 getche ( )
 getchar ( )
 gets ( )
 cin

i. scanf ( )
The scanf ( ) function is used to read multiple data values of different data types from
the keyboard. The scanf () function is built-in function defined in a header file called
"stdio.h". It has following general syntax
scanf (“format specifier”,&var1,&var2,…...);
Example:
scanf (“%d”,&a);
ii. getch ( )
The getch ( ) function is used to read single character from the keyboard without
displaying it on screen (no echo). It has following general syntax
variable = getch ( );
Example:
char gender = getch ( );

25
iii. getche ( )
The getche ( ) function is used to read single character from the keyboard with
displaying it on screen (echo). It has following general syntax
variable = getche ( );
Example:
char gender = getche ( );
iv. getchar ( )
The getchar ( ) function requires pressing Enter key after entering the character. It has
following general syntax
variable = getchar ( );
Example:
char gender = getchar ( );
v. gets ( )
The gets ( ) function reads the entire string until user presses Enter key. It has
following general syntax
gets (array);
Example:
gets (name);
vi. cin
In C++ Programming language the input can be obtained at runtime from the
keyboard using cin. cin is an input stream and always used with extraction operator
>> and defined in a header file called "iostream.h". It pauses the program until user
enter the value from the keyboard and press Enter. The cin can accept both numeric
and character values It has following general syntax
cin>>variable1>>variable2>>variable3>>…..>>variableN;
Example:
cin>>a>>b; (where a and b is an integer type variable)

26
Q7. Write a program that reads three numbers and print their sum, product and
average.

#include <stdio.h> Output


#include <conio.h>
void main()
{
int num1, num2, num3, sum, product,
average;
printf("Enter First Number = ");
scanf("%d",&num1);
printf("Enter Second Number = ");
scanf("%d",&num2);
printf("Enter Third Number = ");
scanf("%d",&num3);
//Sum...
sum=num1+num2+num3;
printf("Sum = %d", sum);
product=num1*num2*num3;
printf("\nProduct = %d \n", product);
average=sum/3;
printf("Average = %d \n",average);
}

Q8. Write a program that reads the base and height of a triangle and prints its area.

#include <stdio.h> Output


#include <conio.h>
void main()
{
int base,height,area;
printf("Enter Value of Base = ");
scanf("%d",&base);
printf("Enter Value of Height = ");
scanf("%d",&height);
area=base*height/2;
printf("Area = %d \n",area);
}

27
Q9. Write a program that reads temperature in Celsius, converts it into Fahrenheit and
prints it on screen.

#include <stdio.h> Output


#include <conio.h>
void main()
{
int celsius,fahrenheit;
printf("Enter Celsius Value = ");
scanf("%d",&celsius);
fahrenheit = celsius * 9/5 + 32;
printf("Fahrenheit = %d \n",fahrenheit);
}

Q10. Write a program that reads name and address of a student and prints it on the
screen using gets( ) and puts( ) functions.

#include <stdio.h> Output


#include <conio.h>
void main()
{
char name[50];
char address[50];
printf("Enter Name of student = ");
gets(name);
printf("Enter Address of student = ");
gets(address);

printf("Name = ");
puts(name);

printf("Address = ");
puts(address);
}

28
UNIT 4

CONTROL STRUCTURE

Q2. Write a program in C to input three integers. Find out the largest
among these integers using if-else structure and print it on the screen.

#include<stdio.h> Output
#include<conio.h>
void main()
{
int num1,num2,num3;
printf("Enter First Number = ");
scanf("%d",&num1);
printf("Enter Second Number = ");
scanf("%d",&num2);
printf("Enter Third Number = ");
scanf("%d",&num3);
if(num1>num2)
{
printf("largest Number = %d \n", num1);
}
else
if(num2>num3)
{
printf("largest Number = %d \n", num2);
}
else
{
printf("largest Number = %d \n", num3);
}
}

29
[Link] a program in C to input a single character and print a message
“It is a vowel” or “It is a consonant”. Use if-else structure.

#include<stdio.h> Output
#include<conio.h>
void main()
{
char character;
printf("Enter Character = ");
scanf("%c",&character);
if(character == 'a' || 'A')
{
printf("It is a vowel\n");
}
else
if(character == 'e'|| 'E')
{
printf("It is a vowel\n");
}
else
if(character == 'i'|| 'I')
{
printf("It is a vowel\n");
}
else
if(character == 'o'|| 'O')
{
printf("It is a vowel\n");
}
else
if(character == 'u'|| 'U')
{
printf("It is a vowel\n");
}
}

30
[Link] the program in Q3 using switch-case structure.

#include<stdio.h> Output
#include<conio.h>
void main()
{
char character;
printf("Enter Character = ");
scanf("%c",&character);
switch(character)
{
case 'a':
printf("It is a vowel\n");
break;
case 'e':
printf("It is a vowel\n");
break;
case 'i':
printf("It is a vowel\n");
break;
case 'o':
printf("It is a vowel\n");
break;
case 'u':
printf("It is a vowel\n");
break;
}
}

Q5. Write the output of the following program.


#include<stdio.h> Output
#include<conio.h>
void main()
{
int a,b,c;
a=b=10;
c=13;
if((a==b)&&(a>c))
{
printf("Condition is true \n");
}
else
{
printf("a is equal to b \n");
printf("a is not greater than c \n");
}
}

31
[Link] out error if any in the following program.

#include<stdio.h> Error
#include<conio.h>
int main()
{ Condition is required after second if
int a; statement.
printf("Enter any number = ");
scanf("%f",&a);
if(a>10)
printf("value is greater than 10");
else
if
printf("value is less than 10");
}

32
UNIT 5

LOOP STRUCTURE
Q2. Explain the different type of looping structures with examples?

Looping Structure
A type of control structure that repeats a statement or set of statements until stated condition
becomes false is called a looping structure.
There are three types of loops available in C Language i.e.
1. for loop
2. While loop
3. Do-while loop

1. The For loop


The for loop executes one or more statements for a specified number of times. Its general
syntax is
for (initialization; condition; increment/decrement)
{
Body of the loop;
}
Where;
Initialization: it is a statement that specifies the starting value or index of a counter
variable
Condition: it is a relational expression, the statements within the body of the loop only
executed if this expression is true otherwise the loop breaks down.
Increment / Decrement: it will increase or decrease the value of the counter variable
after each iteration.
Body of the Loop: it is a statement or set of statements that to be repeated.
For Example:
for(int i=0; i<=10; i++)
{
printf(“%d”, i);
}
2. The while loop
The while loop executes one or more statements until the given conditions remains true. It
is useful when the number of repetitions or iterations are not known in advance.
It has following syntax:

33
while (condition)
{
Body of the loop;
}

For Example
While ( i<=10)
{
printf(“%d”,i);
i++;
}

3. The Do-while loop


The do-while executes the statement or set of statements until the given condition is true.
In this loop the condition comes after the body of loop, so the body must be executed at
least once even the given condition is false for the first time. It has following general
syntax;

do
{
Body of the loop;
}
while(condition);

For Example
do
{
printf (“%d”,i);
i++;
} while ( i<=10);

Q3. Differentiate between do-while and while loops. Explain with Program
examples?

1. The while loop


The while loop executes one or more statements until the given conditions remains true. It
is useful when the number of repetitions or iterations are not known in advance.
It has following syntax:

34
while (condition)
{
Body of the loop;
}

Example: A program to display “Pakistan” for the five times using the while loop.
#include<stdio.h>
#include<conio.h>
void main( )
{
int n;
clrscr( );
n = 1;
while ( n <= 5)
{
printf (“Pakistan\n”);
n++;
}
getch( );
}

2. The Do-while loop


The do-while executes the statement or set of statements until the given condition is true.
In this loop the condition comes after the body of loop, so the body must be executed at
least once even the given condition is false for the first time. It has following general
syntax;

do
{
Body of the loop;
}
while(condition);

Example: A program to display “Pakistan” for the five times using the do – while
loop.
#include<stdio.h>
#include<conio.h>
void main( )
{
int n;

35
clrscr( );
n = 1;
do{
printf (“Pakistan\n”);
n++;
}
while ( n <= 5);
getch( );
}

Q4. Differentiate between do-while and while loops. Explain with Program
examples?

#include<stdio.h> Output
void main()
{
double i=2, product=1;
while(i<=100)
{
product = product * i;
i+=2;
}
printf("Product of even numbers from 1
to 100 = %ld\n", product);
}

Q5. Write a program to display alphabets from A to Z using for loop?

#include<stdio.h> Output
void main()
{
int ch;
for(ch='A'; ch <= 'Z'; ++ch)
{
printf("%c\t",ch);
}
printf("\n");
}

36
Q6. Write a program to display the following output using nested for loop.

a a

a a a

a a a a

a a a a a

#include<stdio.h> Output
void main( )
{
int i,j;
for(i=1;i<=5;i++)
{
for(j= 1;j<=i;j++)
{
printf("a\t");
}
printf("\n");
}
}

Q7. Write a program in C to print the sum of odd numbers from 1 to 50


using the for loop.

#include<stdio.h> Output
void main()
{
int i = 1, sum=0;
for(i=1;i<=50;i++)
{
if(i%2 != 0)
{
sum = sum + i;
}
}
printf("Sum of odd numbers from 1 to 50
= %d\n",sum);
}

37
38
39
40
41
42

You might also like