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

Programming - U2 ( Array & String )

The document provides a comprehensive overview of basic arrays and strings in programming, detailing how to define, access, and manipulate arrays, including multidimensional arrays. It also covers functions, including their definition, calling, overloading, and recursion, emphasizing the importance of modular programming. Additionally, it introduces string manipulation and character testing, along with examples and exercises for practical application.

Uploaded by

ermikasa2716
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Programming - U2 ( Array & String )

The document provides a comprehensive overview of basic arrays and strings in programming, detailing how to define, access, and manipulate arrays, including multidimensional arrays. It also covers functions, including their definition, calling, overloading, and recursion, emphasizing the importance of modular programming. Additionally, it introduces string manipulation and character testing, along with examples and exercises for practical application.

Uploaded by

ermikasa2716
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

BASIC ARRAYS AND STRINGS

Variables and Multiple Values


• A single variable is capable of storing only one
value at a time.
• For example, to perform computations on the
ages of four students, we would need four
variables to store the ages.
Array
• An array allows us to group
a number of values of the
same type into one large
unit.
• The individual values are
stored together in
consecutive memory
locations and they are
referred to as elements of
the array.
Defining Arrays
The size must be a constant of
• Syntax one of the integer types.
Once defined, the size is
type name[size]; fixed.
• The size specifies the maximum number of
elements that the array can hold
• Examples:
long populations[210];
float salaries[15];
char name[30];
More Examples ...
const int SIZE = 110;
int num_people = 100;

char letters[26];
double atomic_weights[SIZE];
float heights[num_people];
float areas[34.4];

Which of these array declarations are valid?


Accessing the Elements
• The entire array has only
one name.
• Each element is assigned
a number known as a
subscript or an array
index.
• Each element can be
assigned as an individual
variable through the
subscript.
Accessing the Elements, contd
• To access an element of the array, you use
Subscript numbering starts at
array_name[subscript] zero. The subscript of the last
element is one less than the total
• Example: number of elements in the array.

int age[4]; //an array to hold 4


integers
cout<<”Enter the ages of four students:
“;

cin>>>>age[0]>>age[1]>>age[2]>>age[3];

cout<<”After two years”


<<”\nStudent 1 will be “<<age[0]+2
<<”\nStudent 2 will be “<<age[1]+2
<<”\nStudent 3 will be “<<age[2]+2
<<”\nStudent 4 will be “<<age[3]+2;
Arrays and for Loops
• Array elements are conveniently accessed
using for loops.
const int TOTAL = 100;
int age[TOTAL]; //an array to hold TOTAL
integers
cout<<”Enter the ages of “<<TOTAL<<” students:
“;

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


cin>>>>age[i];

cout<<”After two years”;


for (int j=0; j<TOTAL; ++j)
cout<<”\nStudent “<<j+1<<” will be “<<age[j]
+2;
Note
• It is not possible to assign one array to
another or use an array in a expression
hoping to affect all its elements.
Initializing Arrays
• Syntax
type array_name[size] = initializer_list;
• The initializer list contains a set of comma
separated values within a pair of curly braces.
• Example
int age[4] = {25, 12, 15, 27};
/* 25 is stored in age[0], 12 is stored in age[1],
15 is stored in age[2], 27 is stored in age[3] */
Initializing Arrays, contd...
• C++ allows us to define an array without
specifying its size, as long as we provide an
initialization list.
• Example
double factors[] = {1.0, 1.5, 2.0, 2.5};
More Examples

int age[4] = {25, 12};


//age[0] = 25, age[1]=12, age[2]=0, age[3]=0

char name[] = {'B', 'i', 'r', 'u', 'k'};


double factors[4] = {1.0, 1.5, 2.0, 2.5, 3.0};
//ERROR!
Strings
• A string is a special array of characters. It is an
array of type char ending with a null character
('\0').
• Example
char greeting[] = { 'H', 'e', 'l', 'l', 'o', '!', '\0'};
More on Strings
• Strings are special because
– We have an alternate form of initialization
using double quotes
char greeting[] = “Hello!”;
– Strings can be used with cin and cout like any
other variable.
String Manipulations

C++ provides us a library to operate on C++
strings (Also known as c-style strings).

These are operations like finding the length,
concatenation, assignment, etc...

Add the following to your program
#include <cstring>
using namespace std;
Some of the Functions

strlen(char str[])

Returns the number of characters in str

strcat(char first[], char second[])

Concatenates (adds at the end) the string second
on to string first

strcpy(char first[], char second[])

Will copy the contents of second into first

strcmp(char first[], char second[])

Compares the two strings and returns 0 if they are equal, a
negative number if the first string comes before the second in
alphabetical order and a positive number if the first string comes
after the second in alphabetical order
String/Number Conversion

To convert strings to numbers and vice versa,
C++ defines functions in the cstdlib library.

atoi(char s[]), atol(char s[]), atof(char s[])

Converts s to an integer, long, and float
(respectively) and returns the value
Character Testing

C++ provides us with functions to test the values of
characters in the cctype library.

All of these functions take a character as an input
and return a boolean.

isalpha, isalnum, isdigit, islower, isupper, ispunct,
isspace.

In addition, the functions tolower and toupper are
used to convert the cases of characters.
The Standard String

Standard C++ provides an easier way to work with strings in the
library string.

In this library, a type called string is defined.
#include <string>
using std::string;
string str1, str2;
str1 = “Abebe”;
str2 = “Kebede”;
cout<<str1+” “+str2; //concatenation
if (str1 == “Abebe”)
cout<<”Comparison..”;
Reading Assignment

Read about arrays of cstrings

Read about the standard string
Multidimensional Arrays

So far, we have seen one dimensional arrays.

We can also have arrays to store N dimensions of
information. => Multidimensional arrays

Examples of multidimensional data

Matrices

Grade reports of all students

Yearly weather reports (temperature) summarized by
month and day.

We don't usually need to store more than 2D data.
Defining Two Dimensional Arrays

Syntax
type name[size for dim 1][size for dim 2];

Example
double score[3][4];

It is best to think of a 2D array as a table with
rows and columns of elements
2D Arrays

12.0


To access an element of the array, we use two
subscripts – one for the column and one for the row.

Example:
score[1][2] = 12.0;
cout<<score[2][3]<<endl;
2D arrays and nested for loops

This code will take from the user the scores of 80 students
for 4 courses
2D arrays and nested for loops

This code will average the scores of the 4 courses for each
student and stores the results in a one dimensional array.
2D arrays and nested for loops

This code will display the scores and the averages.


Initializing 2D Arrays

You can consider a 2D array to be an array of
arrays.

The initialization statement uses an initializer
list where each element is by itself an
initializer list for a single row.
float scores[2][3] = {{1, 2, 3}, {4, 5, 6}};
Defining and using 3D Arrays
const int YEARS = 10;
const int MONTHS = 12;
const int DAYS = 30;
double temperature[YEARS][MONTHS][DAYS];

//Set the temperature for Tahsas 9, 2014
INTRODUCTION TO FUNCTIONS
Modular programming
A function is a collection of statements that
performs a specific task. (also called a module)
A function performs some computation and usually
yields a result.
Modular Programming: breaking down a program
into a set of manageable functions, or modules.
Real world programs can easily have thousands of
lines of code and unless they are modularized,
they can be very difficult to modify and maintain.
Function Definition
When defining a function, we give it
Name: a function must have a unique name.
Naming rules are the same as those for variables
Parameter List: a list of variables that hold values
being passed into the function
Body: the set of the statements that make up the
function
Return Type: the data type of the value being sent
back from the function.
Example
float cube(float num)
{
float r = num*num*num;
return r;
}

Identify the parts of this function.


Function Call Statements
• The main function starts executing
automatically when the program starts.
• All other functions have to be called
explicitly to start executing.
• This is done by using function call
statements.
Example With Library Functions
int main()
{
float a=5.0, b=3.0, c;
c = pow(a, b);
cout<<c<<endl;
return 0;
}
Function Overloading
These functions having the same name but
different arguments are known as overloaded
functions. For example:
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Recursion
A function that calls itself is known as a
recursive function. And, this technique is
known as recursion.
Example: write a function that calculate the
factorial of a given number.
int factorial(int n)
{
if (n > 1)
{
return n * factorial(n - 1);
}
else
{ return 1; } }
Exercises
1. Write a program that accepts a 2D integer array from the user and
a) Sums all the elements
b) Stores the sum of each row in a 1D integer array
c) Stores the sum of each column in a 1D integer array
2. Write a program that accepts two square matrices of identical
dimensions from the user and
a) Transposes the two matrices and displays the results
b) Performs matrix addition and stores the result in a third matrix
c) Performs matrix multiplication and stores the result in a third matrix

You might also like