Professional Documents
Culture Documents
All Chapters
All Chapters
Chapter One
Introduction to Computer
1
Content
• Definition of computer
• Characteristics of computer
• Type of computers
• Applications of computer
What is computer?
• Speed: - The computer is able to process the data and give the
output in fractions of seconds such that required information is
given to the user on time enabling the user to take right
decisions on right time.
• A powerful computer is capable of executing about 3 million
calculations per second.
• Accuracy: - In spite of its high speed of processing, the
computers accuracy is consistently high enough which avoids
any errors.
• If it all there are errors, they are due to errors in instructions
given by the programmer. (GIGO)
Cont…
• Reliable: - The output generated by the computer is very
reliable, but it is reliable only when the data, which is
passing as input to the computer and the program, which
gives instructions are correct and reliable.
– Digital computer
– Hybrid computers.
Analog computers
– Voltmeter
– Speedometer
digital data.
Cont..
– Minicomputer
– Mainframe computer
– Super computer
Personal / Microcomputer
• The control unit controls the flow of data within the system.
• The control unit controls and monitors communications
between the hardware attached to the computer.
• The arithmetic and logic unit (ALU) is where the CPU performs the
• Every task that your computer carries out is completed here. Even
typing into a word processor involves adding binary digits to the file,
and then calculating which pixels on the screen should change so that
– the logic part, which deals with any logical comparisons, eg 2>1
Registers
Off-line Storage
• Also known as disconnected or removable storage.
• Is a computer data storage on a medium or a device that is not
under the control of a processing unit.
• It must be inserted or connected by a human operator before a
computer can access it again.
• Examples: – Floppy Disk , USB Flash drive , Memory card
4. Output Devices
Monitor
• The monitor is the most common output device. It displays
information in a pictorial form or commonly referred to as pixels.
• More the number of pixels, the better is the picture clarity and
sharpness.
• It includes a screen, circuitry, and the box, in which the circuit is
enclosed. The user can view the processed data on the screen.
• There are two types of Monitor screens. They are as follows:-
– Cathode Ray Tube Monitor (CRT)
– Flat Panel Screen Monitors
Printer
• These software products contain mainly programs which are written in low-
level languages, understandable language where they interact with the
hardware at a very basic level.
• System software acts as the interface between the hardware and the end
users.
Operating systems
• The most important system software package for any computer is
its operating system.
• Every computer system runs under the control of an operating
system.
• Operating systems for computers that are shared by many users
are considerably more complex than operating systems for
personal computers.
System Software
.
Examples
1) Algorithm to add two numbers.
Step 1: START
Step 2: Read two numbers n1 and n2.
Step 3: Sum ← n1 + n2
Step 4: Print Sum
Step 5: STOP
2) Algorithm to find largest number from two numbers.
Step 1: START
Step 2: Read n1 and n2.
Step 3: If n1 > n2, goto step 5
Step 4: Big←n2, goto step 6
Step 5: Big ← n1
Step 6: Print Big
Step 7: STOP
Examples of flow chart
1. Draw a flowchart to add two numbers 2. A Flowchart to find largest of two numbers
Cont…
by the user.
variable.
• To define our own names for constants that we use very often
without having to resort to memory consuming variables, simply by
using the #define preprocessor directive. Its format is: #define
identifier value
– For example: #define PI 3.14159
– #define NEWLINE '\n'
• This defines two new constants: PI and NEWLINE. Once they are
defined, you can use them in the rest of the code as if they were any
other regular constant.
• The #define directive is not a C++ statement but a directive for the
preprocessor; therefore, it assumes the entire line as the directive
and does not require a semicolon (;) at its end.
Declared constants (const)
• With the const prefix you can declare constants with a specific
type in the same way as you would do with a variable:
– const int PI = 3.14159;
– const char tab = '\t';
• Here, PI and tabulator are two typed constants.
• They are treated just like regular variables except that their
values cannot be modified after their definition.
Introduction to Strings
• Variables that can store non-numerical values that are longer than one single character are
known as strings.
• A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type we need to include an additional header file in our source code:
<string>
#include<iostream>
Both initialization formats are valid
using namespace std;
with strings:
#include <string> o string mystring = "This is a string";
int main () o string mystring ("This is a string");
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
Operators
like add (+), subtract (-), multiply (*), divide (/), and mod (%).mod
operands on either side of them like less than (<), less than or equal
(<=), equal (==), Greater than (>), Greater than or equal (>=)and not
• Logical operators: C++ has the following three logical operators. &&
(meaning logical AND), || (logical OR), ! (logical NOT).
E.g:( (5 == 5) && (3 > 6) )
// evaluates to false ( true && false ).
• In any “if” statement, first the “expression” will be evaluated and if the
outcome is non zero (which means TRUE), then the “statements” is
executed. Otherwise, nothing happens (the statement will not be
executed) and execution resumes to the line immediately after the “if”
block.
The If else statement
• First “expression” is evaluated and if the outcome is none zero (true), then “statements1” will be executed.
Otherwise, which means the “expression” is false “statements2” will be executed.
The “if else if” statement
• The “if else if” statement allows us to specify more than two alternative
statements each will be executed based on testing one or more
conditions. if (expression1)
• The general syntax is: statements1;
else if(expression2)
statements2;
..
else if(expressionN)
statementsN;
else
statements
• First “expression1” is evaluated and if the outcome is none zero (true), then “statements1” will be executed.
Otherwise, which means the “expression1” then “expression2” will be evaluated: if the output of expression2 is
True then “statements2” will be executed otherwise the next “expression” in the else if statement will be executed
and so on.
• If all the expressions in the “if” and “else if” statements are False then “statements” under else will be executed.
Nesting If statements within another if statement
statements;
}
Cont…
• The do statement (also called the do while loop) is similar to the while
statement, except that its body is executed first and then the loop
condition is examined.
• In do…while loop, we are sure that the body of the loop will be
executed at least once. Then the condition will be tested.
• The general syntax is:
do
{
statement;
}
while(expression);
Jumping Statements
C ++ enables its programmers to break up a program into segments commonly known as functions, each of
In the figure, we can see that main() calls a function named func1().
Therefore, main() is known as the calling function and func1() is known
as the called function.
The moment the compiler encounters a function call, the control jumps
to the statements that are a part of the called function.
After the called function is executed, the control is returned to the calling
program.
Cont…
The main() function can call as many functions as it wants and as many times
as it wants.
For example, a function call placed within a for loop, while loop, or do–while
loop may call the same function multiple times till the condition holds true.
Not only main(), any function can call any other function.
Why?
Dividing the program into separate well-defined functions facilitates each function to be
Understanding, coding, and testing multiple separate functions is easier than doing the
When a big program is broken into comparatively smaller functions, then different
programmers working on that project can divide the workload by writing different
functions.
Like C/C++ libraries, programmers can also write their own functions and use them from
different points in the main program or any other program that needs its functionalities.
C++ functions generally adhere to the following rules:
2. Function names are made up and assigned by the programmer following the same
rules that apply to naming variables. They can contain up to 32 characters, they must
begin with a letter, and they can consist of letters, numbers, and the underscore (_)
character.
3. All function names have one set of parenthesis immediately following them. This
helps you (and C++ compiler) differentiate them from variables.
4. The body of each function, starting immediately after parenthesis of the function
Function declaration :-Before using a function, the compiler must know the
number of parameters and the type of parameters that the function expects to
receive and the data type of value that it will return to the calling program.
Placing the function declaration statement prior to its use enables the compiler to
make a check on the arguments used while calling that function.
It is the interface of a function (also called function prototype) specifies how it may
be used.
Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function
at the top of the file calling the function.
return_type function_name( parameter list );
Cont…
return_type:-specifies the data type of the value that will be returned to the calling
function as a result of the processing performed by the called function.
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.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameter names are not important in function declaration only their type is required.
Cont…
The function header is same as the function declaration. The only difference
If function definition is done before the main function, then there is no need to put
the prototype, otherwise the prototype should be script before the main function
starts
Function Calling
While creating a C++ function, you give a definition of what the function has to do.
When a function call is executed, the arguments are first evaluated and their
When a function is invoked, the compiler jumps to the called function to execute
Once the called function is executed, the program control passes back to the calling
function.
Function calling
2. Write a function which calculates the area of rectangle. Note the dimensions of
the polygon should be provided from the user.
3 . Write a function which return the maximum of two numbers. Note that the numbers should be
provided from the user.
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
void main()
{
int FirstNum,SecondNum, maximum;
cout<<“Enter the two numbers”;
cin>> FirstNum>>SecondNum;
maximum=max(FirstNum,SecondNum);
cout<<“Maximum of two numbers is=”<<maximum;
}
Home Work
.
3 Write C++ program using function which perform all arithmetic operations for two
numbers.
Note:- 1. Use different functions for each operation
2. Check divide by zero exception (If denominator is zero your program display
error message).
3. Your program display menu for the user to select the operation.
Function Parameters
1. Passing By value :- The value of the actual parameter is passed to formal parameters when we
• In this method, the called function creates new variables to store the value of the arguments
passed to it.
• Therefore, the called function uses a copy of the actual arguments to perform its intended task.
• If the called function is supposed to modify the value of the parameters passed to it, then the
• In the calling function, no change will be made to the value of the variables. This is because
all the changes are made to the copy of the variables and not to the actual variables.
void add(int n);
int main()
{
int num = 2;
cout<<"\nThe value of num before calling the function "<< num;
add(num);
cout<<"\nThe value of num after calling the function = "<<num;
return 0;
}
void add(int n)
{
n = n + 10;
cout<<"\n The value of num in the called function = "<< n;
}
Cont…
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2
Following are the points to remember while passing arguments to a function using the call-by
value method:
When arguments are passed by value, the called function creates new variables of the
same data type as the arguments passed to it.
The values of the arguments passed by the calling function are copied into the newly
created variables.
Values of the variables in the calling functions remain unaffected when the arguments are
passed using the call-by-value technique.
Cont…
2. Passing By Reference
In this method, we declare the function parameters as references rather than normal variables.
When this is done, any changes made by the function to the arguments it received are also
To indicate that an argument is passed using call by reference, an asterisk (*) is placed after
A reference parameter, on the other hand, receives the argument passed to it and works on it
directly.
Any change made by the function to a reference parameter is in effect directly applied to the
argument.
Cont…
1. Local variables:
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or block of code.
Local variables are not known to functions outside their own.
2. Global variables;
Global variables are defined outside of all the functions, usually on top of the
program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration.
Example
void sum ();
int c; // global variable declaration: void sum()
{
int main () {
int x=25;
// local variable declaration:
int y=45;
int a, b,c1; c1=x+y; // error
// actual initialization cout<<“The sum is =”<<c1;
a = 10; }
b = 20;
c = a + b;
cout << c;
sum();
return 0;
}
Cont…
It’s possible to declare local and global variables of the same name.
C++ provides the unary scope resolution operator (::) to access a global variable
when a local variable of the same name is in scope.
The unary scope resolution operator cannot be used to access a local variable of
the same name in an outer block.
A global variable can be accessed directly without the unary scope resolution
operator if the name of the global variable is not the same as that of a local
variable in scope.
Example
#include <iostream>
using namespace std;
int num =15;
int main()
{
double num=77.5;
// display values of local and global variables
cout << "Local double value of number = " <<num;
cout<< "\nGlobal int value of number = " <<::num << endl;
} // end main
Output
Local double value of number =77.5
Global int value of number = 15
Const Argument
In such cases the function declaration must provide default values for those
arguments that are not specified.
The compiler look at the prototype to see how many arguments a function uses
and alerts the program for possible default values.
Default argument must be added from right to left, we can not provide a default
value to a particular argument in the middle or first of an argument list.
Two or more functions having same name but different argument(s) are known
as overloaded functions.
It allows the programmer to write functions to do conceptually the same thing
on different types of data without changing the name.
The overloaded function should be different interns of number of arguments,
data type of the arguments and order of argument lists.
If two or more functions differ only in their return types, C++ can’t overload
them.
To be execute the compiler identifies the overloaded function based on the
difference they encounter while the function is invoked.
Example
1. Write a function which prints area of rectangle and circle using function
int main(void)
void func1(int a, int b) {
{ int i=10,j=40;
a*=2; cout<<“i=“<<i<” and j= ”<<j<<endl;
b+=10; func1(i,j);
cout<<“a=“<<a<” and b= ”<<b<<endl; cout<<“i=“<<i<” and j= ”<<j<<endl;
func2(&i,&j);
}
cout<<“i=“<<i<” and j= ”<<j<<endl;
void func2(int *x, int *y) }
{
*x*=2;
*y+=10;
cout<<“x=“<<*x<” and y= ”<<*y<<endl;
}
3. What is the output of the program?
void message(void)
{
cout << "This is a recursive function.\n";
message();
}
The function above displays the string "This is a recursive function.", and then calls
itself.
The function is like an infinite loop because there is no code to stop it from repeating.
Like a loop, a recursive function must have some algorithm to control the number of
times it repeats.
Cont…
As long as the times argument is greater than zero, it will display the message and
call itself again.
Each time it calls itself, it passes times - 1 as the argument.
Cont..
For example, let's say a program calls the function with the following statement:
Message(5);
The Recursive Factorial Function
In mathematics, the notation n! represents the factorial of the number n. The factorial of
The following C++ function implements the recursive definition shown above:
int factorial(int num)
{
if (num > 0)
return num * factorial(num - 1);
else
return 1;
}
Cont…
// Function prototype
int factorial(int);
void main(void)
{
int number;
o Introduction to array
o Declaration and Initialization of array (1D)
o Accessing 1D array
o Strings and operations on string
o Two dimensional array
o Array manipulation
o Introduction to structure
o Structure declaration
o Arrays of structure
Introduction to array
The data type of the values which will be stored in the array
The name of the array (i.e. a C++ identifier that will be used to access and
update the array values)
The dimensionality of the array:
Storing values in an array Input values for the elements from the keyboard
We start at the index i at 0 and input the value for the first element
of the array.
Since the array has 10 elements, we must input values for elements
whose index varies from 0 to 9.
ASSIGNING VALUES TO INDIVIDUAL ELEMENTS
Any value that evaluates to the data type as that of the array can be
assigned to the individual array element.
A simple assignment statement can be written as marks[3] = 100; Here,
100 is assigned to the fourth element of the array which is specified as
marks[3].
we cannot assign one array to another array, even if the two arrays have
the same type and size.
To copy an array, you must copy the value of every element of the first
array into the elements of the second array.
Accessing the values of an array
• The values of any of the elements in an array can be accessed just like the value
of a regular variable of the same type. The syntax is:
name[index]
• Following the previous examples in which foo had 5 elements and each of those
elements was of type int, the name which can be used to refer to each element is
the following:
• For example, the following statement stores the value 75 in the third element of
foo:
foo [2] = 75;
• and, for example, the following copies the value of the third element of foo to a
variable called x: x = foo[2];
Multidimensional arrays
• jimmy represents a bidimensional array of 3 per 5 elements of type int. The C++
syntax for this is:
int jimmy [3][5];
and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:
jimmy[1][3]
INITIALIZING TWO-DIMENSIONAL ARRAYS
Since the two-dimensional array contains two subscripts, we will use two for
loops to scan the elements. The first for loop will scan each row in the 2D
array and the second for loop will scan individual columns for every row in
Output
the array. Eg. a[0][0]: 0
int main () { a[0][1]: 0
// an array with 5 rows and 2 columns. a[1][0]: 1
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; a[1][1]: 2
// output each array element's value a[2][0]: 2
a[2][1]: 4
for ( int i = 0; i < 5; i++ ) a[3][0]: 3
for ( int j = 0; j < 2; j++ ) { a[3][1]: 6
cout << "a[" << i << "][" << j << "]: "; a[4][0]: 4
cout << a[i][j]<< endl; a[4][1]: 8
}
return 0;
}
Strings
One of the most useful data types supplied in the C++ libraries is the
string.
characters,suchas"Hello"or"May10th is my birthday!".
Cont…
Apart from these characters, a null character ('\0') is stored at the end of the
string.
The subscript starts with a zero (0). All the characters of a string are
stored in successive memory locations
Cont…
When we declare the string like this, we can store size–1 characters
in the array because the last character would be the null character. For
example, char mesg[100]; can store a maximum of 99 characters.
The other way to initialize a string is to initialize it as an array of
characters. For example,
Make an array, that will receive the string, the target of a cin stream.
The following program reads (part of) a string entered by the user:
int main()
{
char str[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
cout << str;
return 0;
}
Cont…
Problem: Entering the string “ This is a test”, the above program only
returns “This ”, not the entire sentence.
Reason: The C++ input/output system stops reading a string when the
first whitespace character is encountered.
Solution: Use another C++ library function, gets() or cin.getline().
cin.getline() function takes the name and size of the string as argument
Cont…
# include <iostream>
using namespace std;
int main()
{
//declaring string (character array)
char text[100]={0};
cout<<"Enter a string: ";
cin.getline(text,100);
cout<<"Input string is: "<<text<<endl;
return 0;
}
STRUCTURES
C/C++ arrays allow you to define variables that combine several data
items of the same kind, but structure is another user defined data type
which allows you to combine data items of different kinds.
Structure is basically a user-defined data type that can store related
information (even of different data types) together.
Structure is a collection of data items. The data item can be different
type, some can be int type, some can be float, some can be char and so
on.
A structure is therefore a collection of variables under a single name.
The data item of structure is called member of the structure.
Cont…
The difference between array and structure is the element of the array
has same type, while the element of structure can be different.
The other difference is that each element of the array referred by its
position while each element of a structure has a unique name.
Declaration of structure
struct [structure tag] struct Books
{ {
Data type 1 member 1; char title[50];
Data type 2 member 2; char author[50];
char subject[100];
Data type n member n; int book_id;
}; };
Creating Structure variable
struct struct_name
struct struct_name
{
{
data_type member_name1;
data_type member_name1; OR data_type member_name2;
data_type member_name2; data_type member_name3;
data_type member_name3; .......................
....................... };
• When all the members of a structure are not initialized, it is called partial
initialization.
• In case of partial initialization, first few members of the structure are
initialized and those that are uninitialized are assigned default values.
Accessing Member of Structure
When the above code is compiled and executed, it produces the following result
−
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
int i;
Employee Emp[ 3 ]; //Statement 1
for(i=0;i<3;i++)
{
cout << "\nEnter details of " << i+1 << " Employee";
cin >> Emp[i].Id>> Emp[i].Name>> Emp[i].Age >> Emp[i].Salary;
}
Array within Structure
Like normal data type, structure can also store an array as well.
Syntax for array within structure
struct structure-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
----------
---------- Eg. struct Student
datatype varN; {
int Roll;
}; char Name[25];
int Marks[3]; //Statement 1 : array of
structure-name obj; marks
int Total;
float Avg;
};
Cont…
void main()
{
int i;
Student S;
cout << "\n\nEnter Student Roll : ";
cin >> S.Roll;
cout << "\n\nEnter Student Name : ";
cin >> S.Name;
S.Total = 0;
for(i=0;i<3;i++)
{
cout << "\n\nEnter Marks " << i+1 << " : ";
cin >> S.Marks[i];
S.Total = S.Total + S.Marks[i];
}
S.Avg = S.Total / 3;
}
Structure within structure
}
D ! !
EN