[go: up one dir, main page]

0% found this document useful (0 votes)
64 views11 pages

Lab 2 Questions

The document discusses C++ fundamentals including variables, data types, input/output, and flow control. It provides examples of declaring and initializing different variable types as well as using the cin and cout functions for basic input and output.

Uploaded by

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

Lab 2 Questions

The document discusses C++ fundamentals including variables, data types, input/output, and flow control. It provides examples of declaring and initializing different variable types as well as using the cin and cout functions for basic input and output.

Uploaded by

mac one
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

LAB PROGRAM DESIGN | TPD 4124

Lab 02: C++ Fundamentals


Objectives
 To learn about variables, basic input / ouput
 To learn about flow of control

Variable syntax

dataType identifier; // variable declaration


dataType identifier = initValue; // variable declaration + initialization

Input / Output

Basic input / output requires the iostream library to be included at the top of the C++ file. The library will
provide the cin function (for input) and the cout function (for output). cin will read user inputs from the
keyboard and cout will display unto the screen (of the command prompt).

Task 1

 Dev C++

1) Install DevC++. https://sourceforge.net/projects/orwelldevcpp/


2) Your lab instructor will guide you in the class.
3) Dev C++ will be used during lab sessions.
4) CodeBlocks can be your second/alternative.

 CodeBlocks

1) Install CodeBlocks.. There are different versions of CodeBlocks available from here:
http://www.codeblocks.org/downloads/26

P a g e 1 | 11
LAB PROGRAM DESIGN | TPD 4124

Figure 1.1: IDE CodeBlocks (Source from Code::Blocks)

2) After installation, test the software with simple code to confirm the software is workable.
File >> New >> Empty File

P a g e 2 | 11
LAB PROGRAM DESIGN | TPD 4124

3) Type the following code:


#include <iostream>
using namespace std;

int main(){
cout<<"Hello";
}

P a g e 3 | 11
LAB PROGRAM DESIGN | TPD 4124

4) Press F9 to build and run. Or you may click Build >> Build and Run. This is to compile to check the
program. If there is an error, error message will be given. Else, it is fine to proceed.

5) If your file is not saved, it will prompt with the Save As screen.

P a g e 4 | 11
LAB PROGRAM DESIGN | TPD 4124

Be careful here. The default extension for the file name is “.c”. This is a C program file, not C++
program file. In order to be saved as a C++ program file, you have to make sure the extension is
“.cpp”. So let’s save the file as “test.cpp”. Then click Save.

6) If everything is fine, the output screen will be shown.

Task 2
In order to properly use the C++ language to solve problems, we would definitely need to use variables.
These variables can be used to store values for mathematical calculations, record keeping, for further
editing, etc.

Identifier
To create a variable we must provide it with a name or an identifier. An identifier can only be made up of
letters (a, b… z, A, B... Z), digits (0, 1…9), or underscore character (_). An identifier also CANNOT begin with
a digit (e.g. 7grades is wrong).

Sample usable identifiers are userBMI, student_name, result, counter, and computerProgramming1.

Variable identifiers must also avoid C++ reserved keywords such as if, else, while, for, exit, etc.

P a g e 5 | 11
LAB PROGRAM DESIGN | TPD 4124

Data type

To create a variable we must also declare its data type. The basic data types are as follows:

Data type Description Sample value


char Can only contain a single character. Even if you save a number in a, b, 1, 2
it, it has become a char and the numeric value follows the ascii
table (http://www.asciitable.com/index/asciifull.gif).
string Able to keep multiple characters. The string class provides many Hello, polyhydrocarbons,
functions for string manipulation. Fatimah binti Ismail
int Used to keep integer values only. The range of int data type is - 1001117238, 27, 71231,
2147483648, 0, 2147483647. This is because int data type is 4 999
bytes (32 bits), so 232 is 4294967296.
float To represent floating point value. Be very careful in using floating 1.23, 8.55
points as a condition criterion.
double Also for floating point value but has double the size of float data 3.5433
type.
bool Only keeps Boolean value. Mainly used for condition or flag 1, 0, true, false
representation.

Try to understand the sample code below:

Code snippet 1:

From the figure at the left side, explain:


1) Variable declaration, initialization

2) Putting a value into a variable

3) Using the value of a variable

Task 3
Before you start using any variables, you first need to declare them. A variable can be global or local.
Global variables are declared outside of the main body or any other function bodies. A local variable is
declared inside a function body.

P a g e 6 | 11
LAB PROGRAM DESIGN | TPD 4124

A body is easily identified by the opening and closing curly braces { }. So any variables declared inside a
pair of { } is a local variable and only visible inside the { }. The variable will no longer exist when we leave
the { }.

Try to guess the values of the tmp variable before execution:

Code snippet 2:

Explain:
1) Why is it possible to re-declare the
variable inside the { }

2) Must we always assign values into a


string variable using “ “ ?

Global variables are declared as below. Try to guess the output before execution.

Code snippet 3:

Explain:
1) Must we always assign values into a char
variable using ‘ ‘ ?

2) What is the value of the res variable?

3) Explain the value of the res variable.

P a g e 7 | 11
LAB PROGRAM DESIGN | TPD 4124

Task 4

Input / output commands are used in almost all C++ programs. They are supplied by the iostream
library.

cin syntax
cin>> variable; // single user input
cin>> variable1 >> variable2; // multiple user input

cout syntax
cout<< “hello world” <<endl; // multiple output

<< is called the insertion operator. This operator is used to put data into the output stream, cout.
>> is called the extraction operator. This operator is used to get data from the user and put into the
variable.

Code snippet 4:

Explain:
1) In the first cout, why must you use
““?

2) How many words can the string


variable, tmp, keep from the user
input?

3) Solve the question (2) problem so


that the string variable, tmp, can
capture the complete input from the
user.

P a g e 8 | 11
LAB PROGRAM DESIGN | TPD 4124

Question 1

Write a program that asks the user for the number of males and the number of females registered
in a class. The program should compute and report what percentage of the student s are males
and what percentage are females. Display the output with two decimal points. If you
remembered to convert the decimal result of each calculation to percent form when you
displayed it, the two values should add up to 100.00 percent.

Question 2

Write a program based on the descriptions below:

Circular velocity refers to the velocity that one object must travel in order to maintain its circular
orbit around another object, usually a planet or other gravitating mass. The circular velocity of
an object is calculated by dividing the circumference of the circular path by the time period over
which the object travels.

Formula : 𝑐𝑖𝑟𝑐𝑢𝑙𝑎𝑟 𝑣𝑒𝑙𝑜𝑐𝑖𝑡𝑦 = where r is radius and T is time.

● Set as 𝜋 constant using preprocessor directive (#define) , value of PI = 3.142 .


● Declare all necessary variables.
● Get the radius and time from the user.
● Calculate the circular velocity.
● Display the results as shown below.

P a g e 9 | 11
LAB PROGRAM DESIGN | TPD 4124

Question 3

A movie theater only keeps 80 percent of the revenue earned from ticket sales. The other 20
percent goes to the distributor. Write a program that calculates a theater's gross and net box
office revenue for a night. The program should ask for the name of the movie, and how many
adult and child tickets were sold. (The price of an adult ticket is $10 and a child's ticket is $6.) It
should display a report similar to the following:

Note: Can store some values that are fixed using constant variables.

Question 4

Write a program based on the instructions below:

Basal Metabolic rate (BMR) is the number of calories you would burn without doing any
activities. The formula:
BMR = 66 + (6.23 x weight in pounds) + (12.7 x height in inches) – (6.8 x age)

● Declare all necessary variables.


● Declare POUND as a constant with value 2.20462 using const keyword
● Declare INCH as a constant with value 39.3701 using const keyword
● Ask the user to enter weight in kilograms.
● Ask the user to enter height in meters.
● Ask the user to enter age.
● Convert kilograms to pounds and meters to inches:
o 1 kilogram is equivalent to 2.20462 pounds
o 1 meter is equivalent to 39.3701 inches
● Use the given formula to calculate the BMR.
● Display the result as shown below.
P a g e 10 | 11
LAB PROGRAM DESIGN | TPD 4124

Question 5
[Ingredients adjuster program ] A cookie recipe calls for the following ingredients:

 1.5 cups of sugar


 1 cup of butter
 2. 75 cups of flour

The recipe produces 48 cookies with these amounts of the ingredients.

Write a program that asks the user how many cookies he or she wants to make and then displays
the number of cups of each ingredient needed for the specified number of cookies.

Sample output 1

Sample output 2

P a g e 11 | 11

You might also like