Lab Manual 1 PDF
Lab Manual 1 PDF
Lab Manual 1
(By: Dawit Z, MIT/2019)
Objectives:
In this manual you will learn:
★ To write simple computer programs in C++
★ To write simple input and output statements
★ To use fundamental data types
★ To declare a variable and constant
★ To use arithmetic operators
★ The precedence of arithmetic operators
★ Increment and decrement operators
1. Environment Set Up
Install Code Blocks IDE on Windows
This manual is about how to install CodeBlocks on your local Environment with
Windows OS.
CodeBlocks is a cross-platform, open-source, free IDE that supports GCC, Visual C++,
and Clang compilers. CodeBlocks developed in C++ using WxWidgets for Windows and
Linux as the GUI toolkit.
It is oriented towards C, C++, and Fortran with custom build system support.
Installation Steps
2. First Program
Example 1: Hello.cpp
1: #include <iostream>
2:
3: int main()
4: {
5: std::cout<<”Hello World!”<<std::endl;
6: return 0;
7: }
This simple application does nothing more than display a line one the screen using
std::cout.
Std::endl instructs cout to end that line, and the application exits by return 0 to the
operating system.
1: Right-click the project and select Build to generate the executable Hello.exe.
2: Navigate to the path of the executable using the command-prompt (typically under the
Debug directory of the project folder).
3: Run it by typing the name of the executable.
Your program composed in Microsoft Visual Studio looks similar to that illustrated in the
following figure.
Executing ./hello on Linux or Hello.exe on Windows returns the following output:
Hello World!
Congratulations! You have started on your way to learning one of the most popular and
powerful programming language of all times!
Understanding Compiler Errors
Compilers are painfully exact in their requirements, yet good ones make a descent effort
at telling you where you have made mistakes.
If you face a problem in compiling the application in your first program above, you might
get errors that look quite like the following (introduced deliberately by omitting the
semicolon in Line 5):
This error message from the Visual C++ Compiler is quite descriptive. It tells the name
of the file that contains the error, the line number(6, in this case) where you missed a
semicolon, and a description of the error itself accompanied by the error number (C2143,
in this case).
Q&A
Q: What are run-time errors, and how are they different from compile-time errors?
A: Errors that happen when you execute your application are called runtime errors.
Compile-time errors don’t reach the end-user and are an indication of syntactical
problems - they keep the programmer from generating an executable.
Exercise 1
I. Look at the following program and try to gues what it does without running it:
1: #include <iostream>
2: int main()
3: {
4: int x = 8;
5: int y = 6;
6: std::cout << std::endl;
7: std::cout << x - y << “ “ << x * y << “ “ << x + y;
8: std::cout << std::endl;
9: return 0;
10: }
II. Type in the program from Exercise I and then compile and link it. What does it do?
Does it do what you guessed?
You use std::cout (pronounced “standard see-out”) to write simple text data to the
console and use std::cin (pronounced “standard see-in”) to read text and numbers
(entered usign the keyboard) from the console.
In fact, in displaying “Hello World” on the screen, you have already encountered cout,
like this:
The statement shows cout followed by the insertion operator << (that helps insert data
into the output stream), followed by the string literal “Hello World” to be inserted,
followed by a newlline in the form of std::endl (pronounced “standard end-line”).
The usage of cin is simple, too, and as cin is used for input, it is accompanied by the
variable you want to be storing the input data in:
Thus, cin is followed by the extraction operator >> (extracts data from the input
stream), which is followed by the variable where the data needs to be stored.
If the user input needs to be stored in two variables, each containing data separated by a
space, then you can do so using one statement.
Note: cin can be used for text as well as number inputs from the user as shown in the
example below.
Example 2: Use cin and cout t o Display Number and Text Input by user
1: #include <iostream>
2: #include <strin>
3: using namespace std;
4:
5: int main()
6: {
7: // Declare a variable to store an integer
8: int inputNumber;
9:
10: cout << “Enter an integer: “;
11:
12: // store integer given user input
13: cin >> inputNumber;
14:
15: // The same with text i.e. string data
16: cout << “Enter your name: “;
17: string inputName;
18: cin >> inputName;
19:
20: cout << inputName << “entered “ << inputNumber << endl;
21:
22: return 0;
23 }
Output
Enter an integer: 2019
Enter your name: Dawit
Dawit entered 2019
Q&A
Q: What does #include do?
A: This is a directive to the preprocessor that runs when you call your compiler. This
specific directive causes the contents of the file named in <> after #include to be inserted
at that line as if it were types at that location in your source code.
1: #include <iostream>
2: void main()
3: {
4: std:: Cout << Is there a bug here?”;
5: }
II. Fix the bug and recompile, link, and run it.
III. Modify Example 2 to demonstrate subtraction (using -) and multiplication (using *)
// With Initializing
variableType variableName = InitialValue;
Examples:
// Declaring float variable
float simpleInterest;
Note:
★ The variable type attribute tells the compiler the nature of data the variable can store,
and the compiler reserves the necessary space for it. The name chosen by the programmer
is a friendly replacement for the address in the memory where the variable’s value is
stored.
★ Unless the initial value is assigned, you cannot be sure of the contents of that memory
location ,which can be bad for the program. Therefore, initialization is optional, but it’s
often a good programming practice.
In the following example, we’ll show how global and local variable behave and to manipulate
them.
#include <iostream>
// :: is the scope operator used to identify and specify the context that an identifier refers to
::a = 20;
cout << "\nlocal a: " << a << " Global a: " <<::a;
return 0;
}
4.3. Constant
★ As the name suggests the name constants is given to such variables or values in C++
programming language which cannot be modified once they are defined.
★ They are fixed values in a program.
★ There can be any type of constants like integer, float, octal, hexadecimal, character
constants etc.
★ Every constant has some range.
Defining constants
★ In C++ program we can define constants in many ways.
★ Let’s us see the common ones
1. Using #define preprocessor directive
#include <iostream>
#define val 10
#define floatVal 4.5
#define charVal 'G'
using namespace std;
int main()
{
cout << "Integer Constant: " << val << endl;
cout << "Floating Point Constant: " << floatVal << endl;
cout << "Character Constant: " << charVal << endl;
return 0;
}
2. Using a const keyword
Example 1:
#include <iostream>
using namespace std;
int main()
{
// int constant
const int intVal = 10;
// Real constant
const float floatVal = 4.14;
// char constant
const char charVal = 'A';
// string constant
const char stringVal[10] = "ABC";
return 0;
}
Example 2:
#include <iostream>
using namespace std;
circle = 2*pi*r;
cout << circle;
cout << newline;
return 0;
}
enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
Example 2:
#include <iostream>
using namespace std;
int main()
{
week today;
today = Thursday;
cout << "Day " << today+1;
return 0;
}
4. Logical operators
5. Bitwise operators
Types:
pre-increment ++ variable
post-increment variable ++
Example 1:
#include<iostream>
using namespace std;
int main()
{
int x,i;
i=10;
x=i++;
int main()
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
cout<<"x: "<<x;
return 0;
}
Exercises
Write a C++ statements that accomplish the following.
1. Declare int variables x and y. Initialize x to 25 and y to 18.
2. Declare and initialized an int variable temp to 10 and a char variable to ‘A’.
3. Update the value of an int variable x by adding 5 to it.
4. Declare and initialize a double variable payRate to 12.50.
5. Copy the value of an int variable firstNum into an int variable tempNum.
6. Swap the contents of the int variables x and y. (Declare additional variables, if
neccessary)
7. Suppose x and y are double variables. Output the contents of x, y, and the expression x +
12 / y - 18.
8. Declare a char variable grade and set the value of grade to ‘A’.
9. Declare int variables to store four integers.
10. Copy the value of a double variable z to the nearest integer into an int variable x.
Assignment 1 (5%)
Write a C++ program for the following tasks.
11. A user is asked to enter two integers (divisor and dividend) and computes the quotient
and remainder.
12. To find the size of a variable
13. To swap two numbers
14. To check whether number is Even or Odd
15. To check whether a character is Vowel or Constant
16. To find largest number among three numbers
17. To find all roots of a quadratic equation
18. To find factorial
19. To display fibonacci series
20. To reverse a number
21. To calculate the number of characters, words, sentences
22. To subtract two strings
23. To arrange numbers in Ascending order
24. To sum ODD numbers in the Given Range
25. Display current date and time
26. To check Leap Year
27. To calculate the Power of a Number
28. To calculate Standard Deviation
29. To reverse a Sentence Using Recursion
30. To find the Transpose of a Matrix