Skip to main content

cpp arrays

Arrays

Variables are used to store single piece of data. Arrays can store many piece of data or collection of data. Arrays like variable can store data of a specific datatype.

#include <iostream>
using namespace std;

int main() {
	int num; //Integer variable
	num = 10; //assignment 
	int num1 = 10; // declare and initialize
	cout << num << endl;
	cout << num1 << endl;

	int nums[3]; //Integer Array
	nums[0] = 2; // assignment
	nums[1] = 5;
	nums[2] = 8;
	int nums1[] = { 4, 2, 4 };
	cout << nums[0] << endl;
	cout << nums[2] << endl;
	cout << nums1[1] << endl;

	return 0;
}


#include <iostream>
using namespace std;

int main() {
	char ch; //declare a char variable
	ch = 'a';

	char chs[5]; //declare an array of 5 char
	chs[0] = 'a';
	chs[1] = 'b';
	chs[2] = 'c';
	chs[3] = 'd';
	chs[4] = 'e';

	cout << "char stored in ch : " << ch << endl;
	cout << "first char stored in chs " << chs[0] << endl;
	cout << "Last char stored in chs " << chs[4] << endl;

 
	return 0;
}

Output:

#include <iostream>
using namespace std;

int main() {
	char ch; //declare a char variable
	ch = 'a';

	char charArray[5]; //declare an array of 5 char
	charArray[0] = 'a';
	charArray[1] = 'b';
	charArray[2] = 'c';
	charArray[3] = 'd';
	charArray[4] = 'e';

	char chs2[] = {'f', 'g', 'h', 'i'};
	char chs3[] = "myword";

	cout << "char stored in ch : " << ch << endl;
	cout << "first char stored in chs " << charArray[0] << endl;
	cout << "Last char stored in chs " << charArray[4] << endl;
	cout << "first char stored in chs2 " << chs2[0] << endl;
	cout << "Last char stored in chs2 " << chs2[3] << endl;
	cout << "first char stored in chs3 " << chs3[0] << endl;
	cout << "first char stored in chs3 " << chs3[5] << endl;
	cout << "Last char stored in chs3 " << chs3[6] << endl;
	return 0;
}



Output:

#include <iostream>
#include <string>
using namespace std;

int main() {
	string items[10];
	for (int i = 0; i < 3; i++)
	{
		cout << "Enter the item : ";
		cin >> items[i];
	}
	for (string item: items)
	{
		cout << item << "\t";
	}
	cout << endl;
	for (int i = 0; i < 5; i++)
	{
		cout << i+1 << ") " << items[i] << "\n";
	}
	return 0;
}

Output:

Traversing an array with for each loop


#include 
#include 
using namespace std;

int main() {
	string month[] = { "Jan", "Feb", "Mar", "Apr",
						"May", "Jun", "Jul", "Aug",
						"Sep", "Oct", "Nov", "Dec" };

	cout << month[3] << endl << endl; //This prints 4th element

	//using for each loop to traverse through the array
	for (string var : month)
	{
		cout << var << endl;
	}

	return 0;
}

Parallel Arrays



#include 
#include 
using namespace std;

int main() {
	const int NUM_EL = 3;

	string items[NUM_EL];
	double prices[NUM_EL];
	for (int i = 0; i < NUM_EL; i++){
		cout << "Enter the item : ";
		cin >> items[i];
		cout << "\t Enter the price : ";
		cin >> prices[i];
	}
	for (int i = 0; i < NUM_EL; i++){
		cout << i+1 << ") " << items[i] << "\t" << prices[i] << "\n";
	}
	return 0;
}


#include 
using namespace std;

int main() {
	//Parallel Arrays - Array with two different datatypes
	string month[] = { "Jan", "Feb", "Mar", "Apr",
						"May", "Jun", "Jul", "Aug",
						"Sep", "Oct", "Nov", "Dec" };
	int monthdays[] = { 31,28,31,30,
						31,30,31,31,
						30,31,30,31 };

	cout << "month[i]" << "\t" << "monthdays[i]" << endl;
	for (int i = 0;  i < 12;  i++)
	{
		cout << month[i] << "\t\t" << monthdays[i] << endl;
	}

	return 0;
}

Here is another example. This time we will populate the array by accepting the inputs from the user.


#include 
#include 
using namespace std;
int main() {
	//Parallel Arrays - Array with two different datatypes
	string month[12];
	int monthdays[12];
	for (int i = 0; i < 12; i++)
	{
		cout << "Month: ";
		cin >> month[i];
		cout << "\t Days in this month: ";
		cin >> monthdays[i];
	}

	cout << "month[i]" << "\t" << "monthdays[i]" << endl;
	for (int i = 0;  i < 12;  i++)
	{
		cout << month[i] << "\t\t\t" << monthdays[i] << endl;
	}
	return 0;
}

Multi Dimensional Array

2D Array


#include <iostream>
#include <string>
using namespace std;
int main() {
	//2D Array - 12 rows and 2 columns
	string month[12][2] = { 
    	{"Jan", "January"},
		{"Feb", "February"},
		{"Mar", "March"},
		{"Apr", "April"},
		{"May", "May"},
		{"Jun", "June"},
		{"Jul", "July"},
		{"Aug", "August"},
		{"Sep", "September"},
		{"Oct", "October"},
		{"Nov", "November"},
		{"Dec", "December"} };
	int monthdays[] = { 31,28,31,30,
						31,30,31,31,
						30,31,30,31 };

	//cout << "month[i]" << "\t" << "monthdays[i]" << endl;
	for (int i = 0;  i < 12;  i++)
	{
		cout << month[i][0] << "\t" << month[i][1] 
			<< "\t\t" << monthdays[i] << endl;
	}
	return 0;
}

output:

Passing array to the function

In the following program, the array is passed to a function.


#include <iostream>
#include <string>
using namespace std;

void printArray(string arr[12][2], int arr2[12])
{
	for (int i = 0; i < 12; i++)
	{
		cout << arr[i][0] << "\t" << arr[i][1]
			<< "\t\t" << arr2[i] << endl;
	}
	return;
}

void changeDays(string arr[12][2], int arr2[12])
{
	int mon,days;
	cout << "Enter the month to change the days for (1-12):";
	cin >> mon;
	cout << "Enter the number of days :";
	cin >> days;
	arr2[mon - 1] = days;
	return;
}

int main() {
	//2D Array - 12 rows and 2 columns
	string month[12][2] = { 
    	{"Jan", "January"},						
    	{"Feb", "February"},
		{"Mar", "March"},
		{"Apr", "April"},
		{"May", "May"},
		{"Jun", "June"},
		{"Jul", "July"},
		{"Aug", "August"},
		{"Sep", "September"},
		{"Oct", "October"},
		{"Nov", "November"},
		{"Dec", "December"} };
	int monthdays[] = { 31,28,31,30,
						31,30,31,31,
						30,31,30,31 };

	do
	{
		int opt;
		cout << "Main menu" << endl;
		cout << "=========" << endl;
		cout << "1. Change days of a month." << endl;
		cout << "2. Print the month and days." << endl;
		cout << "3. Exit." << endl;
		cout << "Enter your selection: ";
		cin >> opt;

		switch (opt)
		{
		case 1:
			changeDays(month, monthdays);
			break;
		case 2:
			printArray(month, monthdays);
			break;
		case 3:
			cout << "Exiting program";
			exit(0);
			break;
		default:
			cout << "Invalid Option"; 
			break;
		}
	} while (true);
}

output:


#include <iostream>
#include <string>
using namespace std;
void GetInfo(string arrItem[3], double arrPrice[3]);
void PrintInfo(string arrItem[3], double arrPrice[3]);
int main() {
	string items[3];
	double prices[3];
	do {
		int opt;
		cout << "Menu" << endl;
		cout << "1. Get Info" << endl;
		cout << "2. Print Info" << endl;
		cout << "3. Exit" << endl;
		cout << "What do you want to do? : ";
		cin >> opt;
		switch (opt)
		{
		case 1:
			GetInfo(items, prices);
			break;
		case 2: 
			PrintInfo(items, prices);
			break;
		case 3:
			cout << "Thank you for using this program." ;
			exit(0);
			break;
		default:
			cout << "Invalid option. Enter 1-3.";
			break;
		}
	} while (true);
	return 0;
}
void GetInfo(string arrItem[3], double arrPrice[3]) {
	for (int i = 0; i < 3; i++) {
		cout << "Enter the item : ";
		cin >> arrItem[i];
		cout << "\t Enter the price : ";
		cin >> arrPrice[i];
	}
}
void PrintInfo(string arrItem[3], double arrPrice[3]) {
	for (int i = 0; i < 3; i++) {
		cout << i + 1 << ") " << arrItem[i] << "\t" << arrPrice[i] << "\n";
	}
}
Output:

Comments

Popular posts from this blog

A Comprehensive Evaluation of the Internal Consulting Process: Steps and Considerations

Introduction Internal consulting has emerged as a critical function within organizations, offering in-house expertise to solve complex business problems and drive change. It closely mirrors external consulting in methodology but is differentiated by the consultant's intimate knowledge of the organization and a vested interest in its long-term success. This article aims to evaluate the key steps involved in the internal consulting process, offering insights into each phase's significance and challenges. Steps in the Internal Consulting Process The internal consulting process can generally be segmented into five distinct stages: Initial Assessment, Data Collection and Analysis, Solution Development, Implementation, and Evaluation. Below is an evaluation of each step: Step 1: Initial Assessment Objective: To understand the problem or opportunity area and define the scope of the project. Significance: A well-defined scope ensures that the consulting project stays focused and manage...

The Evolving Landscape of Consulting Practice: Changes and Implications

Introduction Consulting is a field that thrives on its ability to adapt to market demands and emerging trends. As businesses evolve due to technological advancements, shifts in consumer behavior, and fluctuations in global markets, consulting practices must keep pace. This article explores some of the significant changes currently transforming the consulting industry and discusses their implications for both consultants and clients. Technological Disruption Data Analytics and Artificial Intelligence Consulting firms are increasingly integrating data analytics and artificial intelligence into their service offerings. These technologies allow consultants to offer data-driven insights that can significantly enhance strategic decision-making. This evolution means consultants now need skills in data interpretation and analysis, alongside their traditional expertise in business strategy. Virtual Consulting Platforms The advent of digital platforms enables consulting services to be offered re...

The Skillset of Internal Consultants: A Comparative Analysis

Introduction In the organizational landscape, the role of internal consultants has gained prominence due to the increasing complexity of business problems and the need for specialized in-house expertise. While many skills required for internal consulting overlap with those of external consultants, there are distinct abilities that set them apart. This article aims to compare and contrast these skill sets to provide a clearer understanding of what makes an effective internal consultant. Skills Common to Both Internal and External Consultants Problem-Solving Both types of consultants need to excel at identifying issues and creating viable solutions. Critical thinking and analytical skills are paramount for dissecting complex situations and recommending actionable strategies. Communication Excellent communication skills are a must for any consultant. Whether it’s making a presentation to stakeholders, writing a report, or simply discussing ideas with a team, effective communication is key...