Lab Manual PDF
Lab Manual PDF
Lab Manual PDF
Faculty
CS101L
(Manual)
Table of Contents
There are three parts of this lab: (i) to cover the basics of web services provided by the GIKI, (ii) to revise
the basics of number systems and (iii) to understand the basics of flow charts. The web services include
email service and the course website. Using GIKI email service you can send/receive emails, search for
contacts within GIKI, and set your calendar etc. The course website is the source of lecture notes, slides,
and handouts for the courses. In this way it acts as the interface between the students and instructors.
These basics will also help you in the course CS101.
Learning Objectives
Computer settings for web access in GIKI
To learn using GIKI email
via the web interface (Internet Explorer or Fire fox)
via an Email Client (Outlook Express)
To learn about FCSE course website
making an account
accessing course and lab resources
To learn number systems
Outcomes:
Students should be able to make a GIKI email account
Students should be able access and use course website
Students should know the basic number systems
Click on Tools and then on Internet Option. You will see a screen like this
To use this email you need a password that is available at the PC Lab desk with the laboratory assistants.
He will provide you your email password. You cannot collect the password for your friend. One must
have come to collect his/her own password from the Lab assistants.
In order to access your email you need to
Search engine
Search engine is basically a website which stores information about different other websites, so search
engine will help you to access a website of yours own interest without knowing the address of that
specific website. Google is a powerful search engine. It searches for the web pages which contains the
information which you have provided in the search option. Sometime the information provided by the
search engine is irrelevant. Try to search with your search option enclosed in double quotes (“”) and
without it.
Digital computers are the machines, which respond to numbers only. All the data and instructions must,
therefore, be represented in a numeral format. There are different number systems e.g., decimal
number systems and binary number systems. The binary system has been found to be the most natural
and efficient system for modern digital computers. The following four number systems are commonly
used in modern computers.
Number Conversion
We, in general, use decimal number system in our daily life. However, binary number system is suitable
for use in digital computers. Other number systems are used for programming/coding and data storage
4 =100
5 = 101 Hence (45)O= (100101)B
Binary to Hexadecimal
Highest symbol is F (15)
15 in Binary is 1111
B = 1011
1 = 0001 Hence (B1A)16 (1011 0001 1010)2
A = 1010
A flowchart (also spelled flow-chart and flow chart) is a schematic representation of a process. They are
commonly used in business/economic presentations to help the audience visualize the content better,
or to find flaws in the process. Examples include instructions for a bicycle's assembly, an attorney
outlining a case's timeline, diagram of an automobile plant's work flow, the decisions to be taken on a
tax form etc. Generally the start point, end points, inputs, outputs, possible paths and the decisions that
lead to these possible paths are included. Flow-charts can be created by hand or manually in most office
software, but lately specialized diagram drawing software has emerged that can also be used for the
purpose, such as Visio, OpenOffice.org Draw and Dia.
+ plus, add
- minus, subtract
* multiply
/ divide
± plus or minus
= equal to
> greater than
< less than
≥ greater than or equal to
≤ less than or equal to
≠ not equal
YES or Y
NO or N
TRUE or T
FALSE or FF
Algorithm
An algorithm is a finite set of well-defined instructions for accomplishing some task The concept of an
algorithm is often illustrated by the example of a recipe, although many algorithms are much more
complex; algorithms often have steps that repeat (iterate) or require decisions (such as logic or
comparison) until the task is completed. If an algorithm is flawed or not appropriate to the problem it
will not solve the problem even if we use it efficiently.. For example, performing the potato salad
algorithm will fail if there we try to use it to prepare apple salad even if all the motions of preparing the
salad are performed.
Example: 1.13
Problem: Write an algorithm to find the sum of two numbers
Solution:
1. Input first number
2. Store the number in a
3. Input the second number
4. Store the second number in b
5. Calculate the sum using a + b
6. Store the sum in c
7. Print the sum stored in c
TASKS:
Tasks related to the lab will be provided by the lab instructor.
The aims of this lab are to introduce C/C++ language and to write the first basic computer program.
Learning Objectives:
Introduction of C/C++ Programming Environment (Dev C++)
Writing first program "Welcome to C++"
Compiling and running basic program
Outcomes:
Student should be able to gain basic C++ knowledge
Student should be able to write simple C++ programs
C++ IDEs for Windows: Turbo C++, Dev Cpp , Net Beans, Eclipse & Microsoft Visual Studio
C++ IDE for Android: Cppdroid, C4droid, Quoda
C++ IDE for Iphone: XCode, Cppcode
3. Write your code in the text area as shown in the following screenshot
7. After successfully running the code, you will notice the following output screen
Replace the line cout<<"Welcome to C++ "; in your program with cout<< "This\nis\na\ntest\n\nShe
said, \"How are you?\"\n";
Which would display:
This
is
a
test
She said, "How are you?"
TASKS: Tasks related to the lab will be provided by the lab instructor.
The aims of this lab are to cover some basics of C++ programming e.g., Variables, Types, Arithmetic
Operators and Decision Control Structures.
Learning Objectives:
To learn and to use
Variables
Variable Types
Declaring Variables
Arithmetic Operators
Comments
input/output in C++
cin
cout
Outcomes:
Students should be able to know C++ variables their types and arithmetic operators.
Students should be able to use cin and cout methods in the programs.
Variable Types
A variable type is a description of the kind of information a variable will store. Following are some of the
Types that a variable can have:
Data Type Keyword Used Example Declarations
Integer (Whole Numbers) Int 21 int a; int b=21;
Floating Point (Decimal Numbers) Float 1.56 float a; float b=1.56;
Character (Characters) Char A char a; char a=’A’;
Declaring Variables
Declaring a variable in C++ is simple. Let's say you want to declare a variable of type int called myAge.
That is to say, the variable myAge will store an integer. In C/C++, this is written:
intmyAge;
All this does is tell the computer that you plan to use an integer, and that the integer's name is myAge.
In some languages, variables are initialized to 0 - that is, a variable's initial value will be 0. This is not true
of C++! Sometimes your variables will be initialized to 0, but sometimes they will be initialized with
garbage. As you might anticipate, this can cause some nasty bugs. Hence, it is always a good idea to
initialize your variables with some value. If you don't know what a variable's initial value should be,
initialize it to 0.
Example 3.1
Let’s write a program that stores your age in a variable and outputs “My age is 21". The first line of the
main function initializes myAge by assigning it a value immediately. compile and run the following code.
C++ Comments
A comment is text that the compiler ignores but that is useful
for programmers. Comments are normally used to annotate
int main()
code for future reference. The compiler treats them as white
space. You can use comments in testing to make certain lines {
of code inactive. //declaring integer and character
A C++ comment is written in one of the following ways: vairables
The /* (slash, asterisk) characters, followed by any int a; char ch;
sequence of characters (including new lines), followed /*Initializing the
by the */ characters. This syntax is the same as ANSI C. variables
The // (two slashes) characters, followed by any
*/
sequence of characters. A new line not immediately
preceded by a backslash terminates this form of a=10; ch=’b’;
comment. Therefore, it is commonly called a single- /*Printing the
line comment. variables
The comment characters (/*, */, and //) have no special */
meaning within a character constant, string literal, or cout<<“The value of ch is ”
comment. <<ch<<endl;
cout<<“The value
Example 3.2
of a is ”<<a<<endl;
system(“pause”);
return 0;
}
Output
The value of ch is b
The value of a is 10
Notice the use of “endl” at the end of the cout statements. It simply adds a carriage return which ends
the current line.
Example 3.3
int main()
{
int a = 5;
intc = ’t’;
cout<< “Value of a is ” << a<<endl;
cout<< “and value of c is ” << c <<endl;
/*
You can also print the above in only one statement
*/
cout<< “Value of a is ” << a << “and value of c is ” << c <<endl;
system(“pause”);
return 0;
}
To print out the value of some variable, you need to embed a format specifier in your text string and
pass extra arguments to thecoutfunction. An example:
cout<< “My Age is ” <<MyAge<< “Years”;
This statement prints out the value of MyAge. Note that the value of MyAge is passed to the cout
function.
Output
Value of a is 5
and value of c is t
Value of a is 5 and value of c is t
Example 3.4
int main()
{
inta,b;
cout<<“Enter value of a: \n“;
cin>>a;
cout<<“Enter value of b: \n“;
cin>>b;
cout<< “The value of a is: ”<< a <<endl;
cout<<“The value of b is: ”<< b <<endl;
cout<< “Enter new value for both separated by a space: \n”;
cin>>a >> b;
cout<< “New values are: ”<< a << “ ”<< b <<endl;
system(“pause”);
return 0;
}
Arithmetic Operators
Arithmetic operators are commonly used in a variety of programming languages. In C, there are five of
them, and they all take two OPERANDS. Recall that an operand is an expression that is required for an
operator to work. For example, for 8 + 4, 8 and 4 are considered as the operands.
int main()
{
inta,b;
int sum;
cout<<“Enter value of a: \n“;
cin>>a;
cout<<“Enter value of b: \n“;
cin>>b;
sum=a+b;
cout<<“Sum: ”<<sum<<endl;
return 0;
}
Output
Enter value of a:
3
Enter value of b:
6
Sum: 9
TASKS:
Tasks related to the lab will be provided by the lab instructor.
The aims of this lab are to cover Decision Control Structures of C++.
Learning Objectives:
Comparison/Relational Operators
Logical Operators
If Statement
If - else statement
else - if Statement
Outcomes:
Students should be able to use all types of C++ operators
Students should be able to use if, if-else and else-if statements
Logical Operators
Operator name Syntax
1. The if statement
2. The if-else statement
3. The else - if statement
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int number ;
cout<< “Enter an integer\n”;
cin>> number;
if ( number >100 )
cout<<“The number is greater than 100”;
getch();
return 0;
}
Note we did not use curly brackets ‘, -’for body of if if () because it did not include multiple statements
(block of statements). If it includes multiple statements then it would have been something like this.
if (number<100)
{
cout<< “The number is greater than 100\n”;
cout<< “No doubt that the number is greater than 100”;
}
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int a,b ;
if ( a >=b )
// this condition can also be written as if(a>b || a==b)
cout <<a <<"-" <<b <<"=" <<a-b;
else
cout <<b <<"-" <<a << "=" <<b-a;
getch();
return 0;
}
The above program checks if the number is less than 100. This check is done in the first if statement.
If the result is true the program enters the second if statement which is also called the nested if
statement. Here another check is performed. The number is checked if it less than 50 or not. If the
number is less than 50 it is conveyed to the user. The rest is pretty self-explanatory.
Sometimes we wish to make a multi-way decision based on several conditions. The most general way of
doing this is by using the else if variant on the if statement. This works by cascading several
comparisons. As soon as one of these gives a true result, the following statement or block is executed,
and no further comparisons are performed.
if(expression)
{
Block of statement;
}
else if(exprerssion)
{
Block of statement;
}
else if(exprerssion)
{
Block of statement;
}
. . // you can add as many else-if statements as
many you need
. .
. .
else
{
Block of statement;
}
Example: 4.4
Write a program which takes marks as input and shows the out put as follows:
Marks Output
Greater than or equal to 75 Passed: Grade A
Greater than or equal to 60 Passed: Grade B
Greater than or equal to 45 Passed: Grade C
Less than 45 Failed
int main()
{
int marks;
getch();
return 0;
}
In this example, all comparisons test a single variable called marks. In other cases, each test may involve
a different variable or some combination of tests. The same pattern can be used with more or fewer
else if's, and the final lone else may be left out. It is up to the programmer to devise the correct
structure for each programming problem.
Example: 4.5
Write a program which takes marks as input and then shows output as follows:
Marks Output
87 – 100 Grade A
80 - 87 Grade B+
72 – 80 Grade B
67 – 72 Grade C+
60 - 67 Grade C
below 60 Failed
int main()
{
int marks;
getch();
return 0;
}
In above example logical operator && is used and because of this && operator condition will only be
satisfied if both the conditions in a single if are true. If any of the condition is false because of &&
operator the whole condition will be treated as false.
TASKS:
Tasks related to the lab will be provided by the lab instructor.
The aims of this lab are to cover some other basics of C programming Loop Structure in detail.
Learning Objectives:
While Loop
Nested While Loop
Do While loop
Outcomes:
Students should be able to use while, nested while and do while loop loops.
Syntax
Basic syntax of while loop is as follows:
while ( expression )
{
Single statement
or
Block of statements;
}
The expression can be any combination of Boolean statements that are legal. Even, (while x ==5 || v ==
7) which says execute the code while x equals five or while v equals 7.
#include <iostream>
using namespace std;
int main()
{
int i = 10;
while ( i > 0 )
{
cout<<i;
cout<<”\n”;
i = i -1;
}
system(“pause”);
return 0;
}
}
#include <iostream>
using namespace std;
int main()
{
int counter = 1;
while (counter <= 10)
{
cout<<counter;
cout<<”\n”;
counter++;
}
system(“pause”);
return 0;
}
Our 3rd example is based on a while-loop that keeps on running until a certain condition is reached (a
certain value is entered by the user). That certain value is called the 'sentinel value', 'signal value' or
'flag value'.
Our program asks the user for an integer value, if that value is not -1, it keeps on running through the
next cycle/iteration.
Example 5.3: Printing the numbers you entered using a while loop
#include <iostream>
using namespace std;
int main()
{
int flag; //flag is just an integer variable
cout<<“Enter any number: ( -1 to quit) ”;
cin>>flag;
cout<<“Entering the while loop now...\n”;
while (flag != -1) {
cout<<“Enter any number: ( -1 to quit) ”;
cin>>flag;
cout<<“You entered \n”<<flag;
}
cout<<“Out of loop now”;
system(“pause”);
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int i = 15, j; // variables for counter…
while(i>0) // outer loop, execute this first...
{
j=i-1; // the initial value of j is i - 1
while(j>0) // then, execute inner loop with loop index j,
{
cout<<"*"; // display *
j = j - 1; // decrement j by 1 until j>10, i.e j = 9
}
cout<<"\n"; // go to new line, new row
i = i - 1; // decrement i by 1, repeat until i > 0 that is i = 1
}
system(“pause”);
return 0;
}
Output
Example 5.6
#include <iostream>
using namespace std;
int main ()
{
long n;
do
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n"; } while (n != 0);
return 0;
}
Output:
Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0
TASKS:
Tasks related to the lab will be provided by the lab instructor.
Learning Objectives:
Use of For Loop
Use of Nested For Loop
Comparison between For loop, While loop and Do While loop
Outcomes:
Students should be able to use For loop, Nested For Loop and differentiate them.
return 0;
system(“pause”);
}
Example 6.2: Output
#include<iostream>
using namespace std; Loop counter value is 5.
int main() Loop counter value is 10.
{ Loop counter value is 15.
int x; Loop counter value is 20.
for ( x=5; x <= 50; x = x+5 ) Loop counter value is 25.
{ // x = x + 5 could also be written x += 5 Loop counter value is 30.
cout<< "Loop counter value is " << x << ".\n"; Loop counter value is 35.
} Loop counter value is 40.
system ("pause"); Loop counter value is 45.
return 0; Loop counter value is 50.
}
Can you modify the above program that counts from 50 to 5 with decrements of 5?
Example 6.4:
// The following program checks if the number entered is a prime number or not
//Use of for loop and if-else statement
#include<iostream>
using namespace std;
int main()
{
longn,j;
cout<<"\n\n Enter the Number to test if it is a prime number ";
cin>>n;
for(j=2;j<=n/2;j++)
{
if(n%j==0)
{ cout<<"\n\n\t It is not a prime nuber as it is divisible by"<<j<<endl;
break;}
else
{ cout<<endl<< n << " is a Prime number "<<endl;
break; }
}
system("pause");
}
The aims of this lab are to cover "Switch" and "Case" in detail.
Learning Objectives:
Introduction to Switch and Case Statement
General Syntax of Switch and Case Statements
Use of Break Statement
Use of Continue Statement
Outcomes:
Students should be able to use Switch statement, Case statement, Break statement and
Continue Statement.
#include <iostream>
using namespace std;
int main() {
int a;
cout<<"Pick a number from 1 to 4:\n”;
cin>>a;
switch (a) {
case 1:
cout<<"You chose number 1\n";
case 2:
cout<<"You chose number 2\n";
case 3:
cout<<"You chose number 3\n";
case 4:
cout<<"You chose number 4\n";
default:
cout<<"That's not 1,2,3 or 4!\n";
}
system(“pause”);
return 0;
}
(Suppose I entered 2...)
Pick a number from 1 to 4:
2
You chose number 2
You chose number 3
You chose number 4
That's not 1,2,3 or 4!
You'll notice that the program will select the correct case but will also run through all the cases below it
(including the default) until the switch block's closing bracket is reached.
To prevent this from happening, we'll need to insert another statement into our cases...
int main() {
int a;
switch (a) {
case 1:
cout<<"You chose number 1\n";
break;
case 2:
cout<<"You chose number 2\n";
break;
case 3:
cout<<"You chose number 3\n";
break;
case 4:
cout<<"You chose number 4\n";
break;
default:
cout<<"That's not 1,2,3 or 4!\n";
}
system(“pause”);
return 0;
}
On first inspection you'll find that it's virtually identical to the last example, except I've inserted a break
statement at the end of each case to "break" out of the switch block.
Now it should work as expected:
Pick a number from 1 to 4:
2
You chose number 2
Example 7.4:
#include <iostream>
using namespace std;
int main()
{
char c;
int store;
for(;;) {
cout<<"\nPress any key, Q to quit:";
cin>>c;
if(c == 'Q')
break;
else{
store = (int) c; // Convert character to corresponding ASCII value
cout<<store<<endl;
}
}
system("pause");
return 0;
} // Loop exits only when 'Q' is pressed
NOTE: It is almost always a good idea to have a default case in switch statements. If you have no other
need for the default, use it to test for the supposedly impossible case, and print out an error message;
this can be a tremendous aid in debugging.
Continue
This does the opposite of break; Instead of terminating the loop, it immediately loops again, skipping the
rest of the code. So let’s print the integers from 1 to 10, but this time we'll leave out printing 4 and 5.
You probably won't use continue very often but it's useful on the odd occasion.
Note: Before doing your lab exercises run the examples.
The aim of this lab is to introduce basics of Functions which is the most important aspect of C/C++
languages. In the next lab some other topics related to Functions will be covered.
Learning Objectivese:
Function Introduction
To Use Function Syntax, Examples
Outcomes:
Students should be able to use Functions.
In this example main function just calls the function named asterisks which just prints the line of ten
asterisks.
Example 8.1:
#include<iostream>
using namespace std;
void asteriks(); // prototype declaration
int main(){
asteriks(); // Function calling
system(“pause”);
return 0;
}
void asteriks(){ // Function definition
int i=0;
for(;i<10;i++)
cout<<"*";
}
Second line in the example is the prototype declaration of the function because before calling the
function it’s must that you should at least provide function prototype as given in example.
return_type function name(arguments separated by a comma);
Line 4 is the line which is calling the function.
asteriks() function in the previous example does not take any argument and does not return any thing
represented by empty braces() after function name and void before function name respectively.
After main the function definition of the function asterisks is given.
Lets go one step ahead, function asterisks (int a) with a single argument.
#include<iostream>
using namespace std;
void asteriks(int n); // prototype declaration
int main() {
asteriks(7); // Function calling
system(“pause”);
return 0; }
void asteriks(int num){ // Function definition
int i=0;
for(;i<num;i++)
cout<<"*"; }
This function would take an integer number as an argument and prints the no of asterisks equal to the
number given as argument to the function in straight line. As in example we have given 7 as an
argument while calling so it would print seven asterisks in line as 7 is passed to the function, int num
variable in function definition becomes equal to 7. As it is given in function prototype, compiler expects
function definition should take single argument which should be of integer data type. Due to this in
function calling you need to give an integer as argument (parameter) of a function.
Now an example of a function with two parameters.
Example 8.3:
#include<iostream>
using namespace std;
int add(int num1,int num2); // Function Prototype
int main(){
int s,a,b;
a=4;b=7;
s=add(a,b); // Function calling
cout<<s;
system("pause");
return 0;
}
int add(int num1,int num2 ){ // Function definition
int sum;
sum =num1+num2;
return sum;
}
This line begins the function definition. It tells us the type of the return value, the name of the function,
and a list of arguments used by the function. The arguments and their types are enclosed in brackets,
each pair separated by commas.
The body of the function is bounded by a set of curly brackets. Any variables declared here will be
treated as local unless specifically declared as static or extern types.
return sum;
On reaching a return statement, the control of the program returns to the calling function. Value of sum
is returned from the add function to the main (calling function) at.
s = add(a , b);
it would become s = (value returned from the add function which is sum);
If the final closing curly bracket in the add function’s definition is reached before any return value, then
the function will return automatically, any return value will then be meaningless.
Example 8.4:
Lets do another example of making a program using functions which will tell us whether the input
number is even or odd.
#include<iostream>
using namespace std;
int is_even(int n); // (Prototype declaration)
int main()
{
int number, test;
cout<<"Enter a number to test even or odd"<<endl;
cin>>number;
test = is_even(number); // (Function calling)
if(test==0)
cout<<"The number is odd"<<endl;
else
Function is_even checks whether the number provided to it is even or odd and returns 0 or 1 for even or
odd number respectively.
Second line in the above program is the prototype declaration of the function is_even used in the
program. As mentioned earlier compiler needs to know at least the name of the function before calling
it. Method to give name of the function is to give the prototype of function as written in the program
above the main() function.
Note: You cannot define the function inside another function, can only call another function from inside
another function.
int is_even(int n); ------prototype
can also be witten as int is_even (int);
It means to say that variable name of the parameter is not necessary in prototype.
Whereas line
test=is_even(number); // (Function calling)
is calling the function is_even and passing the number to the function, n in the function definition
becomes equal to value of number. After the is_even function returns, the control would be transfered
back to the main() function and test in the main() function would become equal to the value returned by
the is_even function which is then further used in the main function.
One more way to write the same example is
int main()
{
int number,test;
cout<<"Enter a number to test even or odd";
cin>>number;
test = is_even(number); //(Function calling)
if(test==0)
cout<<"The number is odd";
else
cout<<"The number is even";
system("pause");
return 0;
}
In this example what we have done is instead of giving prototype of the function before the main() just
give complete definition of the function. In this way there is no need of prototype definition. It would
work in the same way as previous one. Please try!!!!!!!
Compile and run this program.
Example 8.6:
#include<iostream>
using namespace std;
float avg(float num1, float num2, float num3); //(Prototype declaration)
int main()
{
float n1,n2,n3,result;
cout<<"Enter three number to find avg";
This program here takes three numbers from user in floating points, and send the numbers to the
function named avg( ).
In the definition part of the function the average calculated is saved in the variable average and is
returned by the returned function.
Learning Objectives:
To learn Function Call by Value
To Learn Function Call by Reference
To use Default values in parameters
Random Number generation
Outcomes:
Students should be able to Call Functions by value and by reference.
Students should be able to generate random numbers.
Example 9.2:
#include<iostream>
using namespace std;
void interchange(int,int);
int main()
{
int x=50, y=70;
interchange(x,y);
cout<<"x="<<x<<" and "<<"y="<<y<<endl;
system("pause");
return 0;
}
void interchange(int x1,int y1)
{
int z1; z1=x1; x1=y1; y1=z1;
cout<<"x1="<<x1<<" and "<<"y1="<<y1<<endl;;
}
Call by Reference:
If you are calling by reference it means that compiler will not create a local copy of the variable
which you are referencing to. It will get access to the memory where the variable saved. When you are
doing any operations with a referenced variable you can change the value of the variable.
Example 9.3:
#include<iostream>
using namespace std;
void interchange(int&, int&);
int main()
{
int x=50, y=70;
cout<<"before calling the function the values are"<<"x="<<x<<" and
y="<<y<<endl;
interchange(x,y);
cout<<"after calling the function the values are"<<"x="<<x<<" and
y="<<y<<endl;
system("pause");
return 0;
}
void interchange(int &x1,int &y1)
{
int z1; z1=x1; x1=y1; y1=z1;
}
Here the function is called by reference. In other words address is passed by using symbol “&”
and the value is accessed by using symbol “*”.
The main difference between them can be seen by analyzing the output of program1 and
program2.
The output of Example 2 that is call by value is
x1=70 y1=50
x=50 y=70
x1=70 y1=50
and again since no values are returned back and therefore original values of x and y as in main
function namely
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}
Output:
Previous=99, Next=101
int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
}
Output:
6
5
Example 9.6:
#include<iostream>
using namespace std;
int main()
{
int number;
for(int i=1; i<=10; i++)
{
number=rand();
cout<<number<<endl;
}
system("pause");
return 0;
}
Example 9.7:
#include<iostream>
using namespace std;
int main()
{
int number;
for(int i=1; i<=10; i++)
{
number=rand()%100;
cout<<number<<endl;
}
system("pause");
return 0;
}
srand( ) is another function to change the pattern of random numbers generation. So one can use
srand(time(NULL) ) to find different random number each time when program is executed. Remember
to #include <time.h> to enable your program to use the time function. The time(NULL) returns the
number of seconds of the current time since epoch.
Example 9.8:
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
srand(time(NULL));
int number;
for(int i=1; i<=10; i++)
{
number=rand();
cout<<number<<endl;
}
system("pause");
return 0;
}
int main()
{
srand(time(NULL));
int number;
for(int i=1; i<=10; i++)
{
number=rand()%100;
cout<<number<<endl;
}
system("pause");
return 0;
}
Learning Objectives:
Array definition
When to use Array
Array declaration
Array Initialization
Accessing Array elements
Copying Arrays
Outcomes:
Students should be able to understand and use arrays.
Example 10.1:
#include <iostream>
using namespace std;
int main()
{
int age;
age=23;
cout<< age;
return 0;
}
It is quite simple. The variable age is created at line (5) as int. A value is assigned to it. Finally, age is
printed to the screen.
age. 23
Declaration of Array
To declare an array in C++, the programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ];
Example 10.2:
#include <iostream>
using namespace std;
int main()
{
int age[4]; //declaration of Array
age[0]=23; //initialization of Array elements
age[1]=34;
age[2]=65;
age[3]=74;
return 0;
}
On line (5), an array of 4 int is created. Values are assigned to each variable in the array on line (6)
through line (9). In memory these are contiguous set of locations shown in following figure.
Age[0] age[1] age[2] age[3]
23 34 65 74
23 34 65 74
Int age[4]={0};
age[0] age[1] age[2] age[3]
0 0 0 0
For example, to store the value 75 in the third element of age , we could write the following statement:
age[2]=75; //note : array index start with 0 in c.
And, for example, to store the value of the third element of age to a variable called a, we could write:
int a=age[2];
Here’s another example of an array at work. This one, SALES, invites the user to enter a series of six
values representing widget sales for each day of the week (excluding Sunday), and then calculates the
average of these values. We use an array of type double so that monetary values can be entered.
Example 10.4:
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 6; //size of array
double sales[SIZE]; //array of 6 variables
cout << “Enter widget sales for 6 days\n”;
for(int j=0; j<SIZE; j++) //put figures in array
cin >> sales[j];
double total = 0;
for(j=0; j<SIZE; j++) //read figures from array
total += sales[j]; //to find total
double average = total / SIZE; // find average
cout << “Average = “ << average << endl;
return 0;
}
Copying arrays
Suppose that after filling our 4 element array with values, we need to copy that array to another array of
4 int ? Try
Example 10.5: this:
#include <iostream>
using namespace std;
int main()
{
int age[4];
int same_age[4];
int i=0;
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
for (;i<4;i++)
same_age[i]=age[i];
for (i=0;i<4;i++)
cout<<same_age[i];
return 0;
}
In the above program two arrays are created: age and same_age. Each element of the age array is
assigned a value. Then, in order to copy the four elements in age into the same_age array, we must do it
In this lab we will be discussing pointers in detail. This is one of the most important concepts in C++
language. Pointers are used everywhere in C++, so if you want to use the C++ language fully you have to
have a very good understanding of pointers. They have to become comfortable for you. To fully grasp
the concept of pointers all you need is the concept and practice of pointers.
Learning Objectives:
To understand Computer Memory and variable concept
Pointer Introduction
Pointer declaration
Reference and Dereference Operators
Pointer example and its explanation
Pointer Arithmetic’s
Sending Pointers as Arguments to Functions
Outcomes:
Students should be able to understand and use pointers and can perform basic pointer’s
Arithmetic.
Example 11.1
#include<iostream>
using namespace std;
int main()
{
float fl=3.14;
cout<<fl;
cin>>fl;
return 0;
}
At line (4) in the program above, the computer reserves memory for fl. Depending on the computer's
architecture, a float may require 2, 4, 8 or some other number of bytes. In our example, we'll assume
that a float requires 4 bytes.
Pointer:
In C++ a pointer is a variable that points to or references a memory location in which data is stored. A
pointer is a variable that points to another variable. This means that a pointer holds the memory
address of another variable. Put another way, the pointer does not hold a value in the traditional sense;
instead, it holds the address of another variable. A pointer "points to" that other variable by holding a
copy of its address. Because a pointer holds an address rather than a value, it has two parts. The pointer
itself holds the address and that address points to a value.
Pointer declaration:
A pointer is a variable that contains the memory location of another variable. The syntax is as shown
below. You start by specifying the type of data stored in the location identified by the pointer. The
asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the
variable.
Data_type *variable_name
Such a variable is called a pointer variable (for reasons which hopefully will become clearer a little later).
In C++ when we define a pointer variable we do so by preceding its name with an asterisk. In C++ we
also give our pointer a type which, in this case, refers to the type of data stored at the address we will be
storing in our pointer. For example, consider the variable declaration:
int *ptr;
int k;
ptr is the name of our variable (just as k is the name of our integer variable). The '*' informs the
compiler that we want a pointer variable, i.e. to set aside however many bytes is required to store an
address in memory. The int says that we intend to use our pointer variable to store the address of an
integer.
Referencing Operator
Suppose now that we want to store in ptr the address of our integer variable k. To do this we use the
unary & operator and write:
ptr = &k;
What the & operator does is retrieve the address of k, and copies that to the contents of our pointer ptr.
Now, ptr is said to "point to" k.
Dereferencing operator
The "dereferencing operator" is the asterisk and it is used as follows:
*ptr = 7;
This Listing will be very helpful in understanding the pointers. Understand it thoroughly how it works
and then proceed.
Example 11.2
#include<iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
cout<<"First Value is " << firstvalue<<endl;
cout<<"Second Value is " <<secondvalue<<endl;
return 0;
}
How it Works:
Here in this code we are trying to play with memory and address of our variables for the better
understanding of Pointers. On line number 5 we have two integer variables (i.e firstvalue and
secondvalue). Both are assigned values of 5 and 15 respectively. On line number 6 we have two integer
pointer variables (i.e p1 and p2). Both are assigned addresses of variables in line 5 firstvalue and
secondvalue respectively in line 7 and 8.
In line 9 we see that *p1 is assigned value 10. This means that 10 should be copied in the variable, which
is lying on an address to which p1 is pointing. We know that p1 is pointing to address of firstvalue. So
line 9 results in assigning firstvalue the value of 10.
In line 10 we encounter another assignment which says that value of variable pointed by p2 should be
replaced with the value of variable pointed by p1. So now secondvalue is assigned with value 10 as well.
Well the assignment in line 11 is a bit confusing but very simple, all this assignment is doing is that now
p1 is pointing to the same address as p2. So now we can say p1 and p2 are pointing at same address.
In line 12 we see that *p1 is assigned value 20. This means that 10 should be copied in the variable,
which is lying on an address to which p1 is pointing. We know that p1 is now pointing to address of
secondvalue because in last line we pointed p1 to the address being pointed by p2. So line 12 results in
assigning secondvalue the value of 20.
Now when we print the value of first value and second value it prints 10 for firstvalue and 20 for
secondvalue; which is right due to the reasons explained above.
The variable i now has four names: i, *p, *q and *r. There is no limit on the number of pointers that can
hold (and therefore point to) the same address.
y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;
C++ allows us to add integers to or subtract integers from pointers as well as to subtract one pointer
from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc.,
we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and
p1!=p2 are allowed.
When an integer is added to, or subtracted from, a pointer, the pointer is not simply incremented or
decremented by that integer, but by that integer times the size of the object to which the pointer refers.
The number of bytes depends on the object's data type.
1:#include<iostream>
2:using namespace std;
3: int main()
4: {
5:int *ptr1,*ptr2;
6:int a,b,x,y,z;
7:a=30;b=6;
8:ptr1=&a;
9:ptr2=&b;
10:x=*ptr1 + *ptr2 - 6;
11:y=6 - *ptr1 / *ptr2 +30;
How it Works:
This code explains all the rules related to arithematic of pointers. From line 1 to line 11, it is
simply adding, subtracting and like manipulating with the pointers and variables. After all the
manipulations and arithmetics it started printing values of pointers and other simple variables till
line 12.
ptr1 ptr2
At line 18 it adds 1 to ptr1. Mostly people think that this will change the address of the pointer,
but they are totally wrong. Remember pointer is pointing to an address. This addition does not
change the address of the pointer, infact it changes the value of the pointer (not the value of the
address pointer is pointing at.). ptr1 has the address of variable of variable a . So it adds 1 *4
Btytes = 4bytes in the address of a which is stored in ptr1. Where as ptr2 points at the same value
as before due to the assignment of line 19.
a b
30 0XF…
6
7864 7868 7872 7876 7880 7884 7888
ptr1 ptr2
Line 20 prints the same value as was printed by the Line 16, because values of the variable was
never changed, in fact ptr1’s value which was address of a was changed. Now Line 21 will print
the value stored in ptr1; which is address of memory 4 bytes ahead of variable a. Line 22 is
trying to print the value at address, ptr1 is now pointing to, which was never assigned any value.
int main( )
{
int a = 10, b = 20 ;
a = 20 b = 10
Note that this program manages to exchange the values of a and b using their addresses stored in x and
y.
Try on paper how this code works. Working of this code might be asked in Viva.
Learning Objectives:
What is HPC
Operating System of HPC
Applications of HPC
HPC System Specification in GIKI
How to use HPC for your CS101 Lab
Outcomes:
Students should be able to operate HPC.
Just like your desktop or laptop, your HPC cluster won’t run without software. Two of the most popular
choices in HPC are Linux (in all the many varieties) and Windows. The choice of operating system should
really be driven by the kinds of applications you need to run on your high performance computer. If you
are using Excel to run option calculations in parallel, you’ll want a Windows-based cluster; and so on
Linux currently dominates HPC installations due to HPC’s legacy in supercomputing, large scale
machines, and UNIX i.e. As HPC is used for computationally expensive tasks (Just as Supercomputers) so
Linux is used over them as Windows Based systems are Slow due to Graphical User Interfaces.
Applications of HPC
Structural Mechanics: - Computation has played a central role in mechanics for more than 30 years.
Current HPC systems are being used to address challenging Problems throughout the field. Some of the
Problems in which HPC is used are;
Computational biology: - In biology today, HPC is used for a variety of problems. Some of them
are;
1. The human Proteome Project recently finished rough predictions for all the proteins in the
human genome in a single year- a job that would have taken a century on the available
laboratory cluster.
2. Structure of bio-molecules ( Protein folding, molecular docking)
3. Sequence matching for similarity searching in biological databases
4. Simulation of biological phenomena (vascular flows, impulse propagation in biological nerve
tissue, etc).
Commercial Applications: - the emerging wave of HPC-enabled data-intensive solutions can help
companies, government organizations, and others tackle a wide range of previously intractable
1. Fraud Detection
2. Transaction processing
3. Data mining
4. Scalable Web and Database Servers etc
Total CPUs: 160 cores using latest 16C AMD Opteron Processors
Total main memory: 640 GB of 1600MHz
Total GPUs: 1024 cores (Tesla 2090
system)
Connectivity: 10GB Ethernet switch
Hard disks: 1.8TB with 15k rpm (speed)
1. Double click on the Putty (A Client Software for remote Login) on your Desktop, Enter the
Highlighted IP Address i.e. 192.168.100.21 and then click Open (Encircled in the Figure).
To write your first C++ Program, We have to type our code in the editor.
5. When you press enter the following screen appears, which is the editor window:
Type Your Program in the editor (Nano editor)
The above command compiles and creates the output file myfirst
You can see that the output appears after entering the ./myfirst
Make a Simple Calculator which does basic Arithmetic using NANO Editor
Introduction:
An open ended lab is where students are given the freedom to develop their own critical thinking to
solve a given problem, instead of merely following the preset guidelines from the lab manual or a book.
Working on Open-ended pushes students to develop critical thinking and come up with their own
solutions. An important aspect of open ended lab that a given problem may be solved in different ways,
therefore, students are encouraged to investigate different methods and justify the adopted approach.
Lab Instructor will have a debriefing session at the end of the open ended lab. The instructor may drop
pointers for the students and perhaps talk about the difficulties that the student faced while solving the
problem. This may be in the form of a lecture or a discussion and emphasis on essential learning points.
OEL Problem 1: The problem statement will be provided by the instructor before the start of the open
ended lab.
Aims: To use the decision control structures, loops, arrays, pointers and functions to design and
implement the given problem (Provided by the instructor).
Expected outcomes:
Problem Analysis
Proposed methodologies
Algorithm to solve the problem
Detailed design flow chart
Demonstration of programming skills.
Source code.
[1] http://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm
[4] http://www.cplusplus.com/doc/tutorial/functions/
[5] http://www.functionx.com/cpp/Lesson05.htm
[6] http://www.macs.hw.ac.uk/~pjbk/pathways/cpp1/node176.html
[7] http://programmers.stackexchange.com/questions/157739/2-dimensional-arrays-in-c
GRADING CRITERIA:
CLO/PLO MAPPING:
Lab1 and Lab 2 are mapped to CLO1, which states that the student should have basic
software & hardware understanding.
Lab3 to Lab 12 are mapped to CLO 2, which states that the student should be able to
apply fundamental concepts of computer programming using mathematical concepts
and operations.
Lab 13 is mapped to CLO 3, according to which a student should be able to analyze and
design simple modular program with elementary constructs of a programming language.
All the labs are mapped to PLO 1, which states that a student is expected to show
guided response for all the programming concepts..