Dijlah College University
Department of Computer
Course 2
1 DM Array
المصفوفات االحادية
اساسيات البرمجة
First Class
المرحلة االولى
احمد صبيح توفيق.د
2024-2023
1
Q : Write C++ program to print “ Hello World”
#include <iostream.h>
int main()
{
cout << "Hello World My name is " ;
return 0;
}
This program uses the iostream library to output the "Hello, World!" message to the console.
The std:: prefix is used to qualify elements from the standard C++ library. The main function is
the entry point of the program, and return 0; indicates successful execution.
return 0 : it return a value tells C++ program that the user has ended the program because the
program started with (int main ())
if we started with( voin main (void)) rather than (in main … return 0), the program will not
return any value
C++ Variables
● 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'. ...
● string - stores text, such as "Hello World". ...
● bool - stores values with two states: true or false.
اتبع الموقع التالي++C لمزيد من المعلومات لالطالع على لغة
https://www.programiz.com/cpp-programming
لتطبيق البرامج مباشر على شبكة االنترنت يمكن الدخول على الرابط التالي
https://www.programiz.com/cpp-programming/online-compiler/
بدل عبارة
#include <iostream>
ستكون العبارة
#include <iostream.h>
2
Why Arrays?
Q: Program to read five numbers, find their sum, and print the numbers in
reverse order.
#include <iostream>
using namespace std;
int main()
{
int item0, item1, item2, item3, item4;
int sum;
cout << "Enter five integers: ";
cin >> item0 >> item1 >> item2 >> item3 >> item4;
cout << endl;
sum = item0 + item1 + item2 + item3 + item4;
cout << "The sum of the numbers = " << sum << endl;
cout << "The numbers in the reverse order are: ";
cout << item4 << " " << item3 << " " << item2 << " "
<< item1 << " " << item0 << endl;
return 0;
}
This program works fine. However, if you need to read 100 (or more) numbers and
print them in reverse order, you would have to declare 100 variables and write many
cin and cout statements. Thus, for large amounts of data, this type of program is not
desirable.
3
C++ Arrays
In C++, an array is a variable that can store multiple values of the same type. For example,
Suppose a class has 27 students, and we need to store all their grades. Instead of
creating 27 separate variables, we can simply create an array:
double grade[27];
Here, grade is an array that can hold a maximum of 27 elements of double type.
In C++, the size and type of arrays cannot be changed after its declaration.
C++ Array Declaration
dataType arrayName[arraySize];
For example,
int x[6];
Here,
● int - type of element to be stored
● x - name of the array
● 6 - size of the array
Access Elements in C++ Array
In C++, each element in an array is associated with a number. The number is known as an array
index. We can access elements of an array by using those indices.
// syntax to access array elements
array[index];
Consider the array x we have seen above.
Elements of an array in C++
4
Few Things to Remember:
● The array indices start with 0. Meaning x[0] is the first element stored at index 0.
● If the size of an array is n, the last element is stored at index (n-1). In this example, x[5] is
the last element.
● Elements of an array have consecutive addresses.
For example, suppose the starting address of x[0] is 2120.
Then, the address of the next element x[1] will be 2124, the address of x[2] will be 2128, and so
on.
Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.
C++ Array Initialization
In C++, it's possible to initialize an array during declaration. For example,
// declare and initialize an array
int x[6] = {19, 10, 8, 17, 9, 15};
C++ Array elements and their data
Another method to initialize array during declaration:
// declare and initialize an array
int x[] = {19, 10, 8, 17, 9, 15};
Here, we have not mentioned the size of the array. In such cases, the compiler automatically
computes the size.
C++ Array with Empty Members
In C++, if an array has a size n, we can store up to n number of elements in the array. However,
what will happen if we store less than n number of elements.
For example,
5
// store only 3 elements in the array
int x[6] = {19, 10, 8};
Here, the array x has a size of 6. However, we have initialized it with only 3 elements.
In such cases, the compiler assigns random values to the remaining places. Often, this random
value is simply 0.
Empty array members are automatically assigned the value 0
How to Insert and Print Array Elements?
int mark[5] = {19, 10, 8, 17, 9}
// change 4th element to 9
mark[3] = 9;
// take input from the user
// store the value at third position
cin >> mark[2];
// print first element of the array
cout << mark[0];
Example 1: Displaying Array Elements
#include <iostream>
6
using namespace std;
int main() {
int numbers[5] = {7, 5, 6, 12, 35};
cout << "The numbers are: ";
// Printing array elements
// using range based for loop
for (int n : numbers) {
cout << n << " ";
}
cout << "\nThe numbers are: ";
// Printing array elements
// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}
return 0; }
Run Code
Output
The numbers are: 7 5 6 12 35
The numbers are: 7 5 6 12 35
Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have
printed numbers[i].
We again used a range-based for loop to print out the elements of the array. To learn more
about this loop, check C++ Ranged for Loop.
Example 2: Take Inputs from User and Store Them in an Array
#include <iostream>
using namespace std;
int main() {
int numbers[5];
cout << "Enter 5 numbers: " << endl;
// store input from user to array
7
for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}
cout << "The numbers are: ";
// print array elements
for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}
return 0; }
Run Code
Output
Enter 5 numbers:
11
12
13
14
15
The numbers are: 11 12 13 14 15
Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we took input
from the user and stored it in numbers[i].
Then, we used another for loop to print all the array elements.
C++ Array Out of Bounds
If we declare an array of size 10, then the array will contain elements from index 0 to 9.
However, if we try to access the element at index 10 or more than 10, it will result in an
undefined behavior.
This type of error is likely when we use a normal for loop and we access the array element using
the [] operator.
Note:To overcome this type of error we should prefer range based for loop where no such
operators are needed to access the array elements.
8
Example 3: Display Sum and Average of Array Elements Using for Loop
#include <iostream>
using namespace std;
int main() {
// initialize an array without specifying size
double numbers[] = {7, 5, 6, 12, 35, 27};
double sum = 0;
double count = 0;
double average;
cout << "The numbers are: ";
// print array elements
// use normal for loop
for (int i = 0; i<6; i++)
{
cout << numbers[i] << " ";
// calculate the sum
sum = sum+numbers[i];
// count the no. of array elements
++count;
}
// print the sum
cout << "\nTheir Sum = " << sum << endl;
// find the average
average = sum / count;
cout << "Their Average = " << average << endl;
return 0; }
Run Code
Output
The numbers are: 7 5 6 12 35 27
9
Their Sum = 92
Their Average = 15.3333
In this program:
1. We have initialized a double array named numbers but without specifying its size. We
also declared three double variables: sum, count, and average.
Here, sum =0 and count = 0.
2. Then we used a range-based for loop to print the array elements. In each iteration of the
loop, we add the current array element to sum.
3. We also increase the value of count by 1 in each iteration, so that we can get the size of
the array by the end of the for loop.
4. After printing all the elements, we print the sum and the average of all the numbers. The
average of the numbers is given by average = sum / count;
Q: Write C++ program to Display Largest Element of an array, the
number of the array is entered by user.
#include <iostream>
using namespace std;
int main() {
int i, n;
float arr[100];
cout << "Enter total number of elements(1 to 100): ";
cin >> n;
cout << endl;
// Store number entered by the user
for(i = 0; i < n; ++i) {
cout << "Enter Number " << i + 1 << " : ";
cin >> arr[i];
}
// Loop to store largest number to arr[0]
for(i = 1;i < n; ++i) {
10
if(arr[0] < arr[i])
arr[0] = arr[i];
}
cout << endl << "Largest element = " << arr[0];
return 0;
}
Run Code
Output
Enter total number of elements(1 to 100): 8
Enter Number 1 : 23.4
Enter Number 2 : -34.5
Enter Number 3 : 50
Enter Number 4 : 33.5
Enter Number 5 : 55.5
Enter Number 6 : 43.7
Enter Number 7 : 5.7
Enter Number 8 : -66.5
Largest element = 55.5
This program takes n number of elements from user and stores it in array arr[].
To find the largest element, the first two elements of array are checked and largest of these two
element is placed in arr[0].
Then, the first and third elements are checked and largest of these two element is placed
in arr[0].
This process continues until and first and last elements are checked.
After this process, the largest element of an array will be in arr[0] position.
11
Write C++ program to sort an array in ascending order.
#include <iostream>
# include<cmath>
using namespace std;
int main()
{
int A[100], size, i, j, temp;
// Reading the size of the array
cout<<"Enter size of array: ";
cin>>size;
//Reading elements of array
cout<<"Enter elements in array: ";
for(i=0; i<size; i++)
{
cout << "enter element "<< endl;
cin>>A[i];
}
//Sorting an array in ascending order
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
//If there is a smaller element found on right of the array then swap it.
if(A[j] < A[i])
{
temp = A[i];
A[i] = A[j];
A[j] = temp;
12
}
}
}
//Printing the sorted array in ascending order
cout<<"Elements of array in sorted ascending order:"<<endl;
for(i=0; i<size; i++)
{
cout<<A[i]<<endl;
}
return 0 ;
}
H.W
Q1: Try to find the smallest element
Q2: Write C++ to read, print 1 DM array using for loop and print array in reverse
order.
Q3: Write C++ program to sort an array in descending order.
13