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

Lab Manual 1 PDF

The document discusses basic C++ programming concepts like variables, data types, input/output statements, and functions. It provides examples to demonstrate how to write, compile, and run simple C++ programs that perform tasks like taking input from the user, performing calculations, and displaying output.

Uploaded by

Hadis Syoum
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)
49 views

Lab Manual 1 PDF

The document discusses basic C++ programming concepts like variables, data types, input/output statements, and functions. It provides examples to demonstrate how to write, compile, and run simple C++ programs that perform tasks like taking input from the user, performing calculations, and displaying output.

Uploaded by

Hadis Syoum
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/ 22

Mekelle Institute of Technology

Introduction to Computer and Programming


For
Chemical Engineering & Material Science Engineerng
[2nd Year ]

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.

Building and Executing Your First C++ Application


If you’re using Linux, open the terminal, navigate to the directory containing ​Hello.cpp​,
and invoke the ​g++ ​compiler and linker using the following command line

G++ -o hello Hello.cpp


This command instructs ​g++ ​to create an executable named ​hello ​by compiling your C++
file ​Hello.cpp.
If you’re using Microsoft Visual Studio on Windows, press ​ctrl+F5 ​to run your program
directly via the IDE. This compiles, links, and executes your application.
Alternatively, perform the following individual steps:

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

hello.cpp(6): error c2143: syntax error : missing ‘;’ before ‘return’

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: Can I ignore warning messages from my compiler?


A: ​In certain cases, compilers issue warning messages. Warnings are different from
errors in that the line in question is syntactically correct and compile-worthy.
However, there possibly is a better way to write it, and good compilers issue a warning
with a recommendatioin for a fix.
The suggested correction can mean a more secure way of programming or one that lets
your application work with characters and symbols from non-Latin languages.
You should heed these warnings and improve your program accordingly. Don’t mask the
warning messages, unless you are sure that they’re false positives.

Q: How does an interpreted language differ from a compiled language?


A: ​Languages such as Windows Script are interpreted. There is no compilation step. An
interpreted language uses an interpreter that directly reads the script text file (code) and
performs the desired actions. Consequently, you need to have the interpreter installed on
a machine where the script needs to be executed.
Consequently, performance usually takes a hit as the interpreter works as a runtime
translator between the microprocessor and the code written.

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?

III. ​What do you think is the error in this program:


1: include<iostream>
2: int main()
3: {
4: std::cout << “Hello Class \n”;
5: return 0;
6: }
IV. ​Fix the error, compile, link, and run it. What does it do?

3. Basic Input Using std::cin and Output Using std::cout


Your computer enables you to interact with applications running on it in various forms
and allows these applications to interact with you in many forms, too.
You can interact with applications using the keyboard or the mouse. You can have
information displayed on the screen as text, displayed in the form of complex graphics,
printed on paper using a printer, or simply saved to the file system for later usage.
This section discusses the very simplest form of input and output in C++ - using the
console to write and read information.

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:

8: std::cout << “Hello World” << std::endl;

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:

std::cin >> Variable;

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.

std::cin >> Variable1 >> Variable2;

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.

Q: What is the difference between // comments and /* comments?


A: ​The double-slash comments (//) expire at the end of the line. Slash-star (/*) comments
are in effect until there is a closing comment mark (*/).
Remember, not even the end of the function terminates a slah-star comment; you must
put in the closing comment mark or you will receive a compile-time error.

Q: When do you want to program command-line arguments?


A: ​To supply options that allow the user to alter the behavior of a program. For example,
the command ​ls ​in Linux or ​dir ​in Windows enables you to see the contents within the
current directory or folder. To view files in another directory, you specify the path of the
same using command-line arguments, as in ​ls /​ or ​dir \.
Exercise 2
I. Bug busters: ​Enter this program and compile it. Why does it fail? How can you fix it?

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

4. Data Types, Variables and Assignments


4.1. Variable
Consider: ​x = y+f(2);
★ For this to make sense in a C++ program, the names ​x, y, ​and ​f ​must be suitably declared.
★ That is, the programmer ​must specify that entities​ named ​x, y, ​and ​f ​exist and that they
are of types for which = (assignment), + (addition), and () (function call), respectively,
are meaningful.
★ Every ​name (identifier)​ in a C++ program has a ​type​ associated with it.
★ This type ​determines what operations​ can be applied to the name and ​how such
operations are interpreted​.
★ For example:
float x; // ​x is a floating-point variable
int y = 7; // ​y is an integer variable with the initial value 7
float f(int); // ​f is a function taking an argument of type int and returning a floating
number
★ These declarations would make the example meaningful.

★ A Variable is a ​name given to a memory location​. It is the basic unit of storage in a


program.
★ The value stored in a variable can be ​changed during program execution​.
★ A variable is ​only a name​ given to a memory location, all the ​operations​ done on the
variable effects that memory location.
★ In C++, all the variables ​must be declared before use​.
★ When programming in languages like C++, you define variables to store those values.
★ Defining a variable is quite simple and follows this pattern:
// Declaring a single variable
variableType variableName;

// Declaring multiple variables


variableType variableName1, variableName2, variableName3;

// With Initializing
variableType variableName = InitialValue;

Examples:
// Declaring float variable
float​ simpleInterest;

// Declaring integer variable


int​ time, speed;

// Declaring character variable


char​ var;

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

4.2. Scope of a Variable


★ Scope ​is a certain module of a program such as function, class or namespace.
★ A scope of a variable is ​a region in which it is visible and can be accessed.
★ Based on the scope of variable, a variable is of two types:
1. Local Variables
★ Variables that are declared inside a module and can only be used within
the module are called local variables.
★ They can’t be used outside the block in which they are declared.
2. Global Variables
★ Variables that are declared outside all modules and can be accessed and
assigned by all the functions in the program are called Global Variables.
★ The lifetime of global variables is the same as the lifetime of the program
where it is declared.

In the following example, we’ll show how global and local variable behave and to manipulate
them.
#include <iostream>

using namespace std;

// defining the global variables


int a = 10;
int main()
{
// local variable
int a = 15;
cout << "local a: " << a << " Global a: " <<::a;

// :: 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

#define identifierName value;

#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";

cout << "Integer constant: " << intVal << endl;


cout << "Floating point constant: " << floatVal << endl;
cout << "Character constant: " << charVal << endl;
cout << "String constant: " << stringVal << endl;

return 0;
}

Example 2:

#include <iostream>
using namespace std;

const double pi = 3.14159;


const char newline = '\n';
int main()
{
double r = 5.0; // radius
double circle;

circle = 2*pi*r;
cout << circle;
cout << newline;

return 0;
}

3. Using ​#enum​ preprocessor directive


★ Enumeration is a user-defined data type that consists of integral constants.
★ To define an enumeration, keyword ​enum​ ​is used.
Example 1:

enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};

Example 2:

#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main()
{
week today;
today = Thursday;
cout << "Day " << today+1;
return 0;
}

4.4. C++ Operators


★ Operators are used to perform operations on variables and values.
★ C++ divides the operators into the following groups:
1. Arithmetic operators
★ Arithmetic operators are used to perform common mathematical
operations.
2. Assignment operators
3. Comparison operators

4. Logical operators

5. Bitwise operators

5. Increment and Decrement Operators in C++


★ Increment operators are used to increase the value of the variable by one
★ Decrement operators are used to decrease the value of the variable by one
★ Both increment and decrement operators are used on single operand or variable, so it is
called as a ​unary operator.
★ Unary operators are ​having higher priority ​than the other operators it means unary
operators are executed before other operators.
Syntax:
++ ​ // increment operator
-- ​// decrement operator

Types:
pre-increment ++ variable
post-increment variable ++

Example 1:
#include<iostream>
using namespace std;

int main()
{
int x,i;
i=10;

x=i++;

cout<<"x: "<<x <<endl;


cout<<"i: "<<i;
return 0;
}
Example 2:
#include<iostream>
using namespace std;

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

Assignment Due Date


Oct 24, 2019 || 13/02/2012 E.C

Note: solution to the ​exercises​ and


assignment​ will be given in a separate file.

You might also like