0% found this document useful (0 votes)
2 views

Lab 02

The document outlines the objectives and tasks for a C++ fundamentals lab, focusing on variables, input/output, and control flow structures like if-else, switch, while, do-while, and for loops. It provides syntax examples for variable declaration, input/output functions, and control structures, along with tasks for installing CodeBlocks and writing simple C++ programs. Additionally, it includes exercises for practicing user input and output, as well as implementing various control structures.

Uploaded by

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

Lab 02

The document outlines the objectives and tasks for a C++ fundamentals lab, focusing on variables, input/output, and control flow structures like if-else, switch, while, do-while, and for loops. It provides syntax examples for variable declaration, input/output functions, and control structures, along with tasks for installing CodeBlocks and writing simple C++ programs. Additionally, it includes exercises for practicing user input and output, as well as implementing various control structures.

Uploaded by

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

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).

if - else

The commonly used selection control structure to branch the flow of a C++ program. The syntax is:

if (condition) { // true condition statements }


else { // false condition statements }

Can also be the following if the testing of more conditions are needed:

if (condition1) { // executed only if condition1 is true }


else if (condition2) { // executed only if condition1 is false AND condition2 is true }
else { // executed only if condition1 is false AND condition2 is false }

switch

Another type of selection control structure. Primarily used for non-continuous values, i.e. grade A, B,
C and D. The syntax is:

switch (expression)
{ case constant1: // executed if expression is equal to constant1;
break;
case constant2: // executed if expression is NOT equal to constant1 AND equal to constant2;
break;
default: // executed if expression doesn’t match any constants }
while
while (condition) { Typically used to solve problems that have no
// loop body defined iterations before the execution of the
} loop.
do while
do { Used to get a minimum of 1 iteration,
// loop body condition is checked after execution of loop
} while (condition) ; body.
for
for(init ; condition ; update) { If the number of iterations is known, for loop
// loop body is a good candidate to solve the problem.
}

Task 1
1) Install CodeBlocks. This is the software that we are going to use for C++ throughout
TCP1121. There are different versions of CodeBlocks available from here:
http://www.codeblocks.org/downloads/26
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
3) Type the following code:
#include <iostream>
using namespace std;

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

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.
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.

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.

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.

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.
Question 1 (cin, cout, if- else)

Write a C++ program that asks the user to input his/her name and gender. Then output the user’s
name with the appropriate honorific. Sample execution as below:

Question 2 (if- else if- else)

Write a C++ program that asks the user to input the mark then display the appropriate grade
according to the table below. Display an error message if mark is out of range (< 0 or > 100).

Mark Grade
80 – 100 A
70 – 79 B
50 – 69 C
0 – 49 F
Sample execution as below:

Question 3 (switch, do-while)

Write a C++ program that displays a simple 3-choice menu then accepts the user input for choice.
Then based on the choice, simply restate what the user has chosen. Also include an error message
should the choice be invalid. Sample execution as below:
Then put menu query into a do while loop that keeps repeating if the user chooses.

Question 4 (for loop)

Write a C++ program that asks a user for 5 numbers then displays the sum of those numbers.

Question 5 (while loop)

Write a C++ program that asks a user for a numbers then displays the sum of those numbers. The
program stops when the user keys in a 0.

You might also like