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

C++ Lab Report Section A

Uploaded by

barniderese
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C++ Lab Report Section A

Uploaded by

barniderese
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

ARBA MINCH UNIVERSITY

COLLEGE OF COMPUTER AND SOFTWARE ENGINEERING

C++ Programming Lab Report

2016 Pre-Engineering
SECTION-A
1.Amanuel Ginbo . . . . . . . . . . . . . . . . . . .NSR/084/16
2.Atnan Chali . . . . . . . . . . . . . . . . . . . . . NSR/1164/16
3.Belete Beyhun . . . . . . . . . . . . . . . . . . . .NSR/152/16
4.Dagmawi Wube . . . . . . . . . . . . . . . . . . NSR/092/16
5.Dina Zilo. . . . . . . . . . . . . . . . . . . . . . . . NSR/T/019/16
6.Etsubdink Ayalew. . . . . . . . . . . . . . . . . NSR/327/16
7.Haile Tegenu. . . . . . . . . . . . . . . . . . . . . NSR/450/16
8.Masresha Dagmawi . . . . . . . . . . . . . . . NSR/1404/16
9.Milkyas Tesfaye. . . . . . . . . . . . . . . . . . NSR/699/16
10.Molalign Tsegaye. . . . . . . . . . . . . . . . NSR/717/16
11.Nathan Kaleb. . . . . . . . . . . . . . . . . . . . NSR/T/011/16

Submitted to : Mrs. Amarech


October 2017 E.C
Arba Minch, Ethiopia
1. C++ Introduction

C++ is a powerful general-purpose programming language developed by Bjarne Stroustrup in 1985. It was designed as
an extension of the C programming language to add features for high-level programming while retaining the efficiency
and flexibility of C.

C++ is widely used for systems programming (like operating systems, browsers, and games), application development,
and embedded systems. One of its key features is support for object-oriented programming (OOP), which allows
developers to create classes, objects, and methods, thereby making code more reusable and modular.

In addition to OOP, C++ supports other paradigms such as procedural and functional programming. With features like
direct memory manipulation using pointers, it’s an ideal choice for performance-critical applications. Its standard library
provides data structures, algorithms, and input/output functions, making it a comprehensive tool for developers.

• Developer Name

1.Amanuel Ginbo
2.Atnan Chali
3.Belete Beyhun
4.Dagmawi Wube
5.Dina Zilo
6.Etsubdink Ayalew
7.Haile Tegenu
8.Masresha Dagmawi
9.Milkyas Tesfaye
10.Molalign Tsegaye
11.Nathan Kaleb
• Developed Lab Name

Lab Name: Electrical and Computer Engineering Lab

"Introduction to C++ Programming" // "Basic Programming Concepts in C++".

2. C++ Comments

Comments are non-executable statements in C++ that help explain the code. While they don't affect the program's
functionality, they improve code readability and help other developers understand the logic behind the code. C++ supports
two types of comments:

1. Single-line comments:

Single-line comments start with // and continue until the end of the line. They are typically used for brief explanations or
to comment out specific lines of code.

Example:

// This is a single-line comment

int age = 25; // Variable for storing age

2. Multi-line comments:

Multi-line comments start with /* and end with */. These are useful for longer explanations or for temporarily disabling
multiple lines of code during debugging.
Example:

/* This is a multi-line comment

used for detailed explanations or

to comment out large blocks of code. */

int sum = 0;

3. C++ Variables, Literals, and Constants

✓ Variables

Variables in C++ are used to store data that the program will use and manipulate during execution. Each variable has a
specific data type, such as int, float, or char, which determines the kind of value it can hold.

A variable is declared by specifying the data type followed by the variable name.

Example:

int age = 25; // 'age' is a variable of type 'int'

float temperature = 36.5; // 'temperature' is a variable of type 'float'

✓ Literals

Literals are fixed values that appear directly in the code and do not change. They represent constant values of basic data
types.

Examples:

Integer literal: 42

Floating-point literal: 3.14159

Character literal: 'A'

String literal: "Hello, World!"

Literals are assigned to variables and help define specific values that a variable will store.

✓ Constants

Constants are variables whose value cannot be changed once they are initialized. In C++, you can define constants using
the const keyword or preprocessor directives like #define.

1. Using const:

const int MAX_VALUE = 100; // MAX_VALUE cannot be changed

2. Using #define:

#define PI 3.14159 // PI is a macro that replaces occurrences of PI with 3.14159

Constants are often used for values that do not change throughout the program, such as mathematical constants (e.g., PI),
or configuration values (e.g., maximum allowed users).
4. C++ Data Types

C++ supports various fundamental data types that allow programmers to define the kind of data a variable will hold.
Understanding the different data types is crucial for proper memory allocation and performance optimization.

Primary Data Types:

1. int (Integer):

Used to store whole numbers without a decimal point.

Example:

int count = 10;

2. float (Floating Point):

Used to store decimal numbers with single precision.

Example:

float price = 9.99;

3. double:

Used to store double-precision floating-point numbers, providing more precision than float.

Example:

double distance = 12345.6789;

4. char (Character):

Used to store single characters, typically enclosed in single quotes.

Example:

char grade = 'A';

5. bool (Boolean):

Used to store logical values, either true or false.

Example:

bool isValid = true;

Derived Data Types:

Array: Used to store multiple values of the same type in contiguous memory locations.

Pointer: Used to store the memory address of another variable.

Reference: An alias for another variable.

5. C++ Constants
Constants in C++ are variables that are declared with a fixed value that cannot be altered during the execution of the
program. Defining constants is essential for making your code more understandable and less prone to errors.

1. Using const keyword:

This method is preferred when defining constants in modern C++ programming.

const int MAX_LIMIT = 50;

const float GRAVITY = 9.8;

2. Using #define Preprocessor Directive:

This method was more commonly used in C programming but is still supported in C++.

#define PI 3.14159

Using constants improves the readability of the code by giving meaningful names to fixed values. It also makes
maintenance easier, as changes can be made in one place instead of multiple occurrences in the code.

6. C++ Basic Input/Output

C++ provides standard input and output operations through the iostream library, which contains objects like cin (for input)
and cout (for output). These are part of the C++ Standard Library and are essential for interacting with the user.

Input with cin:

The cin object is used to accept input from the user. It reads input from the keyboard and assigns it to a variable.

#include <iostream>

using namespace std;

int main() {

int num;

cout << "Enter a number: ";

cin >> num; // User input is stored in 'num'

cout << "You entered: " << num;

return 0;

Output with cout:

The cout object is used to display output to the console. You can use the insertion operator << to send data to cout.

cout << "Hello, World!" << endl;

Chaining Output Statements:

You can chain multiple cout operations in a single line using the insertion operator:
cout << "The sum is " << sum << " and the product is " << product << endl;

This flexibility makes cout and cin essential for building interactive applications in C++.

7. C++ Operators

Operators in C++ are symbols that tell the compiler to perform specific mathematical, logical, or relational operations.
Operators form the core of any program, enabling calculations, decision-making, and data manipulation.

8. C++ Types of Operators

✓ Arithmetic Operators:

These are used for mathematical operations:

+ (Addition)

- (Subtraction)

* (Multiplication)

/ (Division)

% (Modulus for finding the remainder)

Example:

int sum = 10 + 5; // sum will be 15

int product = 10 * 5; // product will be 50

9. C++ Relational and Logical Operators

✓ Relational Operators:

These operators compare two values and return true or false:

== (Equal to)

!= (Not equal to)

> (Greater than)

< (Less than)

>= (Greater than or equal to)

<= (Less than or equal to)

Example:

bool result = (10 > 5); // result will be true

✓ Logical Operators:
Logical operators are used to combine or modify boolean expressions and return a boolean result (true or false). They are
often used in control flow statements like if, while, or for loops.

&& (Logical AND): Returns true if both operands are true.

|| (Logical OR): Returns true if at least one operand is true.

! (Logical NOT): Reverses the boolean value.

Example:

bool result = (true && false); // result is false because one operand is false

result = (true || false); // result is true because one operand is true

result = !true; // result is false because ! reverses the value

• Logical operators are crucial in controlling program flow, especially when combining multiple conditions in an if
or while statement.

10. C++ if, if...else, and Nested if...else

✓ The if Statement:

The if statement allows the program to execute a block of code only if a specified condition evaluates to true.

Example:

int age = 18;

if (age >= 18) {

cout << "You are eligible to vote.";

In this case, if the age is 18 or greater, the message "You are eligible to vote" will be printed.

✓ The if...else Statement:

If the condition in an if statement is false, the else statement allows the program to execute an alternate block of code.

Example:

int age = 16;

if (age >= 18) {

cout << "You are eligible to vote.";

} else {

cout << "You are not eligible to vote.";

Here, since the age is less than 18, the message "You are not eligible to vote" will be printed.

✓ Nested if...else Statements:


Sometimes, multiple conditions need to be evaluated, and this is where nested if...else statements come into play.

Example:

int score = 85;

if (score >= 90) {

cout << "Grade: A";

} else if (score >= 80) {

cout << "Grade: B";

} else if (score >= 70) {

cout << "Grade: C";

} else {

cout << "Grade: F";

11. C++ for Loop

The for loop is used to iterate over a sequence (such as numbers in a range or elements in an array) a specific number of
times.

Syntax of a for Loop:

for (initialization; condition; increment) {

// loop body

Initialization: Executed once before the loop starts.

Condition: The loop continues as long as this condition is true.

Increment: This is executed after each iteration of the loop.

Example:

for (int i = 0; i < 5; i++) {

cout << "Value of i: " << i << endl;

In this loop, the value of i starts at 0, and as long as i is less than 5, the loop runs, printing the value of i and incrementing
it by 1 each time.

12. C++ while and do...while Loop

✓ The while Loop:


The while loop is used to repeatedly execute a block of code as long as the condition is true.

Syntax:

while (condition) {

// loop body

Example:

int i = 0;

while (i < 5) {

cout << "i is " << i << endl;

i++;

This loop continues running until i is no longer less than 5.

✓ The do...while Loop:

The do...while loop is similar to the while loop, but it guarantees that the loop body will be executed at least once, even if
the condition is false.

Syntax:

do {

// loop body

} while (condition);

Example:

int i = 0;

do {

cout << "i is " << i << endl;

i++;

} while (i < 5);

In this case, the loop body will execute at least once even if i is initially greater than or equal to 5.

13. C++ break Statement

The break statement is used to immediately exit a loop, regardless of the condition.

Example:

for (int i = 0; i < 10; i++) {

if (i == 5) {
break; // Loop stops when i equals 5

cout << i << endl;

In this loop, when i becomes 5, the loop terminates, and no further iterations are performed.

14. C++ switch Case Statement]

The switch statement provides a way to execute different parts of code based on the value of a variable or expression.

Syntax:

switch (expression) {

case value1:

// statements

break;

case value2:

// statements

break;

default:

// default statements

Example:

int day = 3;

switch (day) {

case 1:

cout << "Monday";

break;

case 2:

cout << "Tuesday";

break;

case 3:

cout << "Wednesday";

break;

default:
cout << "Invalid day";

In this example, since day is 3, the message "Wednesday" will be printed. If day had no matching case, the default case
would be executed.

15. C++ Arrays

An array is a data structure that can hold multiple values of the same data type. In C++, arrays are used to store a
collection of values in contiguous memory locations.

Syntax of an Array:

dataType arrayName[arraySize];

dataType: Specifies the type of elements in the array.

arrayName: The name of the array.

arraySize: The number of elements the array can hold.

Example:

int numbers[5] = {1, 2, 3, 4, 5};

Here, numbers is an array that can hold 5 integers. The elements are initialized to the values 1, 2, 3, 4, and 5.

You can access an element of an array using the index, starting from 0:

cout << numbers[0]; // Outputs 1

cout << numbers[4]; // Outputs 5

• Arrays are useful when you need to store a fixed-size collection of elements, such as a list of numbers or
characters.

16. C++ Type of Arrays

C++ allows you to define both one-dimensional and multi-dimensional arrays.

1D Arrays (Single-dimensional Arrays):

As shown in the previous example, 1D arrays store a sequence of elements of the same type.

Example:

int scores[3] = {85, 90, 78};

▪ Multidimensional Arrays: C++ also supports multidimensional arrays, where arrays are nested within arrays.
The most common form is the two-dimensional array, which is used to represent a matrix.

Syntax:

dataType arrayName[rows][columns];

Example (2D Array):


int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

Here, matrix is a 2x3 array that holds integers.

To access an element in a 2D array:

cout << matrix[0][1]; // Outputs 2

17. Passing Arrays to a Function in C++ Programming

In C++, you can pass an entire array to a function by specifying the array name as the argument. Since the array name
represents the memory address of the first element, you are essentially passing a pointer to the function.

Syntax:

void functionName(dataType arrayName[], int size);

Example:

void printArray(int arr[], int size) {

for (int i = 0; i < size; i++) {

cout << arr[i] << " ";

int main() {

int myArray[3] = {10, 20, 30};

printArray(myArray, 3);

return 0;

18. C++ Multidimensional Arrays

As discussed earlier, multidimensional arrays, particularly 2D arrays, are used for storing data in rows and columns. You
can define and manipulate 3D arrays or higher, although this is less common in most basic applications.

Example of a 2D Array:

int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 3; j++) {

cout << matrix[i][j] << " ";

cout << endl;


}

19. C++ String

In C++, strings can be created using either character arrays or the std::string class from the C++ Standard Library. The
std::string class offers a more flexible and efficient way to manipulate strings compared to character arrays.

Example Using std::string:

#include <iostream>

#include <string>

using namespace std;

int main() {

string greeting = "Hello, World!";

cout << greeting;

return 0;

The std::string class allows you to easily perform string operations such as concatenation, finding substrings, and
modifying characters. For example:

string name = "Alice";

name.append(" Johnson"); // Concatenates " Johnson" to "Alice"

cout << name; // Outputs: Alice Johnson

20. C++ Pointers

A pointer is a variable that stores the memory address of another variable. Pointers are very powerful and allow you to
manipulate memory directly.

Syntax of a Pointer:

dataType* pointerName;

dataType: The type of data the pointer will point to.

pointerName: The name of the pointer.

Example:

int var = 42;

int* ptr = &var; // Pointer to var

cout << "Address of var: " << ptr << endl; // Outputs the memory address

cout << "Value of var: " << *ptr << endl; // Outputs the value of var (42)
In this example, the pointer ptr holds the address of the variable var. The dereference operator * is used to access the
value stored at the memory address.

21. C++ Type of Pointers

There are various types of pointers in C++:

1. Null Pointer: A pointer that does not point to any valid memory location.

int* ptr = nullptr; // Null pointer

2. Void Pointer: A pointer that can point to any data type.

void* ptr;

int x = 10;

ptr = &x; // ptr now points to an int

3. Pointer to Pointer: A pointer that holds the address of another pointer.

int x = 5;

int* ptr = &x;

int** ptr2 = &ptr;

22. C++ Pointers and Arrays

Pointers and arrays are closely related in C++. The name of an array is essentially a pointer to its first element. Therefore,
you can use pointers to iterate through an array.

Example:

int arr[3] = {10, 20, 30};

int* ptr = arr; // Pointer to the first element of arr

for (int i = 0; i < 3; i++) {

cout << *(ptr + i) << " "; // Access array elements using pointer arithmetic

In this example, the pointer ptr is used to access each element of the array arr. Pointer arithmetic (ptr + i) allows you to
move through the array, and dereferencing (*) gives access to the array elements.

You might also like