ANINDAM IT

SEO/SEM

C++ Array

C++ Notes: Array Examples

Example -- adding all elements of an array

This program values into an array and sum them. Assume fewer than 1000 input values. Yes, we could have summed them in the input loop.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

// arrays/readsum.cpp -- Read numbers into an array and sum them.

// Fred Swartz - 2003-11-20

#include <iostream>

using namespace std;

int main() {

int a[1000]; // Declare an array of 1000 ints

int n = 0; // Number of values in a.

while (cin >> a[n]) {

n++;

}

int sum = 0; // Start the total sum at 0.

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

sum = sum + a[i]; // Add the next element to the total

}

 

cout << sum << endl;

 

return 0;

}

Why read numbers into memory

The previous example, which reads numbers into an array then sums the elements of the array, is not a convincing use of arrays. It would have been just as easy to add them while we were reading them.

But usually the computation can not be performed while reading, for example, sorting them and printing them in order by their value. An even simpler example is given below - printing them in reverse order of input.

Example -- printing the input values last to first

Here is something than can't be done with a simple input loop.

1

2

3

4

5

6

7

8

9

10

11

12

 

 

 

 

 

 

 

 

 

 

// arrays/reverse-input.cpp - Reverses order of numbers in input.

#include <iostream>

using namespace std;

int main() {

//--- Declare array and number of elements in it.

float a[100000];

int n; // Number of values currenlty in array.

 

//--- Read numbers into an array

n = 0;

while (cin >> a[n]) {

n++;

}

 

//--- Print array in reverse order

for (int i=n-1; i>=0; i--) {

cout << a[i] << endl;

}

 

return 0;

}//end main

Copyleft 2000-3 Fred Swartz Last update 2003-11-24, URL=undefined

 

C++ Notes: Array Memory Diagrams

Here is an array declaration and code to initialize it.

int a[5]; // Allocates memory for 5 ints.

. . .

a[0] = 1;

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

a[i] = a[i-1] * 2;

}

Arrays are often represented with diagrams that represent their memory use. The diagram below is one typical way to represent the memory used by an array.

Each box represents the amount of memory needed to hold one array element. For ints this is usually 4 bytes. We can write the value of an element inside the box. Pointers hold the memory address of other data and are represented by a black disk with an arrow pointing to the data it references.

The actual array variable, a in this example, is a pointer to the memory for all of its elements. A common shortcut is to omit writing the array variable, and write only the elements that hold the data because these are usually the focus of attention. Sometimes the cells are written horizontally, especially when showing C-strings (arrays of chararcters).

 

or simply

 

 

or just

 

Copyleft 2003 Fred Swartz Last update 2003-11-24, URL=undefined

 

C++ Notes: C-Strings

Strings

There are two ways to represent character strings in C++.

Arrays of characters, terminated by a "zero" value, are commonly used. These are referred to as "c-strings" to distinguish them from the string type that was introduced in the C++ Standard Template Library.

The string class is a relatively late addition to C++ that represents strings as objects. This class is generally easier to use than c-strings, but you usually can not avoid some use of c-strings.

Characters

Individual characters (type char) are stored in single bytes. A character literal is surrounded by single quotes (eg, 'a', ')', ...). Double quotes are used to represent a c-string literal. Eg, "a" is a c-string consisting of one character followed by a zero. Some characters need to be preceded by a special escape character (the backslash), because they have some meaning to the compiler. For example, '\'' is a single quote, '\\' is a single backslash, '\n' is the newline character, and there are others.

Arrays of Characters terminated with "zero"

C-strings are stored as characters in an array. Following the characters there is a character with code zero. You can write this as either 0 or '\0'. The name for this ASCII character is NUL, but that should not be confused with the special pointer value NULL (which should not be used for this purpose).

Quoted Strings

A double-quoted string of characters is a common way to write an array of characters. The string "Hello" represents and array of six (not 5) characters. The last character is the terminating zero code. Example,

char greeting[] = "Hello";

is the same as

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Using a quoted string as an array

A quoted string really represents an array, so it can even be subscripted. For example,

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

cout << "Hello"[i];

}

Include files

If you are using the c-string and character functions, you must have

#include <cstring>

#include <cctype>

or for old compilers

#include <string.h>

#include <ctype.h>

Copyleft 1996 Fred Swartz Last update 2003-12-02, URL=undefined

 

C++ Notes: 2-Dimensional Arrays

Data that is in rows and columns is usually stored in 2-dimensional arrays.

Declaring of 2-dimensional arrays

Two-dimensional arrays are declared by specifying the number of rows then the number of columns.

int a[30][10]; // declares an int array of 30 rows and 10 columns.

char ticTacToeBoard[3][3]; // three rows and three columns of chars.

Initializing 2-dimensional arrays

Unless specified, all initial values of arrays are garbage. You can specify initial values by enclosing each row in curly braces like this:

char ticTacToeBoard[3][3] = {{'x', 'x', 'o'},

{'o', 'o', 'x'},

{'x', 'o', ' '}

};

If some elements are omitted in the initialization list, they are set to zero.

Subscripting 2-dimensional arrays

Write subscripts as x[row][col]. Passing over all elements of a two-dimensional array is usually done with two nested for loops.

// clear the board

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

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

ticTacToeBoard[row][col] = ' ';

}

}

Passing 2-dimensional arrays as parameters

C++ doesn't care about bounds, but it needs to compute the memory address given the subscripts (see below). To do this it needs to know the row width (number of columns). Therefore formal 2-dimensional array parameters must be declared with the row size, altho the number of rows may be omitted. For example,

void clearBoard(ticTacToeBoard[][3]) {

. . .

}

Related Pages

Arrays of Arrays

Copyleft 2000 Fred Swartz Last update 2004-01-22, URL=undefined

 

C++ Notes: 2-D Array Memory Layout

Two kinds of multi-dimensional arrays.

There are two basic ways of implementing 2-dimensional arrays: rectangular, sequential, two-dimensional arrays and arrays of arrays. Some languages use one method, some another, and some both. C++ allows both methods, and each has its advantages and disadvantages.

rectangular sequential arrays. In this case the rows are laid out sequentially in memory. This provides simplicity in memory management and a slight speed advantage. This is the kind of array C/C++ creates by default.

Arrays of arrays. In this style each element of a one-dimensional array is a pointer to another array. This is a common way to create an array of C-strings (a zero-terminated array of characters). This is also useful if the rows are uneven length or are dynamically allocated. The disadvantage is that memory management is more complex, often requiring dynamic allocation and deallocation. This is the only kind of multi-dimensional array in Java. See Arrays of Arrays.

Rectangular arrays allocated in memory by row

Let's see how the memory is allocated for this array.

char ttt[3][3] = {{'x', 'x', 'o'},

{'o', 'o', 'x'},

{'x', 'o', ' '}

};

The memory for this array could be visualized as in the diagram to the right, which identifies a few cells by their subscripts.

 

 

Because memory is addressed linearly, a better representation is like the diagram to the left.

Computing the address of an array element

C++ must compute the memory address of each array element that it accesses. C++ does this automatically, but it helps to understand what's going on "under the hood". Assume the following declaration:

char a[ROWS][COLS]; // assume ROWS and COLS are const ints

Because arrays are laid out in memory by row, each row length is COLS (the number of columns is the size of a row). Let's assume that you want to find the address of a[r][c]. The baseAddress of the array is the address of the first element. The rowSize is COLS in the above example. The elementSize is the number of bytes required to represent the data (typically 1 for char, 4 for int, 4 for float, and 8 for double.

address = baseAddress + elementSize * (r*rowSize + c);

Note

The number of rows (ROWS) is not used in the computation.

Because the number of rows is not used, there is no need to pass it when declaring a formal array parameter for a two-dimension array.

Copyleft 2003 Fred Swartz Last update 2003-12-02, URL=undefined

 

C++: C-Strings - Programming Exercise Solutions - main

Here is a min program. The functions it calls are in another file, and an include file which contains those headers is used.

C-Strings - Programming Exercise Solutions - functions

C-Strings - Programming Exercise Solutions - header

C++ Class Program

I need to create a program that has a class that keeps track of the dog's name, breed, age, and license fee, which is static. I have to include a method to display the info. This is what I have thus far. I am getting an error and not sure why. Please help.

CPP / C++ / C Code:

#include <iostream>

#include <cstring>

#include <string>

using namespace std;

class Dog

{

private:

char dog_Name[30];

char breed[30];

int age;

static int lic_fee;

public:

Dog();

void setListData(char*pn,char*on,int a);

void displayDog();

void displayInfo();

};

Dog::Dog()

{

strcpy(dog_Name,"");

strcpy(breed,"");

age=0;

static double lic_fee = 12.25;

}

void Dog::setListData(char*pN,char*on,int a)

{

strcpy(dog_Name,pN);

strcpy(breed,on);

age=a;

static double lic_fee = 12.25;

}

void Dog::displayDog()

{

cout <<"Dog Name: "<< dog_Name << "Dog Breed: " << breed << "Age of Dog: " << age << "License Fee: " << lic_fee << endl;

}

void DisplayInfo(Dog DogRec[], int p = 8)

{

cout << "Dog Name \t Breed \t Dog Age \t License Fee" << endl;

for(int i=0;i<p; ++i)

{

if(strcmp(DogRec[i]) == 0)

{

cout << DogRec[i].dog_Name << '\t'<< breed[i]<< '\t' <<

age[i]<< '\t' << lic_fee<< endl;

}

}

}

 

#include <iostream>

#include <string>

#include <cstring>

#include "dog.h"

using namespace std;

void main()

{

Dog DogRec[8];

DogRec[0].setListData("Rocko", "Maltese", 4);

DogRec[1].setListData("Nicki", "Terrier", 9);

DogRec[2].setListData("Harvey", "Golden Retriever", 15);

DogRec[3].setListData("Dale Jr", "Boxer", 38);

DogRec[4].setListData("Boxer", "Boxer", 8);

DogRec[5].setListData ("JJ", "German Sheperd", 5);

DogRec[6].setListData("Misty", "Collie", 46);

DogRec[7].setListData("Carter", "Cocker Spaniel", 7);

DisplayInfo(DogRec,8);

getch();

}

// strings/cstring-array-main.cpp - Example C-string functions using arrays.

// 2003-12-10 Fred Swartz

//============================================ includes

#include <iostream>

#include <cstring>

using namespace std;

#include "cstring-array.h"

//============================================ globals

int testCount = 0;

int testFailures = 0;

//============================================ prototypes

void check(bool passed, char testName[]);

//============================================ main

int main() {

char s[100];

char t[100];

//-- trimRight

strcpy(s, "How are you? ");

trimRight(s);

check(strcmp(s, "How are you?")==0, "trimRight 1");

 

strcpy(s, "How are you?");

trimRight(s);

check(strcmp(s, "How are you?")==0, "trimRight 2");

 

strcpy(s, "");

trimRight(s);

check(strcmp(s, "")==0, "trimRight 3");

 

//-- truncate

strcpy(s, "How are you?");

truncate(s, 3);

check(strcmp(s, "How")==0, "truncate 1");

 

//-- padRight

strcpy(s, "test");

padRight(s, 6);

check(strcmp(s, "test ")==0, "padRight 1");

 

strcpy(s, "test");

padRight(s, 2);

check(strcmp(s, "test")==0, "padRight 2");

 

//-- isAlpha

check( isAlpha("test"), "isAlpha 1");

check( isAlpha("") , "isAlpha 2");

check(!isAlpha("a ") , "isAlpha 3");

check(!isAlpha("123") , "isAlpha 4");

 

//-- count

check(count("abracadabra", 'a')==5, "count 1");

check(count("xyz", 'a') == 0 , "count 2");

check(count("", 'a') == 0 , "count 3");

 

cout << endl << "Summary: Passed " << testCount-testFailures

<< ", Failed " << testFailures << endl;

 

char x; cout << "Enter any char to exit."; cin.get(x); // keep window open

return 0;

}

//============================================ check

void check(bool passed, char testName[]) {

testCount++;

if (passed) {

cout << "Passed " << testName << endl;

} else {

cout << "FAILED " << testName << endl;

testFailures++;

}

}

// strings/cstring-array-main.cpp - Example C-string functions using arrays.

// 2003-12-10 Fred Swartz

//============================================ includes

#include <iostream>

#include <cstring>

using namespace std;

#include "cstring-array.h"

//============================================ globals

int testCount = 0;

int testFailures = 0;

//============================================ prototypes

void check(bool passed, char testName[]);

//============================================ main

int main() {

char s[100];

char t[100];

//-- trimRight

strcpy(s, "How are you? ");

trimRight(s);

check(strcmp(s, "How are you?")==0, "trimRight 1");

 

strcpy(s, "How are you?");

trimRight(s);

check(strcmp(s, "How are you?")==0, "trimRight 2");

 

strcpy(s, "");

trimRight(s);

check(strcmp(s, "")==0, "trimRight 3");

 

//-- truncate

strcpy(s, "How are you?");

truncate(s, 3);

check(strcmp(s, "How")==0, "truncate 1");

 

//-- padRight

strcpy(s, "test");

padRight(s, 6);

check(strcmp(s, "test ")==0, "padRight 1");

 

strcpy(s, "test");

padRight(s, 2);

check(strcmp(s, "test")==0, "padRight 2");

 

//-- isAlpha

check( isAlpha("test"), "isAlpha 1");

check( isAlpha("") , "isAlpha 2");

check(!isAlpha("a ") , "isAlpha 3");

check(!isAlpha("123") , "isAlpha 4");

 

//-- count

check(count("abracadabra", 'a')==5, "count 1");

check(count("xyz", 'a') == 0 , "count 2");

check(count("", 'a') == 0 , "count 3");

 

cout << endl << "Summary: Passed " << testCount-testFailures

<< ", Failed " << testFailures << endl;

 

char x; cout << "Enter any char to exit."; cin.get(x); // keep window open

return 0;

}

//============================================ check

void check(bool passed, char testName[]) {

testCount++;

if (passed) {

cout << "Passed " << testName << endl;

} else {

cout << "FAILED " << testName << endl;

testFailures++;

}

}

return 0;

}

//============================================ check

void check(bool passed, char testName[]) {

testCount++;

if (passed) {

cout << "Passed " << testName << endl;

} else {

cout << "FAILED " << testName << endl;

testFailures++;

}

}

 

 

I've got this program..its a specification, client and implementation file.

// Program Money manipulates instances of class MoneyType.

// From here through the line of asterisks should be in a specification file.

class MoneyType

{

public:

void Initialize(long, long);

long DollarsAre() const;

long CentsAre() const;

MoneyType Add(MoneyType) const;

private:

long dollars;

long cents;

};

//**********************************************************

// From here through the next line of asterisks should be in the client file.

// The client file must include the specification file.

#include

using namespace std;

int main ()

{

MoneyType money1;

MoneyType money2;

MoneyType money3;

money1.Initialize(10, 59);

money2.Initialize(20, 70);

money3 = money1.Add(money2);

cout "$" money3.DollarsAre() "."

money3.CentsAre() endl;

return 0;

}

// From here through the rest of the file should be in the an implementation file.

// The implementation file must include the specification file.

// Post: dollars is set to newDollars; cents is set to newCents.

void MoneyType::Initialize(long newDollars, long newCents)

{

dollars = newDollars;

cents = newCents;

}

// Post: Class member dollars is returned.

long MoneyType::DollarsAre() const

{

return dollars;

}

// Post: Class member cents is returned.

long MoneyType::CentsAre() const

{

return cents;

}

// Pre: Both operands have been initialized.

// Post: value + self is returned.

MoneyType MoneyType::Add(MoneyType value) const

{

MoneyType result;

result.cents = cents + value.cents;

result.dollars = dollars + value.dollars;

return result;

}

I want to add class constructors to class MoneyType. One should have parameters, and one should be parameter less setting dollars and cents to zero.

I need help writing a program for my C++ class. The assignment is to write a prgram where the user enters a password which must contain at least 6 characters (containing at least 1 lowercase, 1 uppercase, and one digit)and I need to validate the entry as indicated and after reading all of the characters, specify why the password is not acceptable. I have it working but it is reading each character and then outputs after each character the reason it didn't meet the requirements. I want the program to read all characters and then output only once explaining the exact reason it did not meet. Anything you can do to help me will be greatly appreciated!!!

#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;

//Function Prototype
void testNum(char [], int);

int main()
{
const int SIZE = 7; //Array Size
char password[SIZE]; //To hold password
int length;
length = strlen(password);

//Get the password.
cout<< "Enter a password.\n";
cin.getline(password, SIZE);
length = strlen(password);

while (length <6)
{
cout<< "Please enter a password with at least 6 characters.\n";
cin.getline(password, SIZE);
length = strlen(password);
}


//Call function.
testNum(password, SIZE);


return 0;
}
//Function Definition

void testNum(char pswd[], int size)
{

int count;

//Test for validity
for (count = 0; count<size-1; count++)
{
if (!isupper(pswd[count]))
cout << "The password does not contain an uppercase letter.\n";

if (!islower(pswd[count]))
cout << "The password does not contain a lowercase letter.\n";

if (!isdigit(pswd[count]))
cout << "The password does not contain a digit.\n";

}


}

 

Recent Videos

No recent videos