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

What Is An Array?: Introduction To Computing

This document discusses arrays and strings in computing. It begins by defining an array as a collection of identical data objects stored consecutively in memory locations under a common name. Arrays have properties like being zero-indexed and only holding one data type. The document describes how to declare and initialize arrays, and access array elements using indexes. It also discusses passing arrays as parameters to functions. The document notes that strings are collections of characters used to represent words, sentences, etc. It states that in C++, strings are implemented using character arrays.

Uploaded by

sfd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
206 views

What Is An Array?: Introduction To Computing

This document discusses arrays and strings in computing. It begins by defining an array as a collection of identical data objects stored consecutively in memory locations under a common name. Arrays have properties like being zero-indexed and only holding one data type. The document describes how to declare and initialize arrays, and access array elements using indexes. It also discusses passing arrays as parameters to functions. The document notes that strings are collections of characters used to represent words, sentences, etc. It states that in C++, strings are implemented using character arrays.

Uploaded by

sfd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Introduction to Computing

Chapter six

Arrays and Strings

6. What is An Array?
 A collection of identical data objects, which are stored in consecutive memory
locations under a common heading or a variable name. In other words, an array is a
group or a table of values referred to by the same name. The individual values in
array are called elements. Array elements are also variables.
 Set of values of the same type, which have a single name followed by an index. In
C++, square brackets appear around the index right after the name
 A block of memory representing a collection of many simple data variables stored in
a separate array element, and the computer stores all the elements of an array
consecutively in memory.

6.1. Properties of arrays:


 Arrays in C++ are zero-bounded; that is the index of the first element in the array is 0
and the last element is N-1, where N is the size of the array.
 It is illegal to refer to an element outside of the array bounds, and your program will
crash or have unexpected results, depending on the compiler.
 Array can only hold values of one type

6.2. Array declaration


 Declaring the name and type of an array and setting the number of elements in an
array is called dimensioning the array. The array must be declared before one uses in
like other variables. In the array declaration one must define:
1. The type of the array (i.e. integer, floating point, char etc.)
2. Name of the array,
3. The total number of memory locations to be allocated or the maximum value of
each subscript. i.e. the number of elements in the array.
 So the general syntax for the declaration is:

DataTypename arrayname [array size];


 The expression array size, which is the number of elements, must be a constant such
as 10 or a symbolic constant declared before the array declaration, or a constant
expression such as 10*sizeof (int), for which the values are known at the time
compilation takes place.

Compiled By: Markos A. Page 1


Introduction to Computing

Note: array size cannot be a variable whose value is set while the program is running.

Thus to declare an integer with size of 10 having a name of num is: int num [10];
This means: Ten consecutive two byte memory locations will be reserved with the name
num.
 That means, we can store 10 values of type int without having to declare 10 different
variables each one with a different identifier. Instead of that, using an array we can
store 10 different values of the same type, int for example, with a unique identifier.

6.3. Initializing Arrays

Compiled By: Markos A. Page 2


Introduction to Computing

Compiled By: Markos A. Page 3


Introduction to Computing

6.4. Accessing and processing array elements


 In any point of the program in which the array is visible we can access individually
anyone of its elements for reading or modifying it as if it was a normal variable. To
access individual elements, index or subscript is used. The format is the following:
name [ index ]
 In c++ the first element has an index of 0 and the last element has an index, which is
one less the size of the array (i.e. arraysize-1). Thus, from the above declaration,
day[0] is the first element and day[4] is the last element.
 Following the previous examples where day had 5 elements and each element is of
type int, the name, which we can use to refer to each element, is the following one:

For example, to store the value 75 in the third element of the array variable day a suitable
sentence would be: day[2] = 75; //as the third element is found at index 2

Compiled By: Markos A. Page 4


Introduction to Computing

 And, for example, to pass the value of the third element of the array variable day to
the variable a , we could write:
a = day[2];
 Therefore, for all the effects, the expression day[2] is like any variable of type int
with the same properties. Thus an array declaration enables us to create a lot of
variables of the same type with a single declaration and we can use an index to
identify individual elements.
 Notice that the third element of day is specified day[2] , since first is day[0] , second
day[1] , and therefore, third is day[2] . By this same reason, its last element is day
[4]. Since if we wrote day [5], we would be acceding to the sixth element of day and
therefore exceeding the size of the array. This might give you either error or
unexpected value depending on the compiler.
 In C++ it is perfectly valid to exceed the valid range of indices for an Array, which
can cause certain detectable problems, since they do not cause compilation errors but
they can cause unexpected results or serious errors during execution. The reason why
this is allowed will be seen ahead when we begin to use pointers.
 At this point it is important to be able to clearly distinguish between the two uses the
square brackets [ ] have for arrays.
 One is to set the size of arrays during declaration
 The other is to specify indices for a specific array element when accessing the
elements of the array
 We must take care of not confusing these two possible uses of brackets [ ] with arrays:

Eg: int day[5]; // declaration of a new Array (begins with a type name)
day[2] = 75; // access to an element of the Array.
Other valid operations with arrays in accessing and assigning:
int a=1;
day [0] = a;
day[a] = 5;
b = day [a+2];
day [day[a]] = day [2] + 5;
day [day[a]] = day[2] + 5;

Eg: Arrays example, display the sum of the numbers in the array

#include <iostream.h>

int day [ ] = {16, 2, 77, 40, 12071};

int n, result=0;

void main () {

Compiled By: Markos A. Page 5


Introduction to Computing

for ( n=0 ; n<5 ; n++ )

{ result += day[n]; }

cout << result;


getch();

6.5. Arrays as parameters



 At some moment we may need to pass an array to a function as a parameter. In C++ it is not
possible to pass by value a complete block of memory as a parameter, even if it is ordered as an
array, to a function, but it is allowed to pass its address, which has almost the same practical
effect and is a much faster and more efficient operation.
 In order to admit arrays as parameters the only thing that we must do when declaring the
function is to specify in the argument the base type for the array that it contains, an identifier
and a pair of void brackets [ ] . For example, the following function:
void procedure (int arg[])
 Admits a parameter of type "Array of int " called arg . In order to pass to this
function an array declared as:
int myarray [40];
 It would be enough with a call like this
procedure (myarray);

Here you have a complete example:

Compiled By: Markos A. Page 6


Introduction to Computing

 As you can see, the first argument (int arg[] ) admits any array of type int , whatever its
length is, for that reason we have included a second parameter that informs the function
the length of each array that we pass to it as the first parameter so that the for loop that
prints out the array can have the information about the size we are interested about. The
function mult doubles the value of each element and the firstarray is passed to it. After
that the display function is called. The output is modified showing that arrays are passed
by reference.
 To pass an array by value, pass each element to the function

Compiled By: Markos A. Page 7


Introduction to Computing

6.6. Strings of Characters:


What are Strings?
 In all programs and concepts we have seen so far, we have used only numerical variables,
used to express numbers exclusively. But in addition to numerical variables there also
exist strings of characters that allow us to represent successive characters, like words,
sentences, names, texts, etc. Until now we have only used them as constants, but we have
never considered variables able to contain them.
 In C++ there is no specific elementary variable type to store string of characters. In order
to fulfill this feature we can use arrays of type char, which are successions of char
elements. Remember that this data type (char) is the one used to store a single character,
for that reason arrays of them are generally used to make strings of single characters.
 For example, the following array (or string of characters) can store a string up to 20
characters long. You may imagine it thus:

char name [20];

 This maximum size of 20 characters is not required to be always fully used. For
example, name could store at some moment in a program either the string of characters
"Hello" or the string "studying C++”. Therefore, since the array of characters can store
shorter strings than its total length, there has been reached a convention to end the valid
content of a string with a null character, whose constant can be written as '\0’.
 We could represent name (an array of 20 elements of type char) storing the strings of
characters "Hello" and "Studying C++" in the following way

 Notice how after the valid content it is included a null character ('\0') in order to
indicate the end of string. The empty cells (elements) represent indeterminate
values.

6.7. Initialization of Strings


 Because strings of characters are ordinary arrays they fulfill same rules as any
array. For example, if we want to initialize a string of characters with
predetermined values we can do it in a similar way to any other array:

Compiled By: Markos A. Page 8


Introduction to Computing

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


 In this case we would have declared a string of characters (array) of 6 elements of type
char initialized with the characters that compose Hello plus a null character '\0’.
 Nevertheless, string of characters have an additional way to initialize its values: using
constant strings.
 In the expressions we have used in examples of previous chapters there have already
appeared several times constants that represented entire strings of characters. These are
specified enclosed between double quotes ( “ “ ), for example:
Eg: "the result is: "
is a constant string that we have probably used in some occasion.
 Unlike single quotes ( ' ) which allow to specify single character constants, double quotes
( " ) are constants that specify a succession of characters. These strings enclosed between
double quotes have always a null character ( '\0' ) automatically appended at the end.
 Therefore we could initialize the string mystring with values by any of these two ways:
char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char mystring [] = "Hello";
 In both cases the Array or string of characters mystring is declared with a size of 6
characters (elements of type char ): the 5 characters that compose Hello plus a final null
character ( '\0' ) which specifies the end of the string and that, in the second case, when
using double quotes ( " ) it is automatically appended.
 Before going further, you should note that the assignation of multiple constants like
double-quoted constants ( " ) to arrays are only valid when initializing the array, that is,
at the moment when declared.
 The following expressions within a code are not valid for arrays
mystring="Hello"; mystring[] = "Hello";
neither would be: mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };

 So remember: We can "assign" a multiple constant to an Array only at the moment of


initializing it. The reason will be more comprehensible when you know a bit more about
pointers, since then it will be clarified that an array is simply a constant pointer pointing
to an allocated block of memory. And because of this constant feature, the array itself
cannot be assigned any value, but we can assign values to each of the elements of the
array.
 At the moment of initializing an Array it is a special case, since it is not an assignation,
although the same equal sign ( = ) is used. Anyway, have always present the rule
previously underlined.

Assigning Values to Strings


 Just like any other variables, array of character can store values using assignment
operators. But the following is not allowed.
mystring=”Hello”;

Compiled By: Markos A. Page 9


Introduction to Computing

 This is allowed only during initialization. Therefore, since the lvalue of an assignation
can only be an element of an array and not the entire array, what would be valid is to
assign a string of characters to an array of char using a method like this:
 mystring[0] = 'H'; mystring[1] = 'e'; mystring[2] = 'l'; mystring[3] = 'l'; mystring[4]
= 'o'; mystring[5] = '\0';
 But as you may think, this does not seem to be a very practical method. Generally for
assigning values to an array, and more specifically to a string of characters, a series of
functions like strcpy are used. strcpy ( str ing c o py ) is defined in the ( string.h ) library
and can be called the following way:
 strcpy ( string1 , string2 );
 This does copy the content of string2 into string1. string2 can be either an array, a
pointer, or a constant string , so the following line would be a valid way to assign the
constant string "Hello" to mystring :
 strcpy (mystring, "Hello");

 Look how we have needed to include <string.h> header in order to be able to use
function strcpy.
 Although we can always write a simple function like the following setstring with the
same operating than cstring's strcpy :

Compiled By: Markos A. Page 10


Introduction to Computing

Another frequently used method to assign values to an array is by using directly the input stream
( cin ). In this case the value of the string is assigned by the user during program execution.
 When cin is used with strings of characters it is usually used with its getline method, that
can be called following this prototype:
 cin.getline ( char buffer [], int length , char delimiter = ' \n');
 where buffer is the address where to store the input (like an array, for example), length is
the maximum length of the buffer (the size of the array) and delimiter is the character
used to determine the end of the user input, which by default - if we do not include that
parameter - will be the newline character ( '\n' ).
 The following example repeats whatever you type on your keyboard. It is quite simple
but serves as example on how you can use cin.getline with strings:

Compiled By: Markos A. Page 11


Introduction to Computing

 Notice how in both calls to cin.getline we used the same string identifier ( mybuffer ).
What the program does in the second call is simply step on the previous content of buffer
by the new one that is introduced.
 If you remember the section about communication through console, you will
remember that we used the extraction operator ( >> ) to receive data directly from
the standard input. This method can also be used instead of cin.getline with
strings of characters. For example, in our program, when we requested an input
from the user we could have written: cin >> mybuffer;
 This would work, but this method has the following limitations that cin.getline has not:
• It can only receive single words (no complete sentences) since this method uses as
delimiter any occurrence of a blank character, including spaces, tabulators, newlines
and carriage returns.
• It is not allowed to specify a size for the buffer. What makes your program unstable
in case that the user input is longer than the array that will host it.
 For these reasons it is recommendable that whenever you require strings of characters
coming from cin you use cin.getline instead of cin >>

Converting strings to other types


 Due to that a string may contain representations of other data types like numbers it might
be useful to translate that content to a variable of a numeric type. For example, a string

Compiled By: Markos A. Page 12


Introduction to Computing

may contain "1977" , but this is a sequence of 5 chars not so easily convertible to a
single integer data type. The cstdlib ( stdlib.h ) library provides three useful functions
for this purpose:
 •atoi: converts string to int type.
 atol: converts string to long type.
 atof: converts string to float type.
 All of these functions admit one parameter and return a value of the requested type ( int ,
long or float ). These functions combined with getline method of cin are a more reliable
way to get.

Functions to manipulate strings


The cstring library ( string.h ) defines many functions to perform some manipulation operations
with C-like strings (like already explained strcpy). Here you have a brief with the most usual:
a) String length
 Returns the length of a string, not including the null character (\0).
strlen (const char* string );
b) String Concatenation:
 Appends src string at the end of dest string. Returns dest.

Compiled By: Markos A. Page 13


Introduction to Computing

 The string concatenation can have two forms, where the first one is to append the
whole content of the source to the destination the other will append only part of
the source to the destination.
 Appending the whole content of the source
strcat (char* dest , const char* src );
 Appending part of the source
strncat (char* dest , const char* src, int size );
Where size is the number characters to be appended
c) String Copy:
 Overwrites the content of the dest string by the src string. Returns dest.
 The string copy can have two forms, where the first one is to copying the whole
content of the source to the destination and the other will copy only part of the
source to the destination.
 Copy the whole content of the source
strcpy (char* dest , const char* src );
 Appending part of the source
strncpy (char* dest , const char* src, int size );
Where size is the number characters to be copied
d) String Compare:
 Compares the two string string1 and string2.
 The string compare can have two forms, where the first one is to compare the
whole content of the two strings and the other will compare only part of the two
strings.
 Copy the whole content of the source
strcmp (const char* string1 , const char* string2 );
 Appending part of the source
strncmp (const char* string1 , const char* string2, int size );
Where size is the number characters to be compaired
 Both string compare functions returns three different values:
 Returns 0 is the strings are equal
 Returns negative value if the first is less than the second string
 Returns positive value if the first is greater than the second string

6.8Multidimensional Arrays
 Multidimensional arrays can be described as arrays of arrays. For example, a bi-
dimensional array can be imagined as a bi-dimensional table of a uniform concrete data
type.

 Matrix represents a bi-dimensional array of 3 per 5 values of type int . The way to declare
this array would be:

Compiled By: Markos A. Page 14


Introduction to Computing

int matrix[3][5];
 For example, the way to reference the second element vertically and fourth horizontally
in an expression would be: matrix[1][3]

(remember that array indices always begin by 0 )


 Multidimensional arrays are not limited to two indices (two dimensions). They can
contain so many indices as needed, although it is rare to have to represent more than 3
dimensions. Just consider the amount of memory that an array with many indices may
need. For example:
char century [100][365][24][60][60];
 Assigns a char for each second contained in a century, that is more than 3 billion chars !
What would consume about 3000 megabytes of RAM memory if we could declare it?
 Multidimensional arrays are nothing else than an abstraction, since we can simply obtain
the same results with a simple array by putting a factor between its indices:
int matrix [3][5]; is equivalent to
int matrix [15]; (3 * 5 = 15)

 With the only difference that the compiler remembers for us the depth of each
imaginary dimension. Serve as example these two pieces of code, with exactly the
same result, one using bi-dimensional arrays and the other using only simple arrays

Compiled By: Markos A. Page 15


Introduction to Computing

 None of the programs above produce any output on the screen, but both assign values to
the memory block called matrix in the following way:

 We have used defined constants ( #define ) to simplify possible future


modifications of the program, for example, in case that we decided to enlarge
the array to a height of 4 instead of 3 it would be enough by changing the
line:
#define HEIGHT 3
by the following code
#define HEIGHT 4
Worksheet Six
1. Define strlen function (i.e write the function body of strlen)
2. Define the strcmp function and the strncmp function
3. Define strcpy function and the strncpy function
4. Define strcat function and the strncat function
5. Write a program to store the ages of six of your friends in a single array. Store each of the six
ages using the assignment operator. print the ages on the screen

Compiled By: Markos A. Page 16


Introduction to Computing

6. Write a C++ program that accepts 10 integers from the user and finally displays the smallest
value and the largest value.
7. Write a program that accepts ten different integers from the user and display these numbers
after sorting them in increasing order.

Structures
A structure is a collection of one or more variable types grouped together that can be
referred using a single name (group name) and a member name.
You can refer to a structure as a single variable, and you also can initialize, read and change
the parts of a structure (the individual variables that make it up).
Each element (called a member) in a structure can be of different data type.
The General Syntax of structures is:
Struct [structure tag]
{
Member definition;
Member definition;

Member definition;
}[one or more structure variables];
Let us see an example
E.g.: Structure tag
struct Inventory
{
char description[15];
char part_no[6];
int quantity; members of the structure
float cost;
}; // all structures end with semicolon
Another example might be:
struct Student
{
char ID[8];
char FName[15];
char LName[15];
char Sex;
int age;
float CGPA;
};
The above “Student” structure is aimed to store student record with all the relevant details.
After the definition of the structure, one can declare a structure variable using the structure
tag. If we need two variables to have the above structure property then the declaration
would be: 
struct Inventory inv1,inv2; //or
struct Student Stud1,stud2,Stud3;

Compiled By: Markos A. Page 17


Introduction to Computing

 Structure tag is not a variable name. Unlike array names, which reference the array
as variables, a structure tag is simply a label for the structure’s format.
 The structure tag Inventory informs C++ that the tag called Inventory looks like two
character arrays followed by one integer and one float variables.
 A structure tag is actually a newly defined data type that you, the programmer,
defined.

Referencing members of a structure


 To refer to the members of a structure we need to use the dot operator (.)
 The General syntax to access members of a structure variable would be:
VarName.Member
 Where VarName is the varaibale name of the structure variable And Member is
varaibale name of the members of the structure

Eg:
For the above student structure:
struct Student Stud; //declaring Stud to have the property of the Student structure
strcpy(Stud.FName,”Abebe”); //assigned Abebe as First Name
Stud.CGPA=3.21; //assignes 3.21 as CGPA value of Abebe
sout<<Stud.FName; //display the name
sout<<Stud.CGPA; // display the CGPA of Abebe
Initializing Structure Data
 You can initialize members when you declare a structure, or you can initialize a
structure in the body of the program. Here is a complete program.
.
..
struct cd_collection
{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purchased[9];
} cd1 = {"Red Moon Men","Sams and the Sneeds", 12, 11.95,"08/13/93"};
cout<<"\nhere is the info about cd1"<<endl;
cout<<cd1.title<<endl;
cout<<cd1.artist<<endl;
cout<<cd1.num_songs<<endl;
cout<<cd1.price<<endl;
ut<<cd1.date_purchased<<endl;
co
.
..

Compiled By: Markos A. Page 18


Introduction to Computing

 A better approach to initialize structures is to use the dot operator(.). the dot
operator is one way to initialize individual members of a structure variable in the
body of your program. The syntax of the dot operator is :
structureVariableName.memberName

here is an example:
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
struct cd_collection{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purchased[9];
}cd1;
//initialize members here
strcpy(cd1.title,"Red Moon Men");
strcpy(cd1.artist,"Sams");
cd1.num_songs= 12;
cd1.price = 11.95f;
strcpy(cd1.date_purchased,"22/12/02");
//print the data
cout<<"\nHere is the info"<<endl;
cout<<"Title : "<<cd1.title<<endl;
cout<<"Artist : "<<cd1.artist<<endl;
cout<<"Songs : "<<cd1.num_songs<<endl;
cout<<"Price : "<<cd1.price<<endl;
cout<<"Date purchased : "<<cd1.date_purchased;
getch();
}
Arrays of Structures
Arrays of structures are good for storing a complete employee file, inventory file, or any
other set of data that fits in the structure format.
Consider the following structure declaration:
struct Company
{
int employees;
int registers;
double sales;
}store[1000];

Compiled By: Markos A. Page 19


Introduction to Computing

 In one quick declaration, this code creates 1,000 store structures with the definition
of the Company structure, each one containing three members.
 NB. Be sure that your computer does not run out of memory when you create a large
number of structures. Arrays of structures quickly consume valuable information.
 You can also define the array of structures after the declaration of the structure.
struct Company
{
int employees;
int registers;
double sales;
}; // no structure variables defined yet
#include<iostream.h>

void main()
{
struct Company store[1000]; //the variable store is array of the structure Company
…}

Referencing the array structure


The dot operator (.) works the same way for structure array element as it does for
regular variables. If the number of employees for the fifth store (store[4]) increased by
three, you could update the structure variable like this:
store[4].employees += 3;
Unlike in the case of arrays, where the whole content of an array could not be copied to
another one using a simple statement, in structures, you can assign complete structures
to one another by using array notation.
th th
 To assign all the members of the 20 store to the 45 store, you would do this:
th th
store[44] = store[19];//copies all members from 20 store to 45
Here is a complete C++ code that shows you how to use array of structures, and how to
pass and return structures to functions.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<iomanip.h>
struct inventory
{
long storage;
int accesstime;
char vendorcode;
float cost;
float price;
};
void disp_menu(void);

Compiled By: Markos A. Page 20


Introduction to Computing

struct inventory enter_data();


void see_data(inventory disk[125],int num_items);
void main()
{ clrscr();
inventory disk[125];
int ans;
int num_items = 0; //total number of items in the inventory
do{
do{
disp_menu();
cin>>ans;
}while(ans<1 || ans>3);
switch(ans)
{ case 1:
disk[num_items] = enter_data();
num_items++;
break;
case 2:
see_data(disk,num_items);
break;
default :
break;
}
}while(ans != 3);
return;
}//end main
Introduction to Programming in C ++ Compiled by: Mahder Alemayehu and Wondwossen Mulugeta
Addis Ababa University, Faculty of Informatics 21

Compiled By: Markos A. Page 21


Introduction to Computing

void disp_menu()
{
cout<<"\n\n*** Disk Drive Inventory System ***\n\n";
cout<<"Do you want to : \n\n";
cout<<"\t1. Enter new item in inventory\n\n";
cout<<"\t2. See inventory data\n\n";
cout<<"\t3. Exit the program\n\n";
cout<<"What is your choice ? ";
return;
}
inventory enter_data()
{
inventory disk_item;//local variable to fill with input
cout<<"\n\nWhat is the next drive's storage in bytes? ";
cin>>disk_item.storage;
cout<<"\nWhat is the drive's access time in ms ? ";
cin>>disk_item.accesstime;
cout<<"What is the drive's vendor code (A, B, C, or D)? ";
disk_item.vendorcode = getchar();
cout<<"\nWhat is the drive's cost? ";
cin>>disk_item.cost;
cout<<"\nWhat is the drive's price? ";
cin>>disk_item.price;
return (disk_item);
}
void see_data(inventory disk[125], int num_items)
{
int ctr;
cout<<"\n\nHere is the inventory listing:\n\n";
for(ctr=0;ctr<num_items;ctr++)
{
cout<<"Storage: "<<disk[ctr].storage<<"\n";
cout<<"Access time: "<<disk[ctr].accesstime<<endl;
cout<<"Vendor code: "<<disk[ctr].vendorcode<<"\n";
cout<<"Cost : $ "<<disk[ctr].cost<<"\n";
cout<<"Price: $ "<<disk[ctr].price<<endl;
}
return;
}

Compiled By: Markos A. Page 22


Introduction to Computing

ADDIS ABABA UNIVERSITY


FACULTY OF INFORMATICS
Worksheet No 5:

1. Define strlen function (i.e write the function body of strlen)


2. Define the strcmp function and the strncmp function
3. Define strcpy function and the strncpy function
4. Define strcat function and the strncat function
5. Write a program to store the ages of six of your friends in a single array. Store each of the six
ages using the assignment operator. print the ages on the screen
6. Write a C++ program that accepts 10 integers from the user and finally displays the smallest
value and the largest value.
7. Write a program that accepts ten different integers from the user and display these numbers
after sorting them in increasing order.
8. Write a program to store six of your friend’s ages in a single array. Assign the ages in a random
order. print the ages, from low to high, on-screen
9. Modify the program on Q8 to print the ages in descending order.
10. Write a C++ program that calculates the letter grades of 20 students. The program should
accept the mid result and the final result from the students. Use the appropriate validity
control mechanism to prevent wrong inputs.
11. Write a C++ program that has two functions toBinary and toDecimal. The program should
display a menu prompting the user to enter his choice. If the user selects toBinary, then the
function should accept a number in base ten and displays the equivalent binary representation.
The reverse should be done if the user selects toDecimal.
12. Develop a C++ program that accepts a word from the user and then checks whether the word is
palindrome or not. (NB a word is palindrome if it is readable from left to right as well as right
to left).
13. Write a C++ program that accepts a word from the user and then displays the word after
reversing it.
14. Develop a C++ program that accepts the name of a person and then counts how many vowels
the person’s name have.
15. Modify the question in Q14 in such a way that it should replace vowel characters with * in the
person name.
16. Write a program in C++ which read a three digit number and generate all the possible
permutation of numbers using the above digits. For example n = 123 then the permutations are

123, 213, 312, 132, 231, 321
17. Write a program which read a set of lines until you enter #.
18. Write a program which read two matrixes and then print a matrix which is addition of these
two matrixes.
19. Write a program which reads two matrix and multiply them if possible

Compiled By: Markos A. Page 23


Introduction to Computing

20. Write a program which reads a 3 x 2 matrix and then calculates the sum of each row and store
that in a one dimension array.

Compiled By: Markos A. Page 24

You might also like