C/C++, KDEVELOP

Basics

  1. Simple Types
  2. Strings
  3. Arrays and Structs
  4. Operators

Program Flow

Functions

Classes and Objects

X Window

KDevelop


-----------------
© Alfred Nussbaumer
Updated:
09 December 2021
-----------------

Arrays and Structs

An array is a collection of objects of the same type, one- ore multiple-dimensional. The next examples show you how to use arrays.

Single-dimensional Array

The next example introduces the usage of single-dimensional arrays:

#include <iostream.h>
#define NUMBER 3

int main() {
  int values[NUMBER];
  int sum = 0;

  for (int i=0; i<NUMBER; i++) {
    cout << i << ". input (" << NUMBER << "): ";
    cin >> values[i];
  }

  for (int i=0; i<NUMBER; i++) sum+=values[i];
  for (int i=0; i<NUMBER; i++) cout << values[i] << " ";
  cout << "avg: " << (double) sum / NUMBER << endl;
}

The sample run returns the avarage value of three numbers:

0. input (3): 3
1. input (3): 4
2. input (3): 3
3 4 3 avg: 3.33333

Arrays of Strings

Strings may be stored into an array.

#include <iostream.h>

int main() {
  char names[3][10] = {"sarah", "bob", "alex"};

  for (int i=0; i<3; i++) cout << names[i] << endl;
}

sarah
bob
alex

Multiple-dimensional Arrays

Data from a two-dimensional array can be output like a table using rows and columns:

#include <iostream.h>

int main() {
  int matrix[3][4] = {{1,-4,2,3}, 
                      {3,0,-5,3}, 
                      {5,-1,4,3}};
  for (int i=0; i<3; i++) {
    for (int j=0; j<4; j++) cout << matrix[i][j] << ", ";
    cout << endl;
  }
}

1, -4, 2, 3, 
3, 0, -5, 3, 
5, -1, 4, 3,

Structs

Within structs values of different types may be stored. The next example shows how to read strings and integers.

#include <iostream.h>

int main() {
  struct persons {
    char name[20];
    int age;
  };

  struct persons person;

  cout << "Name: ";
  cin >> person.name;
  cout << "Alter: ";
  cin >> person.age;

  cout << person.name << " is " << person.age << " years old." << endl;
}

The program's user has to type a string and an integer...

Name: micky
Alter: 10
micky is 10 years old.


© Alfred Nussbaumer, Weblog "MiniNuss"