Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

LAB 2 – C++ BUILDING BLOCKS-I

Objectives
1. Basics
2. Declaring variables (int, double and char).
3. Input and Output using cin and cout with/without using variables.
4. Using basic arithmetic operators available in C++ ( +, - ,* , / ).
5. Using escape sequences in cout statements.
Introduction:
Consider the following program

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Example explained

Line 1: #include <iostream> is a header file library that lets us work with input and output objects,
such as cout (used in line 5 ). Header files add functionality to C++ programs.

Line 2: using namespace std means that we can use names for objects and variables from the
standard library.

Don't worry if you don't understand how #include <iostream> and using namespace std works. Just
think of it as something that (almost) always appears in your program.

Line 3: A blank line. C++ ignores white space.

Line 4: Another thing that always appear in a C++ program, is int main(). This is called
a function. Any code inside its curly brackets {} will be executed.

Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to
output/print text. In our example it will output "Hello World".

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }

Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.

Line 6: return 0 ends the main function.


Line 7: Do not forget to add the closing curly bracket } to actually end the main function.

Omitting Namespace

You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for some objects:

Example
#include <iostream>

int main() {
std::cout << "Hello World!";
return 0;
}

Comments in program:
Single-line comments start with two forward slashes (//).
Multi-line comments start with /* and ends with */.
e.g
// This is a comment
/* The code below will print the words Hello World!
to the screen, and it is amazing */
Compiler will ignore anything written in comments

Output command:
The cout object, together with the << operator, is used to output values/print text:
cout << "Hello World!";
cout << c;
To insert a new line, you can use the \n character:
e.g
int main() {
cout << "Hello World! \n"; //\n will move the cursor to next line
//if you write \n\n its just like pressing enter two times in a MS word
cout << "I am learning C++";
return 0;
}

Declaring Variables
Variables are containers for storing data values.

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
 string - stores text, such as "Hello World". String values are surrounded by double quotes
 bool - stores values with two states: true or false
To create a variable, you must specify the type and assign it a value: e.g

int myNum = 5; // Integer (whole number without decimals)


double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
int x = 5, y = 6, z = 50;

C++ Identifiers

All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits and underscores


 Names must begin with a letter or an underscore (_)
 Names are case sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (like C++ keywords, such as int) cannot be used as names

User Input Command

cin is a predefined variable that reads data from the keyboard with the extraction operator ( >>).

In the following example, the user can input a number, which is stored in the variable x. Then we
print the value of x:

int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
Tasks:
Write a C++ program, which declares integer ‘a’, float ‘b’ and character ‘c’. Ask user for
an integer value and store it in ‘a’, for a float value and store it in ‘b’ and for a character
value and store it in ‘c’. At the end, print the values of these three variables on screen.
Your output should be as below. Indent your code and include comments for improving
the readability of your code.

Enter Integer Value: 448


Enter Float Value: 32.65
Enter Character Value: A
***** You have entered the following values *****
Integer Value is: 448
Float Value is: 32.65
Character Value is: A
Arithmetic Operations on Variables +, -, *, / , %

Write a C++ program which takes two int values from user and computes their sum,
difference, product, quotient (division) and remainder (use mod i.e %). At the end, print
these results on screen with a beep. Your output should be as below. Indent your code and
include comments for improving the readability of your code.

Enter Value 1: 50
Enter Value 2: 50
Sum = 100
Difference = 0
Product = 2500
Quotient = 1
Remainder = 0
cout Statement with Escape Sequences
By using different escape sequences, write a C++ program, which displays the following
output. After every line, your program must generate a beep. If you already do not know
the escape sequence for generating a beep, find it out for yourself. Indent your code and
include comments for improving the readability of your code.

BCSE
BCSE
BCSE
BCSE

MCS
Hint: cout<<”\tBCSE \n”;
Exercise # 2.1(Arithmetic)

Write a program that inputs three integers from the keyboard and prints the sum, average,
product. The screen dialog should appear as follows:

Input three different integers: 13 27 14


Sum is 54 Average is 18 Product is 4914 S
Excercise # 2.2 (Displaying Shapes with Asterisks *)
Write a program that prints a box and an oval, as follows:
Excercise # 2.3 (Table)
Using the techniques of this chapter, write a program that calculates the squares and cubes of
the integers from 0 to 10. Use tabs to print the following neatly formatted table of values:

Hint : Square of x = x * x
Cube of x = x*x*x

Web Resources

http://www.cprogramming.com/
http://www.mycplus.com/featured-articles/top-10-applications-written-in-c-cplusplus/
http://www.cplusplus.com/doc/tutorial/program_structure/
http://www.cplusplus.com/doc/tutorial/variables/
http://www.cplusplus.com/doc/tutorial/constants/
http://www.cs.wustl.edu/~schmidt/C++/

#include <iostream>
using namespace std;

int main() {

int x;
int y;
int z;
int sum;
int prd;
int avg;

cout "Enter Numbers : ";


cin>>x;
cin>>y;
cin>>z;

sum = x + y + z;
prd = x * y * z;
avg = (x+y+z)/3;
//cout << "Hello World!";
int n0 =0;
int n1 =1;
int n2 =2;
int n3 =3;
int n4 =4;
int n5 =5;
int n6 =6;
int n7 =7;
int n8 =8;
int n9 =9;
int n10 =10;

cout<<"Value\tSquare\tCube \n";
cout<<n0 <<" \t"<<n0*n0<<" \t"<<n0*n0*n0<<"\n";
cout<<n1 <<" \t"<<n1*n1<<" \t"<<n1*n1*n1<<"\n";
cout<<n2 <<" \t"<<n2*n2<<" \t"<<n2*n2*n2<<"\n";

//cout << "Type a number: "; // Type a number and press enter
// cin >> x; // Get user input from the keyboard
// cout << "Your number is: "; // Display the input value
// cout << x;
return 0;
}

You might also like