Notes - Computer Science II
Notes - Computer Science II
Lectures / Notes
I
Part I – C Language
II
Chapter # 1
Concepts of Computer Programming
Programming Languages
Programming languages are used to create programs that implement specific algorithms.
Thousands of different programming languages have been created, mainly in the computer
field, and many more still are being created every year.
Each programming language has its own vocabulary and structural rules.
Programmers use these languages to construct programs containing lists of instructions for the
computer to perform specific task.
Most Popular languages are:
BASIC
Java
Visual Basic
C++
C# (pronounced C-sharp)
PHP
SQL
JavaScript
Computers only understand programs in their own machine language. Machine language is
the language of 0‘s and 1‘s.
It is difficult to write program in machine language so what is the solution to this dilemma?
The answer is in what are called high-level languages i.e. Computer programming languages
that look like natural language.
All programs written in high level language must be translated before their instructions
execution.
Computer languages can be grouped according to which translation process is used to convert
the instructions into binary code:
• Assemblers
• Interpreters
• Compilers
Page | 1
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Generations Of Programming Languages
• First Generation - Machine Language (code)
o Machine language programs were made up of instructions written in binary
code.
o This is the ―native‖ language of the computer.
• Second Generation - Assembly Language
o Assembly language programs are made up of instructions written in
mnemonics.
• Third Generation - People-Oriented Programming Languages
o High-level languages: Use statements that resemble English phrases combined
with mathematical terms needed to express the problem or task being
programmed.
• Fourth Generation - Non-Procedural Languages
o Programming-like systems aimed at simplifying the programmer‘s task of
imparting instructions to a computer.
o Many are associated with specific application packages.
Query Languages:
Report Writers:
Application Generators:
• Fifth Generation - Natural Languages
o Object-Oriented Languages: A language that expresses a computer problem
as a series of objects a system contains, the behaviors of those objects, and how
the objects interact with each other.
Page | 2
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Flow Chart
A flow chart, or flow diagram, is a graphical representation of a program that details the
sequencing of steps required to create output.
A typical flow chart uses a set of basic symbols to represent various functions, and shows the
sequence and interconnection of functions with lines and arrows.
Flowcharts are used in analyzing & designing a program.
Flowchart Symbols
Flowcharts use special shapes to represent different types of actions or steps in a program.
Lines and arrows show the sequence of the steps, and the relationships among them.
Commonly used symbols are:
Algorithm
Page | 3
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Example: Write an algorithm and draw a flow chart to calculate the factorial of a number (N).
Verify your result by a trace table by assuming N = 5.
Algorithm:
Step 1: Input N
Step 2: Factor = 1
Step 3: Counter = 1
Flow chart
Page | 4
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
High Level Languages:
Higher level languages make use of English like words and statements and mathematical
symbols for instructions.
Higher level languages make programming easier, since they are relatively easy to learn.
Less time is required to write programs in high level languages.
The programmer is not required to know the detailed working of the computer system in order
to program in a high level language.
They are machine independent.
Higher level languages are also known as problem oriented languages.
However a high level language is not directly understood by the computer. It is required to be
translated into machine language. Therefore they generally execute more slowly and require
more memory than the same program written in assembly language.
The programs which are used to translate programs written in high level language into
machine language are known as translators.
The types of translators are:
I) Compiler
II) Interpreter
I) Compiler:
The compiler translates the entire source program into machine language program at once.
The source code remains intact.
Once a program is compiled it can be run as many times as required, without being required to
be recompiled.
A compiler is a program which normally resides on the secondary storage device. It gets
loaded into the CPU when the source program is to be translated.
A compiler checks for errors like illegal symbols, statements etc. during compilation and
gives out a list of error messages at the end of execution. This is a very valuable aid to the
programmer to correct the programs. However, the compiler is incapable of detecting any
logical errors in the program.
II) Interpreter:
The interpreter is the program which translates a high level language program into machine
language as follows :
Page | 5
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
- It takes one statement from the high level language program
Since the program is translated statement by statement, the machine level program of the
source program is not stored anywhere in memory. Therefore, the program has to be
interpreted every time when it has to be run. Thus no object code is generated.
The interpreted programs are generally slower than compiled programs. However, if any
changes are made in the source program it can interpret only those statements and it is not
required to compile the entire program again.
Interpreters are relatively easy to write and smaller in size as compared to compilers.
Thus assemblers, compilers and interpreters are systems software which translate the source
program into object program i.e. program which can be understood by the computer. These
translators are also known as language processors.
Page | 6
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Chapter # 2
Introduction to C Programming Language
Introduction to C
C is a programming language. The C language was developed by Dennis Ritchie in 1972 at AT&T
Bell Labs. It was called his newly developed language C simply because there was a B programming
language already and the B language led to the development of C Language. C language is based
on ALGOL and B languages.
Programming language is any language that computer system can understand directly or indirectly to
can perform the actions asked by the programmer as set of instructions in form of a computer
program. C language is a high-level programming language. In the computer world, the further a
programming language is from the computer architecture, the higher the language's level. You can
imagine that the lowest-level languages are machine languages that computers understand directly.
The high-level programming languages, on the other hand, are closer to our human languages. We
have to use some special programs, called compilers or interpreters, to translate such a program into a
machine-readable code. That is, the text format of all instructions written in a high-level language
has to be converted into the binary format. The code obtained after the translation is called object
code. Prior to the translation, a program in text format is called source code.
Page | 7
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
C History
• Developed by Dennis Ritchie at AT&T, early 70s,
• Developed between 1969 and 1973 along with Unix
• Designed for systems programming
o Operating systems
o Utility programs
o Compilers
o Filters
• Evolved from B, which evolved from BCPL
• Family of languages:
– BCPL, Martin Richards
– B (typeless), Ken Thompson, 1970
– C, Dennis Ritchie, Bell Labs, early 70s
– C++, Bjarne Stroustrup, Bell Labs, 80s
– Java, James Gosling Sun, 1995
– C#, Microsoft, recently
C vs. C++
C is a powerful system programming language, and C++ is an excellent general purpose
programming language
C++ is a superset of C
C++ has all the characteristics of C
Reasons to learn C
• Main reason is its simplicity reliability, and it‘s easy to use and easy to learn
Page | 8
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Features of C
• Structured language
– It has the ability to divide and hide all the information and instruction.
– Code can be partitioned in C using functions or code block.
• General purpose language
– Make it ideal language for system programming.
– It can also be used for business and scientific application.
– The ability of c is to manipulate bits, byte and addresses.
• Portability
– Portability is the ability to port or use the software written .
– One computer C program can be reused.
– By modification or no modification.
• Code Re-usability & Ability to customize and extend
– A programmer can easily create his own function
– It can be used repeatedly in different application
– C program basically collection of function
– The function are supported by 'c' library
– Function can be added to 'c' library continuously
• Limited Number of Key Word
– There are only 32 keywords in 'C'
– 27 keywords are given by ritchie
– 5 is added by ANSI
– The strength of 'C' is lies in its in-built function
– Unix system provides as large number of C function
– Some function are used in operation .
– Other are for specialized in their application
• Powerful
– Completeness – business to scientific applications
– Flexibility – preprocessor, conditional compilation, header files
• Both a high level and low level language
– High level – symbolic references, user written functions, powerful operator set,
derived data types
– Low level – allow reference to storage directly, bits and bit patterns manipulation
Page | 9
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Basic C Program Structure
1. Comments
2. Compiler directives and include files
3. Declarations of global variables and constants
4. Declaration of functions
5. Main function
6. Sub-functions
7. Interrupt service routines
Example: First C Program
Output
How are you!
Every set of C programs should have one main ( ) function. This is called the driving function. The
program execution starts at ‗{ ‗, the opening brace of the main function body and ends at the ‗ } ‗
closing brace. Every statement in C ends with a ‗ ; ‗ ( semicolon ).
Page | 10
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Directives
#include <stdio.h>
#include<stdio.h>
• Since we are using a function printf(); in our program in order to print a sentence, so it is
necessary to give reference of this function.
• The functionality of printf(); function is defined somewhere in one of many C Standard
Libraries, the name of that library is stdio.h.
• Hence including stdio.h at the top of our program become reference for printf function. We
also call it prototype, or header file, since it is at the head of our program.
• stdio.h, which stands for "standard input/output header", is the header in the C standard library
that contains macro definitions, constants, and declarations of functions and types used for
various standard input and output operations.
Header files
• The files that are specified in the include section is called as header file
• These are precompiled files that has some functions defined in them
Page | 11
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
• We can call those functions in our program by supplying parameters
• Header file is given an extension .h
• C Source file is given an extension .c
void main(void)
Main function
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
printf(―How are you!‖);
getch();
}
Explanation:
―getch();‖.
Page | 12
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
This function holds the output‖How are you‖ on the output window, till user presses any key.
Getch stands for get character.
Getch() fucntion is the member of conio.h library, hence we include this library at the top of
our program.
clrscr()
• Clrscr(); is a fucntion used to clear the previous output from output window.
Comments in C
Comments (remarks) may appear anywhere within a program, as long as they are placed
within the delimiters / * and */ (e.g., /* This is comment */).
• Such comments are helpful in identifying the program's principal features or in explaining the
underlying logic of various program features.
• Single line comment
– // (double slash)
– Termination of comment is by pressing enter key
• Multi line comment
/*….
…….*/
Some Definitions
• Integrated Development Environment (IDE):- It is a software package that makes it possible
to edit, compile, link, execute, and debug a program without leaving the environment. It is a
screen display with pull down menus. We use menu selections to invoke all the operations
necessary to develop our program.
• Syntax (form):-The syntax of a language describes the possible combinations of symbols that
form a correct program.
• Compiler:- It is the part of IDE, that translates our source file into machine language.
Page | 13
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
• Keyword:- Keywords are the words whose meaning has already been explained to the C
compiler
• Source Program: printable/Readable Program file
• Object Program: nonprintable machine readable file
• Executable Program: nonprintable executable code
• Syntax errors: reported by the compiler
• Execution/Run-time errors: reported by the operating system
• Coding: writing the instructions in a computer language.
• Debugging: detecting and correcting the errors in the programs
There are several such IDEs available in the market targeted towards different operating systems. For
example, Turbo C, Turbo C++ and Microsoft C are some of the popular compilers that work under
MS-DOS; Visual C++ and Borland C++ are the compilers that work under Windows.
Assuming that you are using a Turbo C or Turbo C++ compiler here are the steps that you need to
follow to compile and execute your first C program…
1. Start the compiler at C> prompt. The compiler (TC.EXE is usually present in C:\TC\BIN
directory).
2. Select New from the File menu.
3. Type the program.
4. Save the program using F2 under a proper name (say Program1.c).
5. Use Ctrl + F9 to compile and execute the program.
6. Use Alt + F5 to view the output.
Page | 14
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Chapter # 3
C Fundamentals
Character Set
A character denotes any alphabet, digit or special symbol used to represent information.
Following are the valid alphabets, numbers and special symbols allowed in C.
– Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
– Special symbols - ~ ‗ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' < > , . ? /
Page | 15
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Keywords
Keywords are the words whose meaning has already been explained to the C compiler. There
are only 32 keywords available in C. The keywords are also called ‗Reserved words‘.
do if static while
Data Types
C supports several different types of data, each of which may be represented differently within
Larger the value, larger is the space required in memory to store the number. If you are using
a variable whose value varies between 0 and 255 then there is no need to allocate more space
in memory for storing this number. The data types are created for efficient use of the memory.
How much memory is allotted for the various types depends on the machine.
C has 5 basic built-in data types.
Data type defines a set of values that a variable can store along with a set of operations that
Except type void, the basic data types may have various modifiers preceding them. A type
modifier alters the meaning of the base type to more precisely fit a specific need. The list of
modifiers is shown here:
Page | 16
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
– signed
– unsigned
– long
– short
The following Table shows all valid data type combinations supported by C, along with their
minimal ranges and typical bit widths..
When a type modifier is used by itself (that is, when it does not precede a basic type), then int
is assumed. Thus, the following sets of type specifiers are equivalent:
Specifier Same As
signed signed int
unsigned unsigned int
long long int
short short int
Although the int is implied, it is common practice today to specify the int anyway.
Page | 17
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Constants
Constant is an entity whose value does not change. All the numbers are constants.
There are four basic types of constants in C. They are integer constants, floating-point
constants, character constants and string constants
Integer and floating-point constants represent numbers. They are often referred to collectively
as numeric-type constants.
The following rules apply to all numeric-type constants.
2. The constant can be preceded by a minus (-) sign if desired. (Actually the minus sign is an
operator that changes the sign of a positive constant, though it can be thought of as a part of
the constant itself.)
3. The value of a constant cannot exceed specified minimum and maximum bounds. For each
type of constant, these bounds will vary from one C compiler to another.
Integer Constants
An integer constant is an integer-valued number. Thus it consists of a sequence of digits.
Integer constants can be written in three different number systems: decimal (base 10), octal
(base 8) and hexadecimal (base 16).
Beginning programmers rarely, however, use anything other than decimal integer constants.
A decimal integer constant can consist of any combination of digits taken from the set 0
through 9. If the constant contains two or more digits, the first digit must be something other
than 0
EXAMPLE: Several valid decimal integer constants are shown below.
The following decimal integer constants are written incorrectly for the reasons stated.
Page | 18
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Floating-Point Constants
A floating-point constant is a base- 10 number that contains either a decimal point or an
exponent (or both).
Example: Several valid floating-point constants are shown below.
0 1. 0.2 827.602
50000. 0.000743 12.3 31 5.0066
2E-8 0.006e-3 1.6667E+8 .12121212e12
The following are not valid floating-point constants for the reasons stated.
Character Constants
A character constant is a single character, enclosed in apostrophes (i.e., single quotation
marks).
Example: Several character constants are shown below.
Notice that the last constant consists of a blank space, enclosed in apostrophes.
Named Constants - Named constant will have a name like variable but the value of the named
constant would not change as
float PI=3.142;
Here you declare PI as floating type variable but you are not supposed to change the value of
PI.
However you may accidently change the value of PI. To avoid this you can use const key
word in the declaration as
Now the compiler itself would not allow you to change the value of PI and you can use PI into
any expression as;
c=2*PI*j;
Page | 19
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Symbolic or substitution constants - For using symbolic constant we have to use a
preprocessor directive called # define eg.
#define PI 3.142
When you compile the C program the preprocessor gets an instruction from the above
statement to substitute PI with 3.142. Wherever it finds PI written in the program thesame is
substituted by 3.142. PI is not a variable name. PI is not a variable it cannot be used as the
variable.
You can have only one character inside the quotation mark.
char ch;
ch='A ';
Character constants also represent the type int . The value then is the ASCII value of the
character. eg. ASCII value of A is 65, that of B is 66 etc. and thus A also means 65.
char ch;
ch='A ';
ch=ch+1;
printf(― %c‖,ch);
will print 'B '
Example: Several character constants and their corresponding values, as defined by the
ASCII character set, are shown below.
Constant Value
'A' 65
„x' 120
'3' 51
'?' 63
Page | 20
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
output:
Decimal value of a is 65
Character value of a is A
Variables
As a very basic concept, we can say that a variable is an entity whose value changes. We use a
lot of variables in Algebra. When we say
a=5;
• Most programs need to a way to store data temporarily during program execution; these
storage locations are called variables.
• All variables must be declared at top of program, before the first statement.
• The general form of a declaration is
type variable_list;
• Here, type must be a valid data type plus any modifiers, and variable_list may consist of one
or more identifier names separated by commas. Here are some declarations:
int i, j, l;
short int si;
unsigned int ui;
double balance, profit, loss;
Escape Sequences
Certain nonprinting characters, as well as the backslash (\) and the apostrophe (‗), can be
expressed in terms of escape sequences.
An escape sequence always begins with a backward slash and is followed by one or more
special characters. For example, a line feed (LF), which is referred to as a newline in C, can
be represented as \n.
The commonly used escape sequences are listed below.
Page | 21
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Code Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\" Double quote
\' Single quote
\\ Backslash
\v Vertical tab
\a Alert
\? Question mark
We have used '\n' character in printf. This is a non printable character and represents new line.
Thus when we write
printf (" Hello \n"); ( new line character to skip one line . )
printf(" Hi");
'Hello' is printed on first line and 'Hi' is printed on the next line.
String Constants
A string constant consists of any number of consecutive characters (including none), enclosed
in (double) quotation marks.
EXAMPLE: Several string constants are shown below.
"green" "Washington, D.C. 20005H " ―270-32-3456"
"$19.95" "THE CORRECT ANSWER is” “2* ( I+3)/J ―
Constants
Constant is an entity whose value does not change. All the numbers are constants. However we have
to have different types in constant as that of variables for efficient management of memory. Named
constant will have a name like variable but the value of the named constant would not change as
float PI=3.142;
Here you declare PI as floating type variable but you are not supposed to change the value of PI.
However you may accidently change the value of PI. To avoid this you can use const key word in the
declaration as
Now the compiler itself would not allow you to change the value of PI and you can use PI into any
expression as: c=2*PI*j;
Page | 22
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Declarations
A declaration associates a group of variables with a specific data type. All variables must be
declared before they can appear in executable statements.
A declaration consists of a data type, followed by one or more variable names, ending with a
semicolon.
Each array variable must be followed by a pair of square brackets, containing a positive
integer which specifies the size (i.e., the number of elements) of the array.
Example1: A C program contains the following type declarations.
int a, b, c;
Thus, a, b and c are declared to be integer variables, root1 and root2 are floating-point
variables, flag is a char-type variable and text is an 80-element, char-type array. Note the
square brackets enclosing the size specification for text.
Example2: A C program contains the following type declarations.
short int a, b, c;
long int r, s, t;
int p, q;
unsigned x, y;
int c = 12;
float sum = 0. ;
Page | 23
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Expressions
An expression represents a single data item, such as a number or a character.
The expression may consist of a single entity, such as a constant, a variable, an array element
or a reference to a function.
It may also consist of some combination of such entities, interconnected by one or more
operators.
The use of expressions involving operators is particularly common in C, as in most other
programming languages.
Expressions can also represent logical conditions that are either true or false. However, in C
the
Conditions true and false are represented by the integer values 1 and 0, respectively. Hence
logical-type
a+b
x=y
c=a+b
x <= y
x == Y
++i
Statements
A statement causes the computer to carry out some action.
There are three different classes of statements in C.
They are expression statements, compound statements and control statements.
An expression statement consists of an expression followed by a semicolon.
The execution of an expression statement causes the expression to be evaluated.
Example: Several expression statements are shown below.
a = 3;
Page | 24
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
c=a+b;
++i;
pi = 3.141593;
circumference = 2. * pi * radius;
Assignment
• A variable can be given a value by means of assignment:
height = 8;
• Before a variable can be assigned a value—or used in any other way—it must first be
declared.
• A constant assigned to a float variable usually contains a decimal point:
profit = 2150.48;
• It‘s best to append the letter f to a floating-point constant if it is assigned to a float variable:
profit = 2150.48f;
• An int variable is normally assigned a value of type int, and a float variable is normally
assigned a value of type float.
• Mixing types (such as assigning an int value to a float variable or assigning a float value to an
int variable) is possible but not always safe.
• Once a variable has been assigned a value, it can be used to help compute the value of another
variable:
Page | 25
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
height = 8;
length = 12;
width = 10;
Page | 26
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Chapters 4
Operators and Expressions
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C
language is rich in built-in operators and provides the following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
The data items that operators act upon are called operands. Some operators require two operands,
while others act upon only one operand. A few operators permit only single variables as operands.
Arithmetic Operators
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer division
The % operator is sometimes referred to as the modulus operator.
Example: Suppose that a and b are integer variables whose values are 10 and 3, respectively. Several
arithmetic expressions involving these variables are shown below, together with their resulting
values.
Expression Value
a+b 13
a-b 7
a*b 30
a/b 3
a%b 1
Page | 27
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Now suppose that vl and v2 are floating-point variables whose values are 12.5 and 2.0, respectively.
Several arithmetic expressions involving these variables are shown below, together with their
resulting values.
Expression Value
v1 + v2 14.5
vl - v2 10.5
vl * v2 25.0
vl / v2 6.25
Finally, suppose that c1 and c2 are character-type variables that represent the characters P and T,
respectively. Several arithmetic expressions that make use of these variables are shown below,
together with their resulting values.
Expression Value
c1 80
c l + c2 164
c l + c2 + 5 169
c l + c2 + ' 5 ' 217
Note that P is encoded as (decimal) 80, T is encoded as 84, and 5 is encoded as 53 in the ASCII
character set.
If one or both operands represent negative values, then the addition, subtraction, multiplication and
division operations will result in values whose signs are determined by the usual rules of algebra.
Integer division will result in truncation toward zero; i.e., the resultant will always be smaller in
magnitude than the true quotient.
The interpretation of the remainder operation is unclear when one of the operands is negative. Most
versions of C assign the sign of the first operand to the remainder. Thus, the condition
a = ( ( a / b) * b) + (a % b)
will always be satisfied, regardless of the signs of the values represented by a and b.
Example: Suppose that a and b are integer variables whose values are 11 and -3, respectively. Several
arithmetic expressions involving these variables are shown below, together with their resulting
values.
Page | 28
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Expression Value
a+b 8
a-b 14
a*b -33
a/b -3
a%b 2
Example: Let rl and r2 be floating-point variables whose assigned values are -0.66 and 4.50. Several
arithmetic expressions involving these variables are shown below, together with their resulting
values.
Expression Value
rl + r2 3.84
rl - r2 -5.16
rl * r2 -2.97
rl 1 r2 -0.1466667
Example: Suppose that i is an integer variable whose value is 7, f is a floating-point variable whose
value is 5.5, and c is a character-type variable that represents the character w. Several expressions
which include the use of these variables are shown below. Each expression involves operands of two
different types.
Page | 29
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Unary Operators
C includes a class of operators that act upon a single operand to produce a new value. Such operators
are known as unary operators. Unary operators usually precede their single operands, though some
unary operators are written after their operands.
Perhaps the most common unary operation is unary minus, where a numerical constant, variable or
expression is preceded by a minus sign.
Example: Here are several examples which illustrate the use of the unary minus operation.
-root1 -( x + Y) -3 * (x + y)
There are two other commonly used unary operators: The increment operator, ++, and the decrement
operator, --. The increment operator causes its operand to be increased by 1, whereas the decrement
operator causes its operand to be decreased by 1. The operand used with each of these operators must
be a single variable.
Example: Suppose that i is an integer variable that has been assigned a value of 5. The expression
++i, which is equivalent to writing i = i + 1, causes the value of i to be increased to 6. Similarly, the
expression --i, which is equivalent to i = i - 1, causes the (original) value of i to be decreased to 4.
The increment and decrement operators can each be utilized two different ways, depending on
whether the operator is written before or after the operand. If the operator precedes the operand (e.g.,
++i), then the operand will be altered in value before it is utilized for its intended purpose within the
program. If, however, the operator follows the operand (e.g., i++), then the value of the operand will
be altered after it is utilized.
Example: Suppose that x and y are integer variables whose values are 10 and 20, respectively. The
value of the expression -x + y will be -10 + 20 = 10. Note that the unary minus operation is carried
out before the addition. Now suppose that parentheses are introduced, so that the expression becomes
-(10 + 20). The value of this expression is -(10 + 20) = -30. Note that the addition now precedes the
unary minus operation.
Page | 30
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Assignment Operators
• An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
== Equal to 5 == 3 returns 0
i<j true 1
(1 + j) >= k true 1
(j + k) > (i + 5) false 0
k != 3 false 0
Page | 31
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Logical Operators:
The logical operators act upon operands that are themselves logical expressions. The net effect
is to combine the individual logical expressions into more complex conditions that are either
true or false. The result of a logical and operation will be true only if both operands are true,
whereas the result of a logical or operation will be true if either operand is true or if both
operands are true. In other words, the result of a logical or operation will be false only if both
operands are false.
Operator Meaning
&& and
|| or
! not
The hierarchy of operator precedence covering all of the operators discussed so far has become
extensive. These operator precedences are summarized below, from highest to lowest.
Page | 32
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Chapters 5
Input & Output
When we say Input, it means to feed some data into a program. An input can be given in the
form of a file or from the command line. C programming provides a set of built-in functions to
read the given input and feed it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C
programming provides a set of built-in functions to output the data on the computer screen as
well as to save it in text or binary files.
Types of I/O Statements
1. Formatted I/O
scanf()
printf()
2. Unformatted I/O
gets(), puts()
getch(),getche(),putch()
getchar(),putchar()
The functions used for input and output are stored in the header file stdio.h. If programmer
use any of the above function it is necessary to include header file.
1. Formatted Input & Output
(i) scanf() function
The function used to get input from the user during execution of program and stored in
a variable of specified form is called scanf() function.
Syntax: scanf(―format string‖,& variable name);
Types:
Single input e.g scanf(―%d‖,&a);
Multiple input scanf(―%d %c %d‖, &a,&op,&b);|
Example
#include<stdio.h>
#include<conio.h>
void main ()
{
int a;
clrscr();
printf("Enter integer value:");
Page | 33
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
scanf("%d",&a);
printf("The value you enter = %d",a);
getch();
}
Output Enter integer value:5 The value you enter =5
(ii) printf ()Function
This function is used to display text, constant or value of variable on screen in
specified format.
Types:
printf(―hello world‖); // Printf()with no argument list
printf(―the value of integar=%d‖,a); //Printf() with one argument
printf(―Sum of %d+%d=%d‖,a,b,a+b); //Printf()with more than one argument
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
printf(―HELLO WORLD!‖);
getch();
}
Output HELLO WORLD!
(vii) putchar()
The putchar function like getchar is a part of the standard C input/output library. It
transmits a single character to the standard output device (the computer screen).
Syntax
putchar(character variable)
where character variable refers to some previously declared character variable.
Program
#include <stdio.h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
Page | 36
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
putchar( c );
return 0;
}
Enter a value : this is test
You entered: t
Page | 37
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Chapters 6
Decision Statements
Decision Making
Decision making structures require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
The general form of a typical decision making structure found in most of the programming
languages is:
C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.
C programming language provides the following types of decision making statements.
Control Structure
A statement that is used to control the flow of execution in a program is called control
structure. It combines instruction into logical unit. Logical unit has one entry point and one
exit point.
Types of control structures
1. Sequence
2. Selection (branching)
3. Repetition (Iteration)
Page | 38
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Selection Statements
Selection structures allow the computer to make decisions in your programs. It selects a
statement or set of statements to execute on the basis of a condition.
Types:
1. if-else statement
2. switch statement
(i) If Statement
The simplest if structure involves a single executable statement.
Execution of the statement occurs only if the condition is true.
Syntax: if (condition)
statement;
Flow chart:
Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
int marks;
clrscr();
printf("Enter your marks:");
scanf("%d",&marks);
if(marks >=50)
printf("CONGRATULATIONS...!!! you have passed.");
getch();
}
Output
Enter your marks: 67
CONGRATULATIONS...!!! you have passed.
Page | 39
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
(ii) If-else statement
In if-else statement, if the condition is true, then the true statement(s), immediately
following the if-statement are executed otherwise the false statement(s) are executed.
The use of else basically allows an alternative set of statements to be executed if the
condition is false.
Syntax:
if (condition)
{
Statement(s);
}
else
{
Statement(s);
}
Flow chart:
Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
int y;
clrscr();
printf("Enter a year:");
scanf("%d",&y);
if (y % 4==0)
Page | 40
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
printf("%d is a leap year.",y);
else
printf("%d is not a leap year.",y);
getch();
}
Output
Enter a year: 2004
2004 is a leap year.
if ( condition 1)
{
if ( condition 2)
statement 1 ;
else
statement 2 ;
}
else
{
if (condition 3)
statement 3;
else
statement 4;
}
Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
int a,b,c;
clrscr();
printf("Enter three number:");
scanf("%d %d %d,&a,&b,&c);
if (a>b)
{
if (a>c)
printf("a is big‖);
else
printf("c is big‖);
}
Page | 42
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
else
{
if(b>c)
printf("b is big‖);
else
printf("c is big‖);
}
getch();
}
Output
Enter three number:
4
7
6
b is big
(v) Switch Statement
The control statements which allow us to make a decision from the number of choices is
called switch (or) Switch-case statement.
It is a multi way decision statement, it test the given variable (or) expression against a list
of case value.
Rules for Switch
The expression in the switch statement must be an integer or character constant.
No real numbers are used in an expression.
The default is optional and can be placed anywhere, but usually placed at end.
The case keyword must be terminated with colon (:);
No two case constant are identical.
The values of switch expression are compared with case constant in the order specified
i.e from top to bottom.
A switch may occur within another switch, but it is rarely done. Such statements are
called as nested switch statements.
The switch statement is very useful while writing menu driven programs.
Syntax:
switch(expression)
{
case 1:
statement;
break;
case 2:
Page | 43
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
statement;
break;
.
.
.
.
case N:
statement;
break;
default:
statement;
}
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,ans1,choice;
float ans2;
clrscr();
printf(" \n enter two numbers");
scanf("%d%d",&num1,&num2);
printf(" \n1.Addition \n 2.Subtraction \n 3.Multiplication \n 4.Division \n");
printf(―\n Enter the choice:‖);
scanf("%d",&choice);
switch(choice)
{
case 1:
ans1=num1+num2;
printf("Addition =%d",ans1);
break;
case 2:
ans1=num1-num2;
printf("Subtraction =%d",ans1);
break;
case 3:
ans1=num1*num2;
printf("Multiplication =%d",ans1);
break;
case 4:
ans2=(float)num1/num2;
printf("Division =%f",ans2);
break;
Page | 44
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
default:
printf("wrong choice");
break;
}
getch();
}
Output
enter two numbers
23
41
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter the choice 1
64
Page | 45
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Chapters 7
Loop Control Statements
You may encounter situations, when a block of code needs to be executed several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
A loop statement allows us to execute a statement or group of statements multiple times. Given
below is the general form of a loop statement in most of the programming languages:
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
Syntax
initialization;
while (condition)
{ statement;
increment/decrement;
}
Page | 46
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Flow chart
Example
#include<stdio.h>
#include<conio.h>
void main (void)
{
int n=1;
clrscr();
while (n<=5)
{
printf("\n %d",n);
n++;
}
getch();
}
Output
1
2
3
4
5
Page | 47
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Flow chart
Example:
#include<stdio.h>
#include<conio.h>
void main (void)
{
int a=1;
clrscr();
do
{
printf("\n %d",a);
a++;
}
while (a<=5);
getch();
}
Output
1
2
3
4
5
2. If the condition fails initially the loop is Even if the condition fails initially the
Skipped entirely even in the first iteration. loop is executed once.
Page | 48
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
(iii) For loop
For loops are used when the number of iterations is known before entering the loop. It
is also known as counter-controlled loop.
Syntax
for (initialization; condition; increment/decrement)
{
statement()s;
}
Flow chart
Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
int n;
for(n=1;n<=5;n++)
{
printf("\n %d",n);
}
getch();
}
Output
1
2
3
4
5
Page | 49
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Nested loop
A loop within a loop is called nested loop.
In this the outer loop is used for counting rows and the internal loop is used for counting
columns.
Any loop can be used as inner loop of another loop.
Syntax
for (initialization; condition; increment/decrement)
{
for(initialization; condition, increment/decrement)
{
statements(s);
}
}
Example
#include<stdio.h>
#include<conio.h>
void main ()
{
int i,j;
clrscr();
for(i=1;i<=3;i++)
{
for(j=1;j<=2;j++)
{
printf("\n%d\t%d",i,j);
}
}
getch();
}
Output
1 1
1 2
2 1
2 2
3 1
3 2
Page | 50
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
2. continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
The general form or the syntax of the continue statement is
continue;
Program
#include <stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
Page | 51
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
i = 1;
for(i=0;i<5;i++)
{
if(i==3)
continue;
printf("%d",i);
}
getch();
}
Output
0
1
2
4
3. goto statement
It is an unconditional transfer of control. It transfers the control to the specific point.
The goto statement is marked by label statement.
Label statement can be used anywhere in the function above or below the goto statement.
It is written as goto label;
Example:
#include <stdio.h>
#include<conio.h>
void main()
{
int a=3;
clrscr();
Start: printf(―Welcome\n‖);
if(a<5)
{
goto Start; Output
a++; Welcome
} Welcome
getch();
}
Page | 52
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Chapters 8
Arrays
Array
C programming language provides a data structure called the array, which can store a
fixed-size sequential collection of elements of the same type.
Array is a collection of homogenous data stored under unique name. The values in an array
are called as 'elements of an array.' These elements are accessed by numbers called as
'subscripts or index numbers.'
Arrays may be of any variable type.
Array is also called as 'subscripted variable.'
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations.
The lowest address corresponds to the first element and the highest address to the last
element.
Types of an Array:
i. One / Single Dimensional Array
ii. Two Dimensional Array
Features:
Array size should be positive number only.
String array always terminates with null character ('\0').
Array elements are countered from 0 to n-1.
Useful for multiple reading of elements (numbers).
Disadvantages:
There is no easy method to initialize large number of array elements.
It is difficult to initialize selected elements
Program
/* C program to find the sum marks of n students using arrays */
#include <stdio.h>
void main()
{
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
}
Output
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45
Page | 54
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Multidimensional Arrays
C programming language allows programmer to create arrays of arrays known as
multidimensional arrays.
For example: Here, a is an array of two dimension, which is an example of
multidimensional array.
Program
#include<stdio.h>
void main()
{
int a[5][5],b[5][5],c[5][5];
int row1,row2,col1,col2,i,j,k;
printf("Enter the row value of first matrix\n");
scanf("%d",&row1);
printf("Enter the column value of first matrix\n");
scanf("%d",&col1);
printf("Enter the row value of second matrix\n");
scanf("%d",&row2);
printf("Enter the column value of second matrix\n");
scanf("%d",&col2);
if((row1==row2)&&(col1==col2))
{
Page | 55
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
printf("Matrix can be added \n");
printf("Enter the values of first matrix\n");
for(i=1;i<=row1;i++)
{
for(j=1;j<=col1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the values of second matrix\n");
for(i=1;i<=row2;i++)
{
for(j=1;j<=col2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=1;i<=row1;i++)
{
for(j=1;j<=col1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("Sum of the two matrix is\n");
for(i=1;i<=row1;i++)
{
for(j=1;j<=col1;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
else
printf("Addition cannot be perform");
}
Page | 56
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
OUTPUT
Enter the row value of first matrix 2
Enter the column value of first matrix 2
Enter the row value of second matrix 2
Enter the column value of second matrix 2
Matrix can be added
Enter the values of first matrix
24
56
Enter the values of second matrix
31
28
Sum of the two matrix
55
7 14
Page | 57
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Chapters 9
Strings
Strings
Strings are actually one-dimensional array of characters terminated by a null character '\0'.
Thus a null-terminated string contains the characters that comprise the string followed by
a null.
The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows
Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to
print the above mentioned string −
#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Greeting message: Hello
Page | 58
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Function & Purpose
strcpy(s1, s2);
Copies string s2 into string s
strcat(s1, s2);
Concatenates string s2 onto the end of string s1
strlen(s1);
Returns the length of string s1
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1
Defining a Function
The general form of a function definition in C programming language is as follows:
Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Function Body − The function body contains a collection of statements that define
what the function does.
Page | 60
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Example
Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two −
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
For the above defined function max(), the function declaration is as follows:
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters along with the function
name, and if the function returns a value, then you can store the returned value. For example
Page | 61
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
#include <stdio.h>
/* function declaration */
int main () {
int a = 100;
int b = 200;
int ret;
return 0;
int result;
result = num1;
else
result = num2;
return result;
}
We have kept max() along with main() and compiled the source code. While running the final
executable, it would produce the following result:
Formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function:
2. Call by value
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect
on the argument.
3. Call by reference
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
Page | 63
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
C Programs
#include<stdio.h>
#include<conio.h>
main()
{
float r,Area;
printf("Enter radius");
scanf("%f",&r);
Area=3.14*r*r;
printf("Area of circle = %f",Area);
getch();
}
6. Write a Program that gets a character from user and displays its ASCII code
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf(―Enter a character‖);
scanf(―%c‖,&ch);
printf(― ASCII code =%d‖,ch);
getch();
}
Page | 64
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
7. Write a program that gets two numbers from user and perform all arithmetic
operations.
#include<stdio.h>
#include<conio.h>
main()
{
float a,b;
printf(―Enter two numbers‖);
scanf(― %f %f ‖, &a , &b );
printf(―%f + %f = %f \n‖,a,b ,a+b);
printf(―%f - %f = %f \n‖,a,b ,a-b);
printf(―%f * %f = %f \n‖,a,b ,a*b);
printf(―%f / %f = %f \n‖,a,b ,a/b);
getch();
}
8. Write a Program that gets distance in miles from user and convert it into kilometers
#include<stdio.h>
#include<conio.h>
main()
{
float m, km;
printf(―Enter distance in miles‖);
scanf(―%f‖,&m);
km=m * 1.6;
printf(― %f miles = %f km‖, m ,km);
getch();
}
9. Write a Program that gets temperature in foreignheite from user and convert it into
Celsius
#include<stdio.h>
#include<conio.h>
main()
{
float f,c;
printf(―Enter temperature in foreignheite‖);
scanf(―%f‖,&f);
c=5/9.0 *(f-32);
printf(―%f foreinheite = % f centigrade ―,f,c);
getch();
Page | 65
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
}
10. Write a program that takes a number from user and calculates its factorial with while
loop
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int num=0;
int fact=1;
printf(―plz enter a number \n‖);
scanf(―%d‖, &num);
while(num>0)
{
fact=fact*num;
Num--;
}
printf(―factorial of the number is %d‖,fact);
getch();
}
11. Write a program that takes a number from user and calculates its factorial with for
loop.
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int num=0;
int fact=1;
printf(―plz enter a number \n‖);
scanf(―%d‖, &num);
for(int i=num;i>0;i--)
{
fact=fact*num;
}
printf(―factorial of the number is %d‖,fact);
getch();
}
Page | 66
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
12. Write a program that takes a number form user and decides whether the number is even
or odd.
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int num=0;
printf(―plz enter a number \n‖);
scanf(―%d‖, &num);
if(num%2==0)
{
printf(―number is even \n‖);
}
else
{
printf(―number is odd \n‖);
}
getch();
}
13. Write a program that takes obtained marks and total marks from user and calculates
the average and assigns the grade.
#include<stdio.h>
#include<conio.h>
void main(void )
{
clrscr();
int obt_marks=0;
int total_marks=0;
float avg=0.0;
printf("plz enter your obtained marks \n");
scanf("%d",&obt_marks);
printf("plz enter total marks \n");
scanf("%d",&total_marks);
avg=(obt_marks*100.0)/total_marks;
if(avg>=80)
{
printf("Grade A+");
}
else if(avg>=70 && avg<80)
Page | 67
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
{
printf("Grade A");
}
else if(avg>=60 && avg<70)
{
printf("Grade B");
}
else if(avg>=50 && avg<60)
{
printf("Grade C");
}
else if(avg>=40 && avg<50)
{
printf("Grade D");
}
else
{
printf("Grade F");
}
getch();
}
14. Write a program that takes a number from user and print its table with the help of for
loop.
#include<stdio.h>
#include<conio.h>
main()
{
int table=0;
int prod=0;
printf("plz enter a number \n");
scanf("%d",&table);
for(int i=0;i<=10;i++)
{
prod=table*i;
printf(" %d * %d =%d \n ",table,i,prod);
}
getch();
}
15. Write a program program that displays the following shape by using nested for loop
*****
Page | 68
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
*****
*****
*****
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
for(int i=1;i<=4;i++)
{
for(int j=1;j<=5;j++)
{
printf("*");
}
printf("\n");
}
getch();
}
16. Write a program that displays the following shape by using nested for loop
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
printf("%d",j);
}
printf("\n");
}
getch();
}
17. Write a program that gets length and width of a rectangle from user, passes it to a
function that finds Area and returns it to main that displays the area.
#include<stdio.h>
Page | 69
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
#include<conio.h>
float Area(float l,float w)
{
float A= l*w;
return A;
}
void main(void)
{
float l,w;
clrscr();
printf(―plz enter length and width of rectangle‖);
scanf(―%f %f‖,&l,&w);
float area =Area(l,w);
printf(―Area of rectangle = %f‖,area);
getch();
}
18. Write a program that gets a number from user passes it to function that finds and
displays its table.
#include<stdio.h>
#include<conio.h>
void table(int n)
{
for(int i=1;i<=10;i++)
{
printf(―%d * %d= %d \n‖ , n , i , n*i);
}
}
void main(void)
{
int n;
printf(―Enter a number \n‖);
scanf(―%d‖,&n);
table(n);
getch();
}
19. Write a program that prints the square of all the numbers from 1 to 10.
#include<conio.h>
#include<stdio.h>
void main(void)
{
Page | 70
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
int i;
clrscr();
printf("Number\tSquare\n");
for(i=1;i<=10;i++)
{
printf("%d\t%d\n",i,i*i);
}
getch();
}
20. Write a program that reads temperature and prints a message as given below.
Temperature Message
t>35 It is hot!
t≥20, t≤35 Nice Day!
T<20 It is cold!
#include<stdio.h>
#include<conio.h>
void main(void)
{
int temp;
clrscr();
printf("Enter the temperature");
scanf("%d",&temp);
if(temp>35)
printf("It is hot!");
if(temp>=20 && temp<=35)
printf("Nice day");
if(temp<20)
printf("It is cold!");
getch();
}
Page | 71
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
21. Write a program that reads three numbers and prints the largest.
#include<stdio.h>
#include<conio.h>
void main(void)
{
int a,b,c;
clrscr();
printf("Enter any three no.s and get the largest no.");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
printf("%d is the largest no ",a);
else
if(b>a && b>c)
printf("%d is the largest no",b);
else
if(c>a && c>b)
printf("%d is the largest no",c);
else
printf("All no. are equal");
getch();
}
22. Write a program using a function to calculate the area of a rectangle.
#include<stdio.h>
#include<conio.h>
int area(int,int);
void main(void)
{
int height,width,ans;
clrscr();
printf("Enter height of the rectangle\n");
scanf("%d",&height);
printf("Enter the width of the rectangle\n");
scanf("%d",&width);
ans=area(height,width);
printf("The area of the rectangle is %d",ans);
getch();
}
int area(int a,int b)
{
int c;
c=a*b;
return c;
}
Page | 72
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Important Questions:
Page | 73
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Q 7. What is assembly language?
Ans. It is a programming language in which machine language instructions are replaced by English like
words. These words are known as mnemonics. It is pronounced as Ne-Monic. An assembly language
used English like words. It is easy to write a program in assembly language. It is mostly used for system
software.
Page | 75
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Q 20. What are delimiters?
Ans. Curly braces at the beginning and end of the main function are called delimiters. C language
statements are written between delimiters.
C++
C#
COBOL
BASIC
FORTRAN
PASCAL
JAVA
Page | 77
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Q 31. What are header files?
Ans. Header files are part of C compiler. C language provides many built-in programs. Every program
has a unique name. These programs are called built-in functions or library functions. Every library
function can perform a specific task. We can use these library functions in our C language program.
These functions are divided into groups according to their functionality. A group of same type of
functions is stored in a same file. This file is called header file.
Machine Independence
Standard Syntax
Shorter Programs
1. char – a character
Page | 79
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
2. int – an integer, in the range -32,767 to 32,767
3. long int – a larger integer (up to +-2,147,483,647)
4. float – a floating-point number
5. double – a floating-point number, with more precision and perhaps greater range than float
Q 45. What are the maximum and minimum possible ranges of values for long and short type?
Ans. If the int variable is created by default as a ‗long‘ type it typically will have a possible range of
values from a maximum of +214748347 and a minimum of -2147483648. For ‗short‘ type these are the
maximum and minimum values +327676 and minimum -32768.
Q 46. What exactly is a „variable scope‟, „local variables‟ and „global variables‟?
Ans. The extent to which a variable is accessible in a program is called the ‗variable scope‘. Variables
declared internally inside a function are known as ‗local‘ variables. Variables declared externally
outside a function are known as ‗global‘ variables.
Page | 80
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Q 47. What are signed values?
Ans. When an int variable is declared it can by default contain either positive of negative integer
values. These are known as ‗signed‘ values. The range of positive values is determined by your system.
1. Arithmetic operator
2. Relational operators
3. Logical Operators
4. Increment and decrements operators
5. 5.Assignment operators
6. 6.Conditional operator
7. Bitwise operators
1. for loop
2. while loop
3. do – while loop
Page | 81
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Q 53. Explain while loop?
Ans. A while loop has one control expression, and it is executed as long as that expression is true. The
general syntax of a while loop is
while( expression )
statements
We use a while loop when a statement or group of statements which may have to be executed a number
of times to complete their task. The controlling expression represents the condition
statements
1. break statement
2. continue statement
3. goto statement
4. exit() function
Page | 82
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Q 57. Define function?
Ans. A function is a module or block of program code which deals with a particular task. Each function
has a name or identifier by which is used to refer to it in a program. A function can accept a number of
parameters or values which pass information from outside, and consists of a number of statements and
declarations, enclosed by curly braces { }, which make up the doing part of the object
User defined functions are written by the user or programmer to compute a value or perform a task. It
contains a statement block which is executed during the runtime whenever it is called by the main
program.
Page | 83
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Part II - MS Access
Page | 84
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
MS Access
Introduction to Microsoft Access:
Microsoft Access is a computer application (database software) used to create and manage
computer-based databases on desktop computers and/or on connected computers (a network).
Microsoft Access can be used for personal information management (PIM), in a small
business to organize and manage data, or in an enterprise to communicate with servers.
MS Access is a relational database, meaning that data is stored in multiple tables that are
related to each other.
With Microsoft Access, you can analyze large amounts of data faster and more efficiently
than with Excel or other types of spreadsheets.
It has many built in features to assist you in constructing and viewing your information.
Database
Forms
Page | 85
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Tables:
A table is a two-dimensional list of items so that the items are arranged by categories. A complete or
incomplete series of items that represent each category is called a record. Therefore, a table can be
represented as follows:
Reports
A report is an effective way to present your data in a printed format. Because you have control
over the size and appearance of everything on a report, you can display the information the
way you want to see it.
Queries
Database File:
Main file that encompasses the entire database and that is saved to your hard-drive or floppy
disk. (Example: video.mdb )
Data types:
Data types are the properties of each field. A field only has 1 data type.
Most common data types in MS Access are:
Page | 86
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Text Use for text or combinations of text and numbers, such as addresses, or for numbers
that do not require calculations, such as phone numbers or postal codes (255 characters)
Memo Use for lengthy text and numbers, such as notes. Stores up to 63,999 characters
Currency Use for currency values and to prevent rounding off during calculations.
AutoNumber Use for unique sequential that are automatically inserted with a new record
Yes/No Use for data that can be only one of two possible values, such as Yes/No,
True/False, On/Off.
OLE Object Use for OLE objects (such as Microsoft Word documents, Microsoft Excel
spreadsheets, pictures, sounds,
Hyperlink Use for hyperlinks (hyperlink: Colored and underlined text or a graphic that
you click to go to a file, a location in a file, a Web page on the World Wide Web, or a
Web page on an intranet. Stores up to 2048 characters.
Lookup Wizard Use to create a field that allows you to choose a value from another table
or from a list of values using a combo box
A database management system (DBMS) refers to the technology for creating and
managing databases. DBMS is a software tool to organize (create, retrieve, update and
manage) data in a database. The main aim of a DBMS is to supply a way to store up and
retrieve database information that is both convenient and efficient.
Page | 87
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
RDBMS stands for Relational Database Management System. It organizes data into related
tables. Tables have rows and column.
Properties of RDBMS
An RDBMS is easily accessible. You execute commands in them Structured Query Language
(SQL) to manipulate data. SQL is standard language for interacting with a RDBMS.
An RDBMS provides full data independence
A relational database is a collection of individual, named objects. The basic unit of data storage
in a relational database is called a table.
An RDBMS enables data sharing between users.
An RDBMS minimizes the redundancy of data. This means that similar data is not repeated in
multiple tables
Database Models
A database model is a type of data model that determines the logical structure of a database
and fundamentally determines in which manner data can be stored, organized and
manipulated.
The most popular example of a database model is the relational model, which uses a
table-based format.
Types of database models:
Keys
A DBMS key is an attribute or set of an attribute which helps you to identify a row in a table.
They allow you to find the relation between two tables.
Five common types of Keys are:
i. Super Key
ii. Primary Key
iii. Candidate Key
iv. Foreign Key
v. Composite Key
Page | 88
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Super key: A super key is a group of single or multiple keys which identifies rows in a table. A
Super key may have additional attributes that are not needed for unique identification.
Primary Key: A primary key helps us to uniquely identify every row in the table.
Candidate Key: A super key with no repeated attribute is called candidate key.
Foreign Key: A foreign key is a column which is added to create a relationship with another table.
Every relationship in the model needs to be supported by a foreign key.
Composite key: A key which has multiple attributes to uniquely identify rows in a table is called a
composite key.
Relationships
Page | 89
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
Important Questions:
Q 1. Define relation.
Ans. In relational database, the table in which data is stored is called a relation. Collection of rows and
column is called table. Each intersection of a row and column is called cell. Table contains the
descriptive information about an entity. Table is also called relation. Each file in a file management
system corresponds to a table in database management system.
Q 2. What is an Entity?
Ans. Anything about which we want to store data is called entity. It can be a person, place or event etc.
Entity always has a unique name within a domain.
Q 3. What is a key?
Ans. A key field is a field or set of fields of a database table which together form a unique identifier for
a database record. The aggregate of these fields is usually referred to simply as "the key". A key field
also defines searches.
Page | 91
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
MULTIPLE CHOICE QUESTIONS
1. The _____________ loop executes at least once.
a) For b) While
c) Do-While d) None of above
7. To use printf and scanf functions ___________ header file must be included.
a) stdio.h b) math.h
c) string.h d) alloc.h
Page | 92
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
10. The function which calls itself is called ________________ function.
a) Recursive b) Nested
c) Simple d) Complex
18. String functions are accessible through the ______________ header file.
a) stdio.h b) math.h
c) string.h d) alloc.h
Page | 93
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
19. The _______________ statement is used to exit the switch structure.
a) goto b) default
c) return d) break
24. Software that translates assembly language into machine language is called
a) Loader b) Linker
c) Debugger d) Assembler
26. The language computer can understand is only binary code made up of 1s and 0s, this language
is
a) C b) Assembly
c) Machine d) Fortran
Page | 94
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
28. Software that translates the entire program into machine language before its execution is:
a) Word processor b) Database
c) Compiler d) Spreadsheet
36. There are two types of languages high level languages and _______________ level languages.
a) Very high b) Complex
c) Low d) Periodic
Page | 95
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
37. Which Access object is considered primary?
a) Table b) Query
c) Report d) Form
42. A variable that is known only within the function in which it is defined is called:
a) Global variable b) Public variable
c) Pure variable d) Local variable
Page | 96
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
46. A is a type of database which stores information in
tables.
a) Hierarchical database b) Network database
c) Relational database d) Tree database
49. The statement that is used to bypass the remainder of the loop and go back to beginning of loop:
a) break b) continue
c) exit d) return
53. The #include is used in the beginning of a C language program to include _________ file.
a) Header b) Object
c) Source d) Database
Page | 97
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II
55. To hold alphabetic type values ____________ type of variable is used.
a) int b) float
c) double d) char
60. The _____________ loop checks the condition at the end of loop.
a) For b) While
c) Do-While d) None of above
Page | 98
__________________________________________________________________________________________________
Prepared By: Sir Muneer A. Shaikh Subject: Computer Science - II