cs
cs
CS101L
Lab Manual
2023
Contents
I. Table of Contents ............................................................................................................................. ...................... 2
II. Lab Outline ................................................................................................................. ........................................... 8
III. System Requirements ......................................................................................................... .................................. 10
IV. Evaluation Rubrics .......................................................................................................... ..................................... 11
V. Instruction For Students .................................................................................................... .................................... 12
Lab # 04 Switch statement, case, break statement, default, for loop. ................................................................64
Example: 4.1.......................................................................................................................................................65
Example: 4.2.......................................................................................................................................................66
Example: 4.3.......................................................................................................................................................67
Example: 4.4.......................................................................................................................................................68
Which Loop should I use? ...................................................................................................................................68
Example 4.5: .......................................................................................................................................................69
Common Error ....................................................................................................................................................69
4.1 Practice Problem: ..........................................................................................................................................69
4.2 Problem 02....................................................................................................................................................70
4.3 Problem 03....................................................................................................................................................72
Lab Outline
This course will introduce you to the field of computer science and the fundamentals of computer programming. CS101 is specifically
designed for students with no prior programming experience and touches upon a variety of fundamental topics. This course uses C++
programming platform to understand the principles of basic computer language. We do this by demonstrating C++ primitive data types,
relational operators, logical operators, control statements, iterative statements, arrays, recursion, pointers, debugging, exception handling.
By the end of the course, you will understand the basics of computer science and the C++ programming language. The principles you learn
here will be developed further as you progress through the computer science discipline.
Mapping of CLOs and PLOs
Course Learning
Sr. No Outcomes+ PLOs* Blooms Taxonomy
Project 5%
Final Exam 30%
VIII
CS101L - Introduction to Computing and AI Lab
Lecture Breakdown
Lab Contents/Topics
Introduction to C++ compiler and Installation guide, Basics of a C++ program, Algorithm Design, Data Types,
Lab#01:
Variables, Inputs/Outputs and Arithmetic Operators
Control Structures I - Relational Operators, Logical Operators, If else, Multiple IF else, Nested if else
Lab#02:
User defined Functions I– Predefined Functions, User-defined Functions, Value Returning Functions
Lab#05:
User defined Functions II - Void Functions, Value Parameters, Reference Variables as parameters, Pass by
Lab#06: Value and Pass by reference parameters
User Defined Functions III – Reference parameter and value-returning functions, Scope of an identifier,
Global variables, named constants and side effects, Static and automatic variables, Function overloading,
Default parameters.
Lab#07:
Arrays & Strings – Arrays (Accessing array components, Processing one-dimensional arrays, array index out
Lab#08: of bound, array initialization during declaration, partial initialization of arrays during declaration, some
restrictions on array processing, arrays as parameters to functions, constant arrays as formal parameters, base
address of an array and array in computer memory, functions cannot return a value of type array, other ways to
declare arrays), Searching an array for a specific item, C-Strings (Character Arrays), Two and Multi-
Dimensional Arrays.
Lab#09: Recursion
Lab#10: Pointers, Static Arrays, Dynamic Arrays, Two-Dimensional Arrays using Pointers.
Final Exam
CS101L - Introduction to Computing and AI Lab
HARDWARE REQUIREMENT
• Core i3 or Above
• 2 GB RAM
• 20 GB HDD
SOFTWARE REQUIREMENT
• Visual Studio
X
CS101L - Introduction to Computing and AI Lab
Error/exception Handling:
* Runs without exception: 1
* Interactive menu: 0.5
* Displays proper messages/operations clearly: 0.5
Correctness:
* Accurate methodology 2
* All tasks are done: 1
* Passes all test cases:
XI
CS101L - Introduction to Computing and AI Lab
XII
CS101L - Introduction to Computing and AI Lab
Lab # 01
Learning Objectives
❖
To learn the basic concepts of Generative AI
❖
Creative Writing with Generative AI
❖
Large Language Model (LLM’s), Code Generation and Art Creation
❖
Installation of IDE ( Visual Studio)
❖
Introduction to Algorithms
Outcomes:
❖
❖
Able to understand the concept of Generative AI
❖
Should be able to write prompts and get the desired results
Get familiar with IDE
CS101L - Introduction to Computing and AI Lab
1.1 GENERATIVE AI
Generative AI refers to a subset of artificial intelligence techniques and models that focus on generating new data or
content that is similar to existing data. These models learn patterns and structures from a given dataset and use that
knowledge to create new, original content.
1. Prompt Generation:
In prompt generation, user provides a general topic or theme, and AI suggests creative and unique prompts.
Generative models like GPT-3 are commonly used to generate writing prompts.
2. Idea Expansion:
Generative AI can be used to expand and explain basic ideas given by the user.
3. Character and World Building:
When creating characters or fictional worlds, users can generate backstories, personalities, and
characteristics using generative AI.
4. Dialogue Generation:
Generative AI can be used to create natural-sounding dialogues between characters. In this way users can
experiment with different tones and find the right voice for each character.
5. Descriptive Writing:
In descriptive writing, users provide a basic description of settings, scenes, or emotions to AI and it helps
them to expand and enhance the writing.
6. Poetry:
Generative AI can be used to create poetry by generating lines, stanzas, or even entire poems.
7. Collaboration:
Users can work with AI as a co-writer. They can write a paragraph or a few sentences, and then have the AI
continue the text. In this way, unexpected and creative ideas can be generated.
8. Creative Prompts for writer’s block:
Generative AI can be used to generate random ideas or sentences. In this way, users’ creativity can be
enhanced, and new ideas can be generated.
9. Editing and Rewriting:
Users can use Generative AI to suggest alternative phrases, sentence structures, or ways to rephrase their
writing and improve the flow and style of their work.
10. Generating short stories:
Generative AI can be used to continue the stories from a starting point gives by users. In this way, it can
create short stories.
In this experiment, we shall use Generative AI for Content writing and Summarization.
We can use Generative AI for content writing. For this, we can give prompts to a tool like GPT-3, and it creates
content.
We can use Generative AI for precis writing by providing it the original passage and number of words required in
precis to tools such as Chat GPT.
In the example below, we shall write precis with a word limit of 48 words. The original word count is 124.
TASK 01:
Create a prompt for large language Model, such as ChatGPT, to describe how large language models works. Ask at
least three follow up questions based on output. Provide the Prompts and outputs from the conversation.
TASK 02:
Create A Prompt for large language Model, such as Chat GPT, that asks it to perform an instruction other
than answering a question. For example, ask ChatGPT to create a meal plan. plan a trip. create a recipe, or
help you diagnose a problem. Provide the Prompts and outputs from the conversation.
CS101L - Introduction to Computing and AI Lab
Prompt
CS101L - Introduction to Computing and AI Lab
DATA Generated
Task 03
Create A Prompt for large language Model, such as Chat GPT, that Introduces new information since
2021. Please only us public information. The prompt should require the large language model to perform
a task, other than answering a question, with the information. Please provide your prompt additional
information and output.
CS101L - Introduction to Computing and AI Lab
Selection Sort
Sorting:
Sorting refers to the process of arranging a collection of elements (such as an array or a list) in a specific
order, typically in ascending or descending order based on a certain key or comparison criteria. Sorting is
a fundamental operation in computer science and is used extensively in various applications, such as
databases, search algorithms, and data analysis.
Selection Sort:
The time complexity of selection sort is O(n^2) i.e., Quadratic Time Complexity.
We shall use Chat GPT to generate code for Selection sort in python programming language.
import time.
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
import time
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
for _ in range(num_iterations):
start_time = time.time()
selection_sort(numbers.copy())
end_time = time.time()
execution_time = end_time - start_time
total_execution_time += execution_time
Output:
Sorted array: [1, 2, 5, 6, 7, 8, 9]
Average selection sort execution time: 0.00000644 seconds
Problem:
The execution time of generated code is longer compared to standard code.
There is not a 100% guarantee of the accuracy of its responses.
ChatGPT can give ambiguous responses when its codebase does not contain enough information on the
requested topic.
Therefore, we should not rely entirely on ChatGPT-generated, instead we can seek assistance from these
LLMs.
Task 01.
Create a Prompt for code generation of programming concepts. Provide the Prompt and output.
CS101L - Introduction to Computing and AI Lab
1. Visual Art:
Generative models can be trained to create paintings, drawings, 3D art, sculptures, architectural
designs etc. They can transform images using artistic styles, thus creating unique visual
interpretations by transferring the style of one image onto another. They can even mimic the
style of famous artists. Tools like Stable Diffusion Web are commonly used for Visual Art
generation.
2. Music Composition:
Generative AI can compose melodies, harmonies, and even chord progressions. It can generate
music in different genres and styles, offering artists and musicians to come up with creative
ideas and to experiment beyond their usual boundaries.
3. Literature and Poetry:
Generative AI models like GPT-3 can help create poetry, short stories, dialogues, and more
based on given prompts. Writers can co-create content with AI, resulting in unexpected and
intriguing combinations of human and machine creativity.
4. Fashion and Design:
Generative AI can offer suggestions for interior design layouts, furniture arrangements, colour
schemes and can also generate new fashion designs, patterns, and 3D models of clothing items.
5. Digital Art and Animation:
Generative AI can automate the process of creating animations, visual effects, digital
illustrations, characters, and scenes, helping artists bring their ideas to life and enhancing the
efficiency of animation production.
6. Interactive Art:
Generative AI can generate virtual worlds, landscapes, and interactive elements. Moreover, AI
powered interactive installations can respond to user input or environment factors, creating
dynamic and evolving art experiences.
In this experiment, we shall use Generative AI for Art creation.
Mona Lisa:
The Mona Lisa is a half-length portrait painting by of Italian Artist ‘Leonardo da Vinci’. The painting has
been definitively identified to depict Italian noblewoman Lisa del Giocondo. It has been described as the
best known, the most visited, the most written about, the most sung about, and the most parodied work
of art in the world.
CS101L - Introduction to Computing and AI Lab
1.6 Algorithm
An algorithm is a procedure having well defined steps for solving a particular problem. Algorithms
are a finite set of logic or instructions, written in order for accomplish the certain predefined task. It
is not the complete program or code, it is just a solution (logic) of a problem, which can be
represented either as an informal description using a Flowchart or Pseudo code.
The performance of algorithm is measured based on following properties:
Time complexity: It is a way of representing the amount of time needed by a program to run to
completion.
Space complexity: It is the amount of memory space required by an algorithm, during the course of its
execution. Space complexity is required in situations when limited memory is available and for the
multiuser system.
Each algorithm must have:
Specification: Description of the computational procedure.
Output: An algorithm must have 1 or a well-defined output and should match with the desired output.
2. Next, review the standard build process for a Visual Studio project.
3. If C++ is not an already installed language in Visual Studio, you need to install Desktop
development with C++ from the Visual Studio Installer.
4. After installing the Desktop development with the C++ workload, open Visual Studio 2019, and
click Create a new project to start creating your HelloWorld project.
CS101L - Introduction to Computing and AI Lab
5. Select Language as C++, Platform as Windows, and Project Type as Console. Then select
Console App and click Next.
#include <iostream>
int main()
{
std::cout << "Hello World”! ;
return 0;
}
CS101L - Introduction to Computing and AI Lab
9. Compile and run your project by clicking the green triangle in the tool bar (Local Windows
Debugger) or press F5 to Run in Debug Mode. Use Ctrl+F5 to run in Release Mode. Visual
Studio allows single-click for build and debugging. Click Yes to build the project.
10. You can see “Hello World!” in the console window.
CS101L - Introduction to Computing and AI Lab
Learning Objectives:
❖
Variable Types
❖
Declaring Variables
❖
Arithmetic Operators
❖
Comments
❖
input/output in C++
❖
Comparison/Relational Operators
❖
Logical Operators
❖
If Statement
❖
If - else statement
❖
else - if Statement
❖
Introduction to Switch and Case Statement
❖
General Syntax of Switch and Case Statements
❖
Use of Break Statement
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.
❖
Students should be able to use all types of C++ operators
❖
Students should be able to use if, if-else and else-if statements
❖ Students should be able to use Switch statement, Case statement, Break statement
CS101L - Introduction to Computing and AI Lab
What can you name your variables? In general, variable names can be composed of letters, numbers,
and underscores (_).
Keywords: C++ reserves certain names which have special meaning to the language, and you are not allowed to
use any of these keywords as variables names. Some examples of C++ keywords are int, for, else, and class.
You can, however, use keywords in the middle of a variable name, such as "foreign" or "classical".
• Character types: They can represent a single character, such as 'A' or '$'. The most
basic type is char, which is a one-byte character. Other types are also provided for
wider characters.
• Numerical integer types: They can store a whole number value, such as 7 or 1024.
They exist in a variety of sizes, and can either be signed or unsigned, depending on
whether they support negative values or not.
• Floating-point types: They can represent real values, such as 3.14 or 0.01, with
different levels of precision, depending on which of the three floating-point types is used.
• Boolean type: The boolean type, known in C++ as bool, can only represent one of two
states, true or false.
CS101L - Introduction to Computing and AI Lab
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.
CS101L - Introduction to Computing and AI Lab
Example 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.
Code:
int main()
{
Int myAge = 21;
cout<<"My age is “
<<myAge<<“years”;
system(“pause”);
return 0;
}
Code:
my first
string #include
<iostream>
#include
<string> using
namespace std;
int main ()
{
string mystring;
mystring = "This is a
string"; cout << mystring;
return 0;
}
CS101L - Introduction to Computing and AI Lab
As you can see in the previous example, strings can be initialized with any valid string literal, just like
numerical type variables can be initialized to any valid numerical literal. As with fundamental types, all
initialization formats are valid with strings:
Strings can also perform all the other basic operations that fundamental data types can, like being
declared without an initial value and change its value during execution:
Example:
my first string
#include <iostream> 22
#include <string> using
namespace std;
int main ()
{
string mystring;
mystring = "This is the initial string content"; cout
<< mystring << endl;
mystring = "This is a different string content"; cout
mystring << endl;
return 0;
}
22
22
CS101L - Introduction to Computing and AI Lab
Note: inserting the endl manipulator ends the line (printing a newline character and flushing the stream).
The string class is a compound type. As you can see in the example above, compound types are used in
the same way as fundamental types: the same syntax is used to declare variables and to initialize them.
The comment characters (/*, */, and //) have no special meaning within a character constant, string literal,
or comment.
23
CS101L - Introduction to Computing and AI Lab
Example:
int main()
/*Initializing the
variables
*/
a=10; ch=’b’;
/*Printing the
variables
*/
system(“pause”);
return 0;
Output:
The value of ch is b
The value of a is 10
24
CS101L - Introduction to Computing and AI Lab
Notice the use of “endl” at the end of the cout statements. It simply adds a carriage return which ends the
current line.
cin>>roll_number>>MyAge;
(Assume that roll_number and MyAge have been declared beforehand!). If I entered: 1 2 and pressed
Enter, 1 would get assigned to roll_number, and 2 would get assigned to MyAge. But if I entered 1, 2 and
pressed Enter, roll_number would equal 1, but MyAge won't get assigned 2 because cin was not
expecting a comma in the input string.
Now let us look at a way to get input from the user and store it in variables. Consider the following program:
CS101L - Introduction to Computing and AI Lab
Example:
int main()
{
inta,b;
cout<<“Enter value of a: \n“;
cin>>a;
cout<<“Enter value of b: \n“;
cin>>b;
system(“pause”);
return 0;
Output:
Enter value of a:
4
Enter value of b:
7
The value of a is: 4
The value of b is: 7
Enter new value for both separated by a space:
2 5
New values are: 2 5
Multiplication, addition and subtraction are the simplest to use. Division is also easy, but watch
out for the truncation of an int divided by an int! Now, the one that confuses novices is the
modulus operator, sometimes known as the remainder operator.
To keep things simple, a%b returns the REMAINDER that occurs after performing a/b. For this
operator, a and b MUST be integers!
For example, 6%3 returns 0 because 3goes into 6 EXACTLY. Similarly, 4%4, 8%2 and 16%8 all
return
0. So why does 3%4 return 3? Picture it this way: you have 3 holes to fill, but you can only fill 4
holes at a time. You can't fill a group of 4 holes, therefore the 3 holes you had are still empty.
Similar story for 7%4 because you can fill in one group of 4 but still have 3 holes remaining.
CS101L - Introduction to Computing and AI Lab
Example:
int main()
inta,b;
int sum;
cin>>a;
cin>>b;
sum=a+b;
cout<<“Sum: ”<<sum<<endl;
return 0;
Output:
Enter value of a:
3
Enter value of b:
6
Sum: 9
Solution:
#include <iostream>
#include <iomanip>
int main()
{
double userNumber;
return 0;
}
Write a C++ program that prompts the user to input the elapsed time for an event in seconds. The
program then outputs the elapsed time in hours, minutes, and seconds. (For example, if the elapsed
time is 9630 seconds, then the output is 2:40:30.)
Solution:
#include <iostream>
int main()
{
int secondsElapsed, hours, minutes, seconds;
cout << hours << ":" << minutes << ":" << seconds << endl;
return 0;
}
CS101L - Introduction to Computing and AI Lab
Comparison/Relational Operators
Operator Syntax
name
Equal to a == b
Logical Operators
Operator Syntax
name
Logical !a
negation
(NOT)
Logical AND a && b
Logical OR a || b
The if statement controls conditional branching. The body of an if statement is executed if the value of the
expression/condition specified in the if statement is true. The syntax of the if statement is as follows:
Syntax:
if(expression)
{
Block of statement;
}
Example: 1
Write a program in which it takes a number from keyboard as an input and if the number is greater
than 100 it prints “The number is greater than hundred”.
#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;
}
if (number<100)
{
cout<< “The number is greater than 100\n”;
cout<< “No doubt that the number is greater than 100”;
}
Note we did not use curly brackets ‘{ }’for body of if () because it did not include multiple statements
(block of statements). If it includes multiple statements, then it would have been something like this.
CS101L - Introduction to Computing and AI Lab
if-else statement is similar to if with the addition of else statement. If the condition is false in if then
its body will be skipped and the else statement’s body will be executed.
Syntax:
if (expression)
{
else
{
Block of statement;
}
Block of statement;
}
Example: 2
Write a program in which it takes two numbers from keyboard as input and subtract larger number
from smaller.
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
CS101L - Introduction to Computing and AI Lab
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;
}
Example: 3
Write a program which take a number from keyboard and checks the number whether that number is
less than 100 ornot if that number is lessthan100 than check that is it less than 50 or not.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
CS101L - Introduction to Computing and AI Lab
{
int number ;
cout << “Enter an integer\n”; cin
>>number; if ( number <100 )
{
cout<< “Yes the number is less
than 100”; if ( number <50)
{
cout<< “ and number is also less than 50”;
}
else
{
cout<< “ but the number is not less than 50”;
}
}
else
cout<< “No the number is not less than
100”; 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 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.
CS101L - Introduction to Computing and AI Lab
Syntax:
if (expression)
{
Block of statement;
}
else if (expression)
{
Block of statement
}
else if (expression)
{
Block of statement;
}
. . // you can add as many else-if statements as many you need
..
..
else
{
Block of statement
}
Example: 4
Write a program which takes marks as input and shows the output as follows:
CS101L - Introduction to Computing and AI Lab
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int marks;
cout<< “Enter an marks\n”;
cin >> marks ;
if (marks >= 75)
cout<< "Passed: Grade A\n";
else if (marks >= 60)
cout<< "Passed: Grade B\n";
else if (marks >= 45)
cout<< "Passed: Grade C\n";
else
cout<< "Failed\n";
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.
CS101L - Introduction to Computing and AI Lab
Example: 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
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int marks;
39
CS101L - Introduction to Computing and AI Lab
getch();
return 0;
}
In the 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.
Example 6
#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 choose number 1\n”;
case 2:
cout<<”You choose number 2\n”;
case 3:
cout<<”You choose number 3\n”;
case 4:
cout<<”You choose number 4\n”;
default:
cout<<”That’s not 1, 2, 3 or 4\n”;
}
system(“pause”);
return 0;
}
CS101L - Introduction to Computing and AI Lab
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...
The break statement terminates the execution of the nearest enclosing do, for, switch, or while
statement in which it appears. Control passes to the statement that follows the terminated statement.
43
CS101L - Introduction to Computing and AI Lab
Example: 7
#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 choose number 1\n”;
break;
case 2:
cout<<”You choose number 2\n”;
break;
case 3:
cout<<”You choose number 3\n”;
break;
case 4:
cout<<”You choose number 4\n”;
break;
default:
cout<<”That’s not 1, 2, 3 or 4\n”;
}
system (“pause”);
return 0;
}
4
CS101L - Introduction to Computing and AI Lab
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:
Example: 8
#include<iostream> 45
using namespace std;
int main()
{
char grade;
cout<<"Enter your grade: ";
cin>>grade;
switch(grade)
{
case'A':
cout <<"Your average must be between 90 - 100"
<<endl;
break;
case'B':
cout <<"Your average must be between 80 - 89"
<<endl;
break;
case'C':
cout<<"Your average must be between 70 - 79"
CS101L - Introduction to Computing and AI Lab
endl;
break;
case'D':
cout<<"Your average must be between 60 -
69" <<endl;
break;
default:
cout<<"Your average must be below 60" << endl;
}
system("pause");
return 0;
}
#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;
46
CS101L - Introduction to Computing and AI Lab
else
{
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.
4
CS101L - Introduction to Computing and AI Lab
Solution:
#include<iostream>
using namespace std;
int main()
{
cout<<"***************Select Deals***************\n";
cout<<"1. Chicken BBQ\n";
cout<<"2. Mayo garlic fries\n";
cout<<"3. Chicken burger\n";
cout<<"4. Beef Burger\n";
int op;
cout<<"enter your favorite meal\n";
cin>>op;
int cbb=400;
int mf=700;
int cb=300;
int bb=600;
int amt;
if(op==1)
{
cout<<"How many chicken BBq platter do you want??";
cin>>amt;
if (amt>2){
cbb=cbb-(cbb*.25);
amt=amt*cbb;
amt=amt-(amt*.10);
}
else{
cbb=cbb-(cbb*.25);
amt=amt*cbb;
}
cout<<"YOur bill is: "<<amt<<endl;
}
CS101L - Introduction to Computing and AI Lab
else if(op==2)
{
cout<<"How many fries platter do you want??";
cin>>amt;
mf=mf-(mf*.10);
amt=amt*mf;
cout<<"YOur bill is: "<<amt<<endl;
}
else if(op==3)
{
cout<<"How many chicken burger do you want??";
cin>>amt;
cb=cb-(cb*.20);
amt=amt*cb;
cout<<"YOur bill is: "<<amt<<endl;
}
else if(op==4)
{
cout<<"How many Beef burger do you want??";
cin>>amt;
bb=bb-(bb*.15);
amt=amt*bb;
cout<<"YOur bill is: "<<amt<<endl;
}
else
cout<<"Your entered option is not available please try again\n";
}
50
CS101L - Introduction to Computing and AI Lab
Lab#03
Control Structures II
3.1 Loop
Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block
of code is one of the most basic but useful tasks in programming -- many programs or websites that
produce extremely complex output are really only executing a single task many times. Now, think
about what this means: a loop lets you write a very simple statement to produce a significantly greater
result simply by repetition.
51
CS101L - Introduction to Computing and AI Lab
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.
Flow Chart of While Loop
Example 3.1 52
Write a program using while loop who print the values from 10 to 1.
#include <iostream>
using namespace std;
int main()
{
int i = 10;
while ( i > 0 )
{
cout<<i; cout<<”\n”;
i = i -1;
}
system(“pause”);
CS101L - Introduction to Computing and AI Lab
return 0;
}
10
9
8
7
6
5
4
3
2
1
53
Example 3.2:
Print Numbers from 1 to 10 using a while loop
#include <iostream>
using namespace std;
int main()
{
int counter = 1;
while (counter <= 10)
{
CS101L - Introduction to Computing and AI Lab
cout<<counter;
cout<<”\n”;
counter++;
}
system(“pause”);
return 0;
}
Example 3.3:
Printing the numbers you entered using a while loop
#include <iostream>
using namespace std;
int main()
{
int flag;
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”);
54
CS101L - Introduction to Computing and AI Lab
return 0;}
Nested While
Example 3.4:
Write a program who prints asterisk sign (*) in such a way using nested while loops
**************
*************
************
***********
**********
*********
********
*******
******
*****
****
***
**
*
#include <iostream>
using namespace std;
int main()
{
int i = 15, j;
while (i>0)
{
j=j-1;
while (j>0)
{
cout<<“*”;
55
CS101L - Introduction to Computing and AI Lab
j=j-1;
}
cout<<“\n”;
i=i-1;
}
system(“pause”);
return 0;
}
Example 3.5
A program to show the nested while loop
#include <iostream>
using namespace std;
int main()
{
//variable for counter
int i = 1; j;
//outer loop, execute this first …
//for every i iteration, execute the inner loop
while(i<=9)
{
cout << i;
//then execute inner loop with loop index j,
//the initial value of j is i-1
j=j-1;
while(j<0)
{
cout<<”==”<<j;
//decrement j by 1 until j>0, i-e j=1
j=j-1;
}
}
return 0;
}
Output:
56
CS101L - Introduction to Computing and AI Lab
Example 3.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
57
CS101L - Introduction to Computing and AI Lab
GIKI admin opens a joint account for their employees (Assistant professors, lecturers and Engineers)
with starting amount of 50,000. Any employee in case of emergency in need of money can utilize the
account and draw certain amount from the account i-e For Assistant professors its 25,000-maximum
limit, for lecturers its 20,000 and for engineers its 10,000. Design a transaction system for the admin
which applies all the checks (of maximum limit) on account and perform transactions. System should
detect invalid inputs and display error messages.
Solution: 58
#include<iostream>
using namespace std;
int main()
{
int money=50000;
char op;
int m;
int t=1;
cout<<"Welcome to giki joint account\n";
cout<<"Enter options for following profession\n";
cout<<"A. Assistant Professor\n";
cout<<"B.Lecturer\n";
cout<<"C. Engineer\n";
while(t!=0)
{
cout<<"\nEnter your profession\n";
cin>>op;
if(op=='A')
{
cout<<"Enter money you want to transact\n";
cin>>m;
if(m<=25000)
{
money=money-m;
cout<<"transaction successful\n";
cout<<"Amount left in account\n";
cout<<money;
CS101L - Introduction to Computing and AI Lab
}
else
if(op=='B')
{
cout<<"Enter money you want to transact\n";
cin>>m;
if(m<=20000)
{
money=money-m;
cout<<"transaction successful\n";
cout<<"Amount left in account\n";
cout<<money;
}
}
else
if(op=='C')
{
cout<<"Enter money you want to transact\n";
cin>>m;
if(m<=10000)
{
money=money-m;
cout<<"transaction successful\n";
cout<<"Amount left in account\n";
cout<<money;
}
}
else{
cout<<"Option entered is wrong\n";
}
cout<<"Want to continue\n";
cin>>t;
}
}
}
59
CS101L - Introduction to Computing and AI Lab
Customer should be able to select items from menu as well as their amount (how much they want to
order each item). Wrong inputs should be detected and error message should be displayed in case of
wrong input. Bill should be displayed as well on the screen of the robot when customer is done with
order. Write a program for above scenario.
Solution:
#include<iostream>
using namespace std;
int main()
{
int t=1;
int a1=500;
int a2=200;
int a3=50;
int a4=1200;
int amt=1;
int op;
int amount=0;
do
{
cout<<"*******Shanley Hotel Menu******\n";
cout<<"1. Kabab ------- 500 WITH 3 PIECES\n";
cout<<"2.Rice with BBq ---- 200 PER PLATTER\n";
cout<<"3.Drinks --- 50 each\n";
cout<<"4. mutton Karahi ---- 1200\n";
cout<<"Select your food items";
60
CS101L - Introduction to Computing and AI Lab
cin>>op;
if(op==1)
{
cout<<"How many servings\n";
cin>>amt;
amount=amount+a1*amt;
}
else
if(op==2)
{
cout<<"How many servings\n";
cin>>amt;
amount=amount+a2*amt;
}
else
if(op==3)
{
cout<<"How many servings\n";
cin>>amt;
amount=amount+a3*amt;
}
else
if(op==4)
{
cout<<"How many servings\n";
cin>>amt;
amount=amount+a4*amt;
}
else{
cout<<"Try again!! Wrong input\n";
}
61
CS101L - Introduction to Computing and AI Lab
62
CS101L - Introduction to Computing and AI Lab
Lab#04
Control Structures II
The aims of this lab are to cover Control Structures of C++.
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 while, nested while and do while loop loops.
➢
Students should be able to use For loop, Nested for Loop and differentiate them.
63
CS101L - Introduction to Computing and AI Lab
• The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as
long as semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute, and flow of control jumps to the next
statement just after the for loop.
• After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
• The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After
the condition becomes false, the for loop terminates.
Flow Diagram:
64
CS101L - Introduction to Computing and AI Lab
Example: 4.1
#include <iostream>
using namespace std;
int main ()
{
// for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout<< "value of a: " << a <<endl;
65
CS101L - Introduction to Computing and AI Lab
}
return 0;
system(“pause”);
}
Example: 4.2
#include<iostream>
using namespace std;
int main()
{
int x;
for ( x=5; x <= 50; x = x+5 )
{
Output:
66
CS101L - Introduction to Computing and AI Lab
Can you modify the above program that counts from 50 to 5 with decrements of 5?
Example: 4.3
Rectangle comprised of x’s:
for (int rows = 0; rows < 4; rows++)
{
for (int col = 0; col < 12; col++)
{
cout<<”x”;
}
}
67
CS101L - Introduction to Computing and AI Lab
xxxxxxxxxxxx
Example: 4.4
Missing init statement in for loop
#include<iostream>
using namespace std;
int main()
{
int x = 0;
for ( ; x < 10; x++ )
{
cout<<”\n”<<x;
}
system ("pause");
return 0;
}
Example 4.5:
The following program fragments print the numbers 1 - 20. Compare the different looping procedures.
Remember, there are always MANY possible ways to prepare code!
do-while:
int ctr = 1;
do
{
cout << ctr++ << “\n”;
} while
(ctr<=20); for:
int ctr;
for (ctr = 1; ctr <=20; ctr++)
{
Cout<<ctr<<”\n”;
}
while:
int ctr = 1;
while
(ctr<=20)
{
Cout<<ctr++<<”\n”;
}
Common Error
If you wish the body of a for loop to be executed, DO NOT put a semicolon after the for's
parentheses. Doing so will cause the for statement to execute only the counting portion of the loop,
creating the illusion of a timing loop. The body of the loop will never be executed.
Semicolons are required inside the parentheses of the for loop. The for loop is the only
statement that requires such semicolon placement.
Solution:
#include <iostream>
#include <cstdlib>
int main()
{
int inputNumber, sum, individualNumber;
cin >> inputNumber;
do {
individualNumber = inputNumber % 10; //Extract the last digit of the
number sum += individualNumber;
inputNumber = inputNumber / 10; //Remove the last
digit } while (inputNumber > 0);
cout << "The sum of the individual numbers is: " << sum << endl;
return 0;
}
4.2 Problem 02
To make telephone numbers easier to remember, some companies use letters to show their telephone
number. For example, using letters, the telephone number 438-5626 can be shown as GET LOAN. In
some cases, to make a telephone number meaningful, companies might use more than seven letters.
For example, 225-5466 can be displayed as CALL HOME, which uses eight letters. Write a program
that prompts the user to enter a telephone number expressed in letters and outputs the corresponding
telephone number in digits.
If the user enters more than seven letters, then process only the first seven letters. Also output the
– (hyphen) after the third digit. Allow the user to use both uppercase and lowercase letters as well
as spaces between words.
70
CS101L - Introduction to Computing and AI Lab
Solution:
#include <iostream>
int main()
{
char letter;
int counter = 0;
cout << "Program to convert letters to their corresponding telephone digits" << endl;
if (letter != ' ' && letter >= 'A' && letter <= 'z') {
counter++; // Only increment the counter for valid characters
if (letter > 'Z') {
letter = (int)letter-32; // Convert lowercase to uppercase if required.
}
if (counter == 4) {
cout << "-"; // Print the hyphen when required
}
switch (letter) {
case 'A':
case 'B':
case 'C':
cout << "2";
break;
case 'D':
case 'E':
case 'F':
cout << "3";
break;
case 'G':
case 'H':
case 'I':
cout << "4";
break;
case 'J':
71
CS101L - Introduction to Computing and AI Lab
case 'K':
case 'L':
cout << "5";
break;
case 'M':
case 'N':
case 'O':
cout << "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
cout << "7";
break;
case 'T':
case 'U':
case 'V':
cout << "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
cout << "9";
break;
default:
break;
}
}
}
return 0;
}
4.3 Problem 03
Write a C++ program that does the following.
4.3.1 It asks the user to enter an odd negative integer.
72
CS101L - Introduction to Computing and AI Lab
4.3.2 The program reads a value n entered by the user. If the value is not legal, the
program repeatedly makes the user type in another value until a legal value of n
has been entered.
4.3.3 The program computes the equivalent positive number and finds the entries of
Fibonacci series up to that number.
Sample Output:
Solution:
#include <iostream>
using namespace std;
int main()
{
int c, r, n;
int fibonacci, first = 0, second = 0;
cout << "Enter a negative odd integer: ";
cin >> n;
while ((n >= 0) || (n % 2 == 0))
{
cout << "Illegal Entry. Try again: ";
cin >> n;
}
n = -1*n;
cout << "Fibonicci Series upto " << n << " Terms "<<
endl; for ( int j = 0 ; j < n ; j++ )
73
CS101L - Introduction to Computing and AI Lab
if ( j <= 1 )
fibonacci = j;
else
{
fibonacci = first + second;
}
first = second;
second = fibonacci;
return 0;
}
74
CS101L - Introduction to Computing and AI Lab
Lab # 05
Learning Objectives:
❖
Functions concept
❖
Function prototype, definitions and functions calls
❖
Returning values from functions
❖
Function parameters/arguments
Outcomes:
❖
Students should be able to understand the concepts of functions.
❖
Students should practice the examples discussed in the tutorial to get the clear image
of functions before performing the tasks.
Before we go any further, this is a good way to code – write “pseudocode” first, using plain English to
describe what’s supposed to happen, then keep expanding each sentence until it’s sufficiently detailed
that you can express it as if-statements, loops, etc. Often some of the initial English descriptions will
describe good ways to divide up the code into functions.
To turn the catapult pseudocode into code:
Example:
int main() {
buildCatapult();
setUpCatapult();
fireCatapult();
}
CS101L - Introduction to Computing and AI Lab
This style is often a good design for main – main a few calls to some functions that do all the real work.
Each of the functions build Catapult, Setup Catapult, and fire Catapult is said to be “invoked” or “called”
via a “function call” from “calling function” or “caller” (in this case, main). To call a function, type the
name of the function, followed by parentheses. Now that we’ve packaged up each part of our big
procedure and given it a name, we have a bunch of smaller units, each of which we can independently
• Write
• Debug
• Test
• Reuse in later programs
We can also now split development of the program among multiple people, with each developing a
different set of functions. This sort of independence of program components is called modularity, and
is critical to good software engineering. Splitting code up into functions increases the modularity of a
program.
• Function call
86
CS101L - Introduction to Computing and AI Lab
Function prototyping is one very useful feature of C++ function. A function prototype describes the function
interface to the compiler by giving details such as the number and type of arguments and the type of return
values.
The prototype declaration looks just like a function definition except that it has no body i.e., its code is
missing. This is the time you knew the difference between a declaration and a definition.
A declaration introduces a (function) name to the program whereas a definition is a declaration that also
tells the program what the function is doing and how it is doing.
void printHellow();
bool isMultiple(int a,int b);
Therefore, you can say that a function prototype has the following parts :
➢
return type
➢
name of the function
➢
argument list
Example:
void printHello() {
cout << "Hello world!";
}
This definition specifies that we want to name the sequence of commands within the curly braces (
{...} ) printHello, so that we can then call it from another function, such as main, with the syntax printHello();.
CS101L - Introduction to Computing and AI Lab
Example:
bool isMultiple(int a, int b) {
if( a % b == 0 )
return true;
else
return false;
}
Here, bool is the return type, is Multiple is the function name, a and b are argument names, and return
true; and return false; are return statements. Each concept is discussed in detail below.
In the above program, isMultiple (2,3); printHellow() inside main() function calls the user-defined
function.
The function returns an integer which is stored in variable add.
Example:
int main()
{
printHellow();
isMultiple(2,3);
}
88
CS101L - Introduction to Computing and AI Lab
Example:
#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;}
In this example, the question we are asking is “Is a a multiple of b?” The name of the function must
be preceded by a keyword specifying the data type of the answer we are expecting – the return type.
In this case, since we are asking a yes or no question, we want our answer – our return value – to be a
bool. At various points in the program, we specify return statements (here, return true; and return
false;), which indicate what the answer should be if the conditions leading to that statement are
fulfilled. The void return type specifies that there is no return value, which generally means that this
function is for issuing instructions, not asking a question. Returning a value from a void function is a
syntax error. Not returning a value from a non-void function is not a syntax error, but will usually
cause runtime errors.
5.6 Parameters/Arguments:
In the isMultiple function definition, a and b are arguments – variables that are declared between the
parentheses of the function definition and can then be used throughout the function body. The
function call isMultiple(25, 5) specifies that when the body of the isMultiple function is executed for
this call, the variables a and b in the function should store the numbers 25 and 5, respectively.
Functions can have arbitrarily large numbers of arguments – arbitrarily long argumentlists.
CS101L - Introduction to Computing and AI Lab
Lab# 06
Learning Objectives:
❖
Call by value and call by reference
❖
Constant and default parameters
❖
Scope of variables within function
❖
Parameters promotion or demotion
❖
Built in functions.
Outcomes:
❖
Students should be able to understand the concepts of call by value and call by
reference .
❖
Students should be able to understand the concept constant and default parameter.
❖
Students should practice the examples discussed in the tutorial to get the clear image
of functions before performing the tasks.
Any expression can be passed as an argument into a function – for instance, the following is a legal
function call for a maximum function defined to take 3 arguments: maximum( a, b, a + b, maximum(c
+ d, e, f) ).
C++ functions in can be compared to mathematical functions: just like f(x, y, z) means some
mathematical expression named f evaluated for certain values of x, y, and z, isMultiple(a, b) means
some set of instructions named isMultiple evaluated for certain values of a and b.
Arguments in a function can be passed by value or by reference. Variables that exist in the scope of
the caller. For certain variable types (which we’ll get to later), copying the value may be very
computation-intensive, and may take up too much memory. To give the callee access to the caller’s
data, we pass the arguments by reference – the variable in the function actually refers to the same
value in memory as in the caller.
The syntax for declaring arguments to be passed by value is simply an ampersand after the data type
of the variable name.
Example:
void squareByReference(int &value)
{ value = value * value; }
CS101L - Introduction to Computing and AI Lab
If we have a variable number and pass it into squareByReference, the value of number will be updated
when squareByReference exits. Since it updates the original value in memory, the function does not
need to return a value.
Allowing the callee to modify the caller’s data is very useful, but sometimes very dangerous.
Example:
#include<iostrea
m> 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);
Practice problems:
Problem 1:
Classify Numbers
In this example, we use functions to write the program that determines the number of odds and evens
from a given list of integers.
1. Initialize the variables, zeros, odds, and evens to 0.
2. Read a number.
3. If the number is even, increment the even count, and if the number is also zero,
increment the zero count; otherwise, increment the odd count.
4. Repeat Steps 2 and 3 for each number in the list.
The main parts of the program are: initialize the variables, read and classify the numbers, and then
output the results. To simplify the function main and further illustrate
• A function initialize to initialize the variables, such as zeros, odds, and evens.
• A function classifyNumber to determine whether the number is odd or even (and whether it is
also zero). This function also incre- ments the appropriate count.
Main algorithm
We now give the main algorithm and show how the function main calls these functions.
1. Call the function initialize to initialize the variables.
2. Prompt the user to enter 20 numbers.
3. For each number in the list:
a. Call the function getNumber to read a number.
b. Output the number.
c. Call the function classifyNumber to classify the number and increment the appropriate
count.
4. Call the function printResults to print the final results.
Solution:
//
Program: Classify Numbers
This program reads 20 numbers and outputs the number of
zeros, odd, and even numbers.
//************************************************************
* #include <iostream>
#include
<iomanip> using
namespace std;
const int N = 20;
//Function
prototypes
void initialize(int& zeroCount, int& oddCount, int&
evenCount); void getNumber(int& num);
void classifyNumber(int num, int& zeroCount, int&
oddCount, int& evenCount);
void printResults(int zeroCount, int oddCount, int
evenCount); int main()
{
//Variable declaration
int counter; //loop control variable
int number; //variable to store the new number
int zeros; //variable to store the number of zeros
int odds; //variable to store the number of odd integers int evens; //variable to store the
number of even integers
initialize(zeros, odds, evens); //Step 1
cout << "Please enter " << N << " integers."
<< endl; //Step 2
cout << "The numbers you entered are: "
92
CS101L - Introduction to Computing and AI Lab
<< endl;
//Step 4 return 0;
cout << "The number of odd numbers is: " << oddCount
<< endl;
} //end printResults
Sample Run:
94
CS101L - Introduction to Computing and AI Lab
Lab 07
User Defined Functions III
Learning Objectives:
❖
Functions concept
❖
Function prototype, definitions and functions calls
❖
Returning values from functions
❖
Function parameters/arguments
❖
Call by value and call by reference
❖
Constant and default parameters
❖
Scope of variables within function
❖
Parameters promotion or demotion
❖
Built in functions.
Outcomes:
❖
Students should be able to understand the concepts of functions.
❖
Students should practice the examples discussed in the tutorial to get the clear
image of functions before performing the tasks.
Another way to pass the arguments in a function is to define it with const keyword.
Example:
int square(const int number) {
return x * x;
}
Trying to change the value of number in the body of square would be a syntax error.
Example:
void print(const char *str = "\n") {
std::cout << str;
}
95
CS101L - Introduction to Computing and AI Lab
This specifies to the compiler that the function call print() should be treated as equivalent to print("\n")
– that is, the default thing to print is a newline, and we only need to explicitly pass a string if we want
to print something else. If you call a function relying on default values, you cannot pass any values
for arguments after the first argument for which you want to use the default. (Of course, this means
that all the arguments after that must have default values.)
7.3 Scope:
Variables exist within scopes – blocks of code within which identifiers are valid. An identifier can be
referenced anywhere within its scope, as long as the reference comes after its declaration.
Every set of braces is its own scope, and can contain local (i.e. non-global) variables. The moment the
set of braces in which a variable was declared ends, the variable goes out of scope, i.e. it can no longer
be referenced as an identifier. The program usually erases variables that have gone out of scope from
memory. The scope of arguments to a function is the entire function body.
Example: A variable declared in the first line of a function can be referred to anywhere in the function,
but nowhere outside of it. The moment the function exits, the variable ceases to exist in memory.
No two variables may share the same name within a scope. The exception is when you have opened
another scope with a curly brace ( { ), at which point you may declare new variables of the same
name. If another variable is declared within a smaller scope, the variable name refers to the variable in
the narrowest enclosing scope.
Example: In the following code, there are two variables named i. When i is referenced from within the
loop, it is interpreted as referring to the one declared in the loop. Every time the loop executes again, i
is created anew.
Example:
void sampleFunc(int i) {
for( int j = 0; j < 10; j++ ){ int
i = 0; 96
cout << i;
}
}
CS101L - Introduction to Computing and AI Lab
Example:
A function defined as void myFunc(int a) {...} can be called as myFunc(24.3), since the compiler can
convert 24.3 to an int by truncating the decimal.
Early exit:
No more code from a function is executed after one of that function’s return statements; a return
statement ends the function’s execution.
Usually you want the logical path to return statements to be straightforward, but sometimes it’s useful to
return early from a function. You often want to do this in response to an error or an invalid argument.
Example:
bool isPrime(int number) {
if(number <= 1)
return false;
...
}
No number less than 2 can be tested for primality, so if the argument the function received violated
this constraint, it simply exits without even bothering to run the tests in the rest of the function.
97
CS101L - Introduction to Computing and AI Lab
These functions are very efficient and well-implemented. They should be used in preference to hand-
crafted functions whenever possible.
Example: The sqrt function (in header file cmath) takes square roots. The rand function (in cstdlib)
generates random integers.
Example:
#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;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
The easiest way to remember this rule is that the parameters should qualify any one or
more of the following conditions, they should have
different type, number or sequence of parameters.
For example:
These two functions have different parameter type:
99
CS101L - Introduction to Computing and AI Lab
#include <iostream>
using namespace std;
100
CS101L - Introduction to Computing and AI Lab
int main() {
Output:
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
101
CS101L - Introduction to Computing and AI Lab
int main() {
int a = 5;
double b = 5.5;
return 0;
}
Output
Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5
102
CS101L - Introduction to Computing and AI Lab
Practice problems:
Problem 1:
During the tax season, every Friday, J&J accounting firm provides assistance to people who prepare
their own tax returns. Their charges are as follows.
7.7.1 If a person has low income (<= 25,000) and the consulting time is less than or
equal to 30 minutes, there are no charges; otherwise, the service charges are 40%
of the regular hourly rate for the time over 30 minutes.
7.7.2 For others, if the consulting time is less than or equal to 20 minutes, there are no
service charges; otherwise, service charges are 70% of the regular hourly rate for
the time over 20 minutes.
For example, suppose that a person has low income and spent 1 hour and 15 minutes, and the hourly
rate is $70.00. Then the billing amount is 70.00 * 0.40 * (45 / 60) = $21.00. Write a program that
prompts the user to enter the hourly rate, the total consulting time, and whether the person has low
income. The program should output the billing amount. Your program must contain a function that
takes as input the hourly rate, the total consulting time, and a value indicating whether the person has
low income. The function should return the billing amount. Your program may prompt the user to
enter the consulting time in minutes.
Solution:
#include <iostream>
#include <iomanip>
int main()
{
int income, consultingMinutes;
double hourlyRate;
103
CS101L - Introduction to Computing and AI Lab
cout << "Your total bill ammount comes to: $" << calculateBill(income,
consultingMinutes, hourlyRate) << endl;
return 0;
}
}
}
104
CS101L - Introduction to Computing and AI Lab
Problem 2
#include <iostream>
#include <iomanip>
105
CS101L - Introduction to Computing and AI Lab
int main()
{
int x, y;
char z;
double rate, hours;
double amount;
initialise(x, y, z);
getHoursRate(rate, hours);
amount = payCheck(rate, hours);
printCheck(rate, hours, amount);
cout << "The value of x is currently: " << x << endl;
funcOne(x, y);
cout << "The value of x is now: " << x << endl;
nextChar(z);
cout << "The value of z is now: " << z << endl;
return 0;
}
106
CS101L - Introduction to Computing and AI Lab
x = 0;
y = 0;
z = ' ';
}
cout << "For working " << hours << " hours at $" << rate << "/hr you get a total of
$"; cout << fixed << showpoint << setprecision(2);
107
CS101L - Introduction to Computing and AI Lab
x = (x * 2) + y - tempNum;
}
void nextChar(char& z) {
z++;
}
108
CS101L - Introduction to Computing and AI Lab
Lab# 08
Arrays
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.
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.
{
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
20
Now let's keep track of 4 ages instead of just one. We could create 4 separate variables but creating 4
separate variables is not a good approach. (If you are using 4 separate variables for it, then consider
keeping track of 1000 ages instead of just 4). Rather than using 4 separate variables, we'll use an array
because it is quite easy to handle one variable instead of 1000.
110
CS101L - Introduction to Computing and AI Lab
Example 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
Example 3
#include <iostream>
using namespace std;
int main()
{
int age[4]; //array ‘age’ of 4
ints for(int j=0; j<4; j++) //get
4 ages
{
cout << “Enter an age: “;
cin >> age[j]; //access array element
}
111
CS101L - Introduction to Computing and AI Lab
Now how to initialize all the values in array to 0? It can be done by the following statement:
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];
112
CS101L - Introduction to Computing and AI Lab
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 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;
}
113
CS101L - Introduction to Computing and AI Lab
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 element by element. We have used for loop to access every element of array note that for loop takes
value from 0 to 3.
Note: Like printing arrays, there is no single statement in the language that says, "copy an entire array
into another array". The array elements must be copied individually. Thus, If we want to perform any
action on an array, we must repeatedly perform that action on each element in the array.
144
CS101L - Introduction to Computing and AI Lab
{
{7, 6},
{3, 4},
{5, 3},
{2, 3}
},
{
{8, 9},
{7, 2},
{3, 4},
{5, 1}
}
};
cout<<"\narr[0][0][0] = "<<arr[0][0][0]<<"\n";
cout<<"\narr[0][2][1] = "<<arr[0][2][1]<<"\n";
cout<<"\narr[2][3][1] = "<<arr[2][3][1]<<"\n";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
string line;
int i;
cout << "Enter any string :: ";
cin>>line;
cout << "\nThe Original String is :: " << line<<endl;
int len = line.size();
for(i=0;i<len;++i)
{
if (!((line[i]>='a' && line[i]<='z') || (line[i]>='A' && line[i]<='Z')))
{
line[i]='\0';
}
}
cout << "\nAfter Removing Characters, String is :: " << line<<endl;
return 0;
}
115
CS101L - Introduction to Computing and AI Lab
Lab# 09
Recursion
Learning Objectives:
❖
Concept of recursion
❖
Concept of memory allocation in recursive functions
❖
Difference between recursion and iteration
❖
Disadvantages of recursion over iteration
Outcomes:
❖
Students should be able to understand the concepts of recursion.
❖
Students should practice the examples discussed in the tutorial to get a clear image of
recursion and to know about the difference in recursion and iteration before performing the tasks.
❖
In addition, students should also be able to use recursion while passing the function
arguments as pointers or by reference.
9.1 Recursion:
In C++, it is possible for the functions to call themselves. A function is called recursive. if a
statement within the body of a function calls the same function. Sometimes called circular definition,
recursion is thus the process of defining something in terms of itself.
Every function in C++ may be called from any other or itself. Each invocation of a function causes a
new allocation of the variables declared inside it.
116
CS101L - Introduction to Computing and AI Lab
117
CS101L - Introduction to Computing and AI Lab
9.2.1.3 In the third factorial() function, test expression inside if statement is true.
The return num*factorial(num-1); statement is executed, which calls the
fourth factorial() function and argument passed is num-1 which is 1.In the
fourth factorial() function, test expression inside if statement is false. The
return 1; statement is executed, which returns 1 to third factorial() function.
9.2.1.4 The third factorial() function returns 2 to the second factorial() function.
9.2.1.5 The second factorial() function returns 6 to the first factorial() function.
9.2.1.6 Finally, the first factorial() function returns 24 to the main() function,
which is displayed on the screen.
9.3 What is the difference between direct and indirect recursion?
A function fun is called direct recursive if it calls the same function fun. A function fun is called
indirect recursive if it calls another function say fun_new and fun_new calls fun directly or indirectly.
The difference between direct and indirect recursion has been illustrated in the image below.
118
CS101L - Introduction to Computing and AI Lab
When any function is called from main(), the memory is allocated to it on the stack. A recursive
function calls itself, the memory for a called function is allocated on top of memory allocated to
calling function and different copy of local variables is created for each function call. When the base
case is reached, the function returns its value to the function by whom it is called, and memory is de-
allocated and the process continues.
Let us take the example how recursion works by taking a simple function.
When printFun(3) is called from main(), memory is allocated to printFun(3) and a local variable test is
initialized to 3 and statement 1 to 4 are pushed on the stack as shown in below diagram. It first prints
‗3‘. In statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable
test is initialized to 2 and statement 1 to 4 are pushed in the stack.
Similarly, printFun(2) calls printFun(1)and printFun(1) calls printFun(0). printFun(0) goes to if
statement and it return to printFun(1). Remaining statements of printFun(1) are executed and it returns
to printFun(2) and so on. In the output, value from 3 to 1 are printed and then 1 to 3 are printed. The
memory stack has been shown in below diagram.
119
CS101L - Introduction to Computing and AI Lab
Recursion and iteration both repeatedly execute the set of instructions. Recursion is when a statement
in a function calls itself repeatedly. The iteration is when a loop repeatedly executes until the
controlling condition becomes false. The primary difference between recursion and iteration is that is
a recursion is a process, always applied to a function. The iteration is applied to the set of instructions
which we want to get repeatedly executed.
9.5.1 What are the disadvantages of recursive programming over iterative programming?
Note that both recursive and iterative programs have the same problem-solving powers, i.e., every
recursive program can be written iteratively and vice versa is also true. The recursive program has greater
space requirements than iterative program as all functions will remain in the stack until the base case is
reached. It also has greater time requirements because of function calls and returns overhead.
9.6 Problems:
9.6.1 Practice Problem 1:
120
CS101L - Introduction to Computing and AI Lab
Solution:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int n1,ctr;
printf("\n\n count the digits of a given number :\n");
printf(" \n"); printf(" Input a number : ");
scanf("%d",&n1);
ctr = noOfDigits(n1);
if(n1!=0)
{
ctr++;
noOfDigits(n1/10);
}
return ctr;
}
121
CS101L - Introduction to Computing and AI Lab
Sample Run:
Input a number : 50
The number of digits in the number is : 2
9.6.2 Problem 2:
Write a program to multiply two matrix using recursion
Solution:
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAX 10
int main()
{
int arm[MAX][MAX],brm[MAX][MAX],i,j,k;
if(cone!=rtwo)
{
printf("\n Check col. of first and row of second matrix.");
printf("\n They are different. Try again.\n");
}
else
122
CS101L - Introduction to Computing and AI Lab
return 0;
if(i<rone)
{ //row of first
matrix if(j<ctwo)
{ //column of second
matrix if(k<cone)
{
sum=sum+arm[i][k]*brm[k][j];
k++;
multiplyMatrix(arm,brm);
}
crm[i][j]=sum;
sum=0;
k=0;
j++;
multiplyMatrix(arm,brm);
}
j=0;
i++;
multiplyMatrix(arm,brm);
}
}
Sample Run:
124
CS101L - Introduction to Computing and AI Lab
1
2
Here is the elements of Second matrix :
3 4
The multiplication of two matrix is :
3 4
6 8
125
CS101L - Introduction to Computing and AI Lab
Lab# 10
Pointers
Objectives:
❖
To understand the working of computer memory
❖
What are pointers?
❖
Referencing operator and dereferencing operator
❖
Working of pointers
❖
Pointer’s arithmetic
❖
Passing pointers as function arguments
❖
Function pointers
❖
Pointers and Arrays
❖
Memory leaks and how to avoid it?
Outcomes:
❖
Students should be able to understand the concept of memory allocation to variables.
❖
Students should be able to understand the concept of pointers and be able to allocate
different memory locations to pointers.
❖
They should be able to handle pointers arithmetic and also know how to use pointers
as functions arguments and to access the array data using pointers.
❖
Students should be familiar with the concept of memory leaks, what are their
disadvantages, how they occur and how we can avoid it while using the pointers.
10.1 Introduction?
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.
• C++ uses pointers to create dynamic data structures -- data structures built up from blocks of
memory allocated from the heap at run-time.
126
CS101L - Introduction to Computing and AI Lab
• Pointers in C++ provide an alternative way to access information stored in arrays. Pointer
techniques are especially valuable when you work with strings. There is an intimate link
between arrays and pointers in C++.
To fully grasp the concept of pointers all you need is the concept and practice of pointers. Before
talking about pointers let’s talk a bit about computer memory.
Essentially, the computer's memory is made up of bytes. Each byte has a number, an address,
associated with it. The picture below represents several bytes of a computer's memory. In the picture,
addresses 924 thru 940 are shown.
127
CS101L - Introduction to Computing and AI Lab
10.2.2 Example:
Code:
#include<iostream>
int main()
{
float fl=3.14;
cout<<fl;
cin>>fl;
return 0;
Output:
The illustration that shows 3.14 in the computer's memory can be misleading. Looking at the diagram,
it appears that "3" is stored in memory location 924, "." is stored in memory location 925, "1" in 926,
and "4" in 927. Keep in mind that the computer converts the floating-point number 3.14 into a set of
ones and zeros. Each byte holds 8 ones or zero. So, our 4-byte float is stored as 32 ones and zeros (8
per byte times 4 bytes). Regardless of whether the number is 3.14, or -273.15, the number is always
stored in 4 bytes as a series of 32 ones and zeros.
128
CS101L - Introduction to Computing and AI Lab
10.3 Pointers:
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.
10.3.1 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 ask 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.
10.3.2 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:
129
CS101L - Introduction to Computing and AI Lab
ptr = &k;
What the & operator does is retrieve the address of k, and copy that to the contents of our pointer
ptr. Now, ptr is said to "point to" k.
will copy 7 to the address pointed to by ptr. Thus, if ptr "points to" (contains the address of) k,
the above statement will set the value of k to 7. That is, when we use the '*' this way we are
referring to the value of that which ptr is pointing to, not the value of the pointer itself.
Similarly, we could write:
cout<<*ptr<<endl;
to print to the screen the integer value stored at the address pointed to by ptr;.
Here is graphical representation of Pointers.
This Example will be very helpful in understanding the pointers. Understand thoroughly how it
works and then proceed.
130
CS101L - Introduction to Computing and AI Lab
10.3.4 Example:
Output:
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 first value and second
value). 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 first value and
second value respectively in line 7 and 8.
131
CS101L - Introduction to Computing and AI Lab
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.
132
CS101L - Introduction to Computing and AI Lab
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.
133
CS101L - Introduction to Computing and AI Lab
Now when we print the value of first value and second value it prints 10 for first value and 20 for second
value, which is right due to the reasons explained above.
Example
int i;
q = &i;
r = p;
Note that in this code, r points to the same thing that p points to, which is i. You can assign pointers to
one another, and the address is copied from the right-hand side to the left-hand side during the
assignment. After executing the above code, this is how things would look.
134
CS101L - Introduction to Computing and AI Lab
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.
Like other variables pointer variables can be used in expressions. For example if p1 and p2 are
properly declared and initialized pointers, then the following statements are valid.
Example
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 shorthand 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.
135
CS101L - Introduction to Computing and AI Lab
Example
#include<iostream>
using namespace std;
int main()
{
int *ptr1,*ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b
x=*ptr1 + *ptr2 - 6; y=6
- *ptr1 / *ptr2 +30;
cout<<"Address of a: "<<ptr1<<endl;
cout<<"Address-Value in ptr1: "<<*ptr1<<endl<<endl; //The comment
value is the value of ptr1 (address of the a)
cout<<"Address of b: "<<ptr2<<endl;
cout<<"Address-Value in ptr1: "<<*ptr2<<endl<<endl; //The comment
value is the value of ptr2 (address of the b)
cout<<"a: " <<a<<" b: "<<b<<endl<<endl;
//Simply prints the value of a and b
cout<<"x: " <<x<<" y: "<<y<<endl<<endl; //Simply prints the value of
x and y.
ptr1=ptr1 + 1; // adds 4 in address of ptr1. (1*4 = 4)
ptr2= ptr2;
cout<<"a: " <<a<<" b: "<<b<<endl;
//Simply prints the value of a and b
cout<<"Value in ptr1: "<<ptr1<<endl<<endl; // 2293564 //The comment
value is the new memory location value of ptr1
cout<<"\nAddress-Value in ptr1: "<<*ptr1<<endl<<endl; // garbage value
//The comment value is the new value of ptr1 (garbage value)
cout<<"Address of b: "<<ptr2<<endl<<endl;
cout<<"\nAddress-Value in ptr1: "<<*ptr2<<endl<<endl;
cin>>a;
Here note that adding some thing in *ptr1 changes the value of the address stored in ptr. However
adding some thing in ptr will change the address it is pointing to. Printing ptr1 after adding 1 in it
gives different address as it has changed by 4 Bytes.
142
CS101L - Introduction to Computing and AI Lab
How it Works:
This code explains all the rules related to arithmetic 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 arithmetic it started printing values of pointers and other simple variables till line 12.
a b
30 6
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, infect 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 Bytes = 4bytes in the
address of a which is stored in ptr1. Whereas ptr2 points at the same value as before due to the
assignment of line 19.
a b
30 0XF… 6
ptr1ptr2
143
CS101L - Introduction to Computing and AI Lab
Line 20 prints the same value as was printed by Line 16, because values of the variable were 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.
10.4.2 Sending Pointers as Arguments to Functions
When we pass pointers to some function, the addresses of actual arguments in the calling function are
copied into the arguments of the called function. This means that using these addresses we would
have access to the actual arguments and hence we would be able to manipulate them. The following
program illustrates this fact. Try this out:
10.4.3 Example:
Example
#include<iostream>
void swap(int *,int *);
using namespace std;
int main( )
{
int a = 10, b = 20;
int *p, *q;
p = &a;
q = &b; swap(
p, q) ;
cout<<"a: "<<a<<"b: "<<b<<endl;
cin>>a;
}
void swap( int *x, int *y )
{
int t = *x ;
*x = *y;
*y = t;
}
Output:
A=20 b=10
144
CS101L - Introduction to Computing and AI Lab
Note that this program manages to exchange the values of a and b using their addresses stored in x
and y.
And simply put brackets around the name and a * in front of it: that declares the pointer. Because of
precedence, if you don't parenthesize the name, you declare a function returning a pointer:
Once you've got the pointer, you can assign the address of the right sort of function just by using its
name: like an array, a function name is turned into an address when it's used in an expression. You
can call the function as:
(*func)(1,2);
145
CS101L - Introduction to Computing and AI Lab
10.5.1 Example:
Code:
#include<iostream>
using namespace std;
void func(int);
int main(){
void (*fp)(int);
fp = func;
(*fp)(1);
cout<<endl;
fp(2);
system("PAUSE");
return 0;
}
Void func(int arg)
{
cout<<arg<<endl;
}
mypointer = myarray;
After that, mypointer and myarray would be equivalent and would have very similar properties. The
main difference being that mypointer can be assigned a different address, whereas myarray can never
be assigned anything, and will always represent the same block of 20 elements of type int. Therefore,
the following assignment would not be valid:
myarray = mypointer;
146
CS101L - Introduction to Computing and AI Lab
10.6.1 Example:
Code:
#include <iostream>
int main ()
{
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << ", ";
return 0;}
Output:
Pointers and arrays support the same set of operations, with the same meaning for both. The main
difference is that pointers can be assigned new addresses, while arrays cannot.
In the chapter about arrays, brackets ([]) were explained as specifying the index of an element of the
array. Well, in fact these brackets are a dereferencing operator known as offset operator. They
dereference the variable they follow just as * does, but they also add the number between brackets to
the address being dereferenced. For example:
a[5] = 0; // a [offset of 5] = 0
147
CS101L - Introduction to Computing and AI Lab
These two expressions are equivalent and valid, not only if a is a pointer, but also if a is an array.
Remember that if an array, its name can be used just like a pointer to its first element.
148
CS101L - Introduction to Computing and AI Lab
10.7.2 Example:
Code:
body
driver code
int main()
{
return 0;
}
149
CS101L - Introduction to Computing and AI Lab
Code:
/ CPP program to
illustrate how to avoid
memory leak
#include <bits/stdc++.h>
using namespace std;
body
Driver
code int
main()
{
return 0;
}
150
CS101L - Introduction to Computing and AI Lab
Code:
#include <iostream>
using namespace std;
int main(void) {
char str[] = "A string."; char
*pc = str;
return 0;
}
Solution:
#include <iostream>
using namespace std;
int main()
{
char str1[50];
char revstr[50];
char *stptr = str1;
char *rvptr = revstr;
int i=-1;
cout<<"\n\n Pointer : Print a string in reverse order :\n";
cout<<" \n";
cout<<" Input a string : ";
cin>>str1;
while(*stptr)
151
CS101L - Introduction to Computing and AI Lab
{
stptr++;
i++;
}
while(i>=0)
{
stptr--;
*rvptr = *stptr;
rvptr++;
--i;
}
*rvptr='\0';
cout<<" Reverse of the string is :
",revstr; return 0;
}
152
CS101L - Introduction to Computing and AI Lab
Lab # 11
File Handling
Learning Objectives:
❖
Streams in C++
❖
Input/output with files
❖
Open a file
❖
Closing a file
❖
Checking for end of file
Outcomes:
❖
Students should be able to understand the concept of streams in C++.
❖
Students should be familiar with the concept of input/output with files, opening a file, closing
a file and checking for end of file.
iostream.h (short for input/output stream) has certain classes and objects defined within the file, which
we can use in our program directly. It contains the following classes for input/output of data:
• ios- Base class for all other classes for input and output
• istream- Derived from ios. Used to input data into the program (input stream). cin is
an object of this class.
153
CS101L - Introduction to Computing and AI Lab
• ostream- Derived from ios. Used to output data out of the program (output stream).
cout is an object of this class.
the << (insertion operator) passes the value following it (i.e a char * pointing to the string “Hello”) to
the object cout, which in turn acts as an output stream, and hence passes it on to the screen from the
program.
Similarly, when we write the statement:
string s;
cin >> s;
The >> (extraction operator) passes each character of the value the user enters to the object cin, which
in turn acts as an input stream, and hence passes it from the keyboard into the program.
The problem with cout<< is that it only allows flow of data from the program to the screen. Similarly,
cin>> only allows flow of data from the keyboard into the program.
In order to output data from our program to a physical file, or to input from a physical file into our
program, we use the concept of file-handling. We will work with text files for now.
• ifstream- Class derived from istream. Allows input from other sources apart from just
the keyboard.
• ofstream- Class derived from ostream. Allows output other than just the screen.
• fstream- a class which contains all the contents of ifstream, and ofstream through.
multiple inheritance.
154
CS101L - Introduction to Computing and AI Lab
This code creates a file called abc.txt and inserts words into it in the same way we are used to do with
cout, but using the file stream myfile instead.
155
CS101L - Introduction to Computing and AI Lab
This piece of code reads from a physical file. But let’s go step by step:
The mode can be have more than one value, separated by the | operator. For example:
Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default
mode that is used if the file is opened without a second argument:
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even
ifa mode that does not include them is passed as second argument to the open() member function.
The default value is only applied if the function is called without specifying any value for the mode
parameter. If the function is called with any value in that parameter the default mode is overridden,
not
combined.
156
CS101L - Introduction to Computing and AI Lab
Is similar to doing cin >> s. Just like cin >>, F >> would read just a word from the file, as it takes any
white-space (i.e space, tab or new line) as a string terminator. There are a few alternate ways of
inputting data:
11.4.1 getline()
It is a member function of class istream, and is used to input a line from the user. For example:
cin.getline(str,80);
It takes 3 arguments:
1. The name of the string (usually a character array and not a cstyle string)
2. Maximum number of characters in the string (it is important to remember that the last
character must also be string terminator)
3. A delimeter which terminates string input as soon as it is encountered (default is the
enter key) i.e as soon as the user enters the enter key, the string is terminated.
We can also use getline() with fstream objects:
fstream F;
char str[80];
F.getline(str,80);
11.5 get()
It is a member function of class istream, and is used to input a character from the user. For
example:
char ch;
ch=cin.get();
157
CS101L - Introduction to Computing and AI Lab
become available again. In order to do that we have to call the stream's member function close(). This
member function takes no parameters, and what it does is to flush the associated buffers and close the
file:
myfile.close();
Once this member function is called, the stream object can be used to open another file, and the file is
available again to be opened by other processes.
In case that an object is destructed while still associated with an open file, the destructor automatically
calls the member function close().
fstream f;
f.open("story.txt",ios::in);
string s;
f>>s;
while(!f.eof())
{
cout<<s<<endl;
f>>s;
}
int opt;
class housing
{
int hno,income;
char name[20],type[20];
public:
void assign()
{
if(income<15000)
strcpy(type,"LIG");
else if(income>=15000)
strcpy(type,"MIG");
else if(income>=25000)
strcpy(type,"HIG");
}
void input()
{
cout<<"\n Enter House Number: ";
cin>>hno;
cout<<"\n House Name: ";
cin>>name;
cout<<"\n Annual Income: ";
cin>>income;
assign();
}
void output()
{
cout<<"House Number: "<<hno<<"\n"<<"House Name:
"<<name<<"\n"<<"Annual
Income: "<<income<<"\n"<<"Type: "<<type;
}
int retno()
{
return hno;
}
};
159
CS101L - Introduction to Computing and AI Lab
int main()
{
housing h,h1;
fstream f;
int hono;
while(true)
{
cout<<"\n 1: Add Record"<<"\n 2: Modify Record"<<"\n 3:
Display Records"<<"\n 4: Exit\n"<<endl;
cin>>opt;
if(opt==1)
{
char ch='y';
f.open("C:\\Users\\acer\\Documents\\file4.txt",ios::out|ios::binary|
ios::app);
while(ch=='y')
{
cout<<"\n Enter Details: ";
h.input();
f.write((char*)&h,sizeof(h));
cout<<"\n Want to Enter More? y/n:
"<<endl; cin>>ch;
}
f.close();
}
if(opt==2)
{
cout<<"\n Enter House No of Record to be modified:
"; cin>>hono;
f.open("C:\\Users\\acer\\Documents\\file4.txt",ios::in|ios::out|ios:
:binary|ios::ate);
f.seekg(0);
while(f.read((char*)&h,sizeof(h)))
{
if(h.retno()==hono)
160
CS101L - Introduction to Computing and AI Lab
{
cout<<"\n New Value: ";
h1.input();
f.seekp(-sizeof(h),ios::cur);
f.write((char*)&h1,sizeof(h1));
}
}
f.close();
}
if(opt==3)
{
f.open("C:\\Users\\acer\\Documents\\file4.txt",ios::in|ios::binary);
f.seekg(0);
while(f.read((char*)&h,sizeof(h)))
h.output();
f.close();
}
if(opt==4)
exit(0);
return 0;
}
int main()
161
CS101L - Introduction to Computing and AI Lab
fps.open(fname);
if(!fps)
{
cout<<"\nError in opening file..!!";
cout<<"\nPress any key to exit...";
exit(1);
}
fpt.open("C:\\Users\\acer\\Documents\\file5.txt");
if(!fpt)
{
cout<<"\nError in creating file5.txt
file..!!"; fps.close();
cout<<"\nPress any key to exit...";
exit(2);
}
while(fps.eof()==0)
{
fps>>ch;
ch=ch+100;
fpt<<ch;
}
fps.close();
fpt.close();
fps.open(fname);
if(!fps)
{
cout<<"\nError in opening source file..!!";
cout<<"\nPress any key to exit...";
exit(3);
162
CS101L - Introduction to Computing and AI Lab
}
fpt.open("C:\\Users\\acer\\Documents\\file5.txt");
if(!fpt)
{
cout<<"\nError in opening temp.txt
file...!!"; fps.close();
cout<<"\nPress any key to exit...";
exit(4);
}
while(fpt.eof()==0)
{
fpt>>ch;
fps<<ch;
}
cout<<"\nFile "<<fname<<" encrypted successfully..!!";
cout<<"\n\nPress any key to exit...";
fps.close();
fpt.close();
return 0;
}
163