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

[PRF193]-4. Data Handling

This document covers data handling in programming, specifically focusing on arrays, strings, structures, and enumerations in C/C++. It outlines the importance of data handling, how to declare and manipulate arrays, and provides examples of common operations such as inputting, outputting, searching, and modifying array elements. Additionally, it highlights common errors and best practices for working with arrays.

Uploaded by

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

[PRF193]-4. Data Handling

This document covers data handling in programming, specifically focusing on arrays, strings, structures, and enumerations in C/C++. It outlines the importance of data handling, how to declare and manipulate arrays, and provides examples of common operations such as inputting, outputting, searching, and modifying array elements. Additionally, it highlights common errors and best practices for working with arrays.

Uploaded by

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

DATA HANDLING

ARRAYS - STRINGS, STRUCTURES,


ENUMERATIONS
OBJECTIVES
• By the end of this lesson, you will be able to:

PRF193
• Understand the importance of data handling and its role in
programming.
• Identify and differentiate between different data types in C/C++.
• Work with arrays, strings, structures, and enumerations
effectively.
• Manipulate and process data using these data types.

PRF193 - Data Handling 2


PROBLEM
• The program needs to store 3 integers?
int a1 = 4;

PRF193
• → Declare 3 variables: int a1, a2, a3;
int a2 = 7;
• The user wants to enter n integers? int a3 = 0;
• → Not feasible with individual variables!

• To store and process a large amount of data


• → Requires more complex data structures

• Solution: A new data type that allows storing a


sequence of integers and easy data access.

PRF193 - Data Handling 3


ARRAY DATA TYPE

PRF193
• An array is a sequence of values
of the same type (elements) that
are indexed.

• Examples:
• 52 playing cards
• 12,000 students at FPT
University
• 1,000,000,000 Facebook
accounts

PRF193 - Data Handling 4


DECLARING A STATIC ARRAY (FIXED NUMBER OF ELEMENTS)
Syntax:

PRF193
baseType arrayName[number of elements];
baseType arrayName[N1][N2]…[Nn];
• [N1][N2]…[Nn]: Number of elements in each dimension.
• Note:
• A specific number of elements (constant) must be
defined when declaring an array.
• For a multi-dimensional array:
• Total number of elements = N1 * N2 * … * Nn
• Memory used = total number of elements *
sizeof(<base type>)
• Memory usage must be less than 64KB (65,535
Bytes).
• An array is a continuous sequence indexed from 0 to total
number of elements – 1.
PRF193 - Data Handling 5
EXPLICIT ARRAY VARIABLE DECLARATION
• For examples:

PRF193
int OneDimensional[10];
OneDimensional 0 1 2 3 4 5 6 7 8 9

int Two_Dimensional[3][4];
Two_Dimensional 0 1 2 3 4 5 6 7 8 9 10 11

PRF193 - Data Handling 6


NUMBER OF ELEMENTS IN AN ARRAY
The number of elements must be explicitly
specified at the time of declaration. You cannot

PRF193
use variables or regular constants for this
purpose.
int n1 = 10; int a[n1];
const int n2 = 20; int b[n2];

It is recommended to use the preprocessor


directive #define to define the number of
#define n1 10
elements
#defineinn2
an 20
array.
int a[n1]; //  int a[10];
int b[n1][n2]; //  int b[10][20];

PRF193 - Data Handling 7


INITIALIZING ARRAY VALUES AT DECLARATION
There are the following ways to do this:

PRF193
• Initialize Values for All Elements in the Array

int a[5] = {2912, 1706, 1506, 1904, 2043}

0 1 2 3 4

a 2912 1706 1506 1904 2043

• Initialize Values for Only the First Few Elements in the Array

int a[5] = {2912, 1706};


0 1 2 3 4

a 2912 1706 0 0 0

PRF193 - Data Handling 8


INITIALIZING ARRAY VALUES AT DECLARATION
There are the following ways to initialize:

PRF193
• Initialize All Elements to 0
int a[4] = {0};
0 1 2 3

a 0 0 0 0

• Automatically Determine the Number of Elements


int a[] = {2912, 1706, 1506, 1904};
0 1 2 3

a 2912 1706 1506 1904

PRF193 - Data Handling 9


ACCESSING AN ARRAY ELEMENT
• Syntax:

PRF193
array_name[index_1][index_2]...[index_n]
• Example:
• For an array declared as follows:
0 1 2 3
int
a[4];

• Valid Access: a[0], a[1], a[2], a[3] are valid


indices and can be used to access the corresponding
elements.
• Invalid Access: a[-1], a[4], a[5], etc.,
are invalid.

PRF193 - Data Handling 10


ASSIGNING DATA TO ARRAYS
• Direct assignment cannot be used for arrays as a whole; you
must assign values element-by-element.

PRF193
TargetArray = SourceArray;//Incorrect
TargetArray[index i] = value; //Correct

• Example:
#define MAX 3
int M[MAX], N[MAX];
M = {1, 2, 3}; // Incorrect
N = M; // Incorrect
for (int i = 0; i < 3; i++)
N[i] = M[i];

PRF193 - Data Handling 11


COMMON ERRORS
Declaration Without Specifying the Number of
Elements:

PRF193
int a[]; // Incorrect
int a[100]; // Correct
Number of Elements Depends on a Variable or
Non-Constant:
int n1 = 10; int a[n1]; // Incorrect
int a[10]; // Correct
int a[n2]; // Correct
Initialization Separate from Declaration:
int a[4]; a = {2912, 1706, 1506, 1904}; //
Incorrect
int a[4] = {2912, 1706, 1506, 1904}; // Correct
Invalid Array Indices:
int a[4];
a[-1] = 1; // Incorrect
a[10] = 0; // Incorrec
PRF193 - Data Handling 12
BASIC PROBLEMS
1. Write functions to perform the following tasks:
2. Input Array: A function to input elements into the array.

PRF193
3. Output Array: A function to display elements of the array.
4. Search for an Element in the Array: A function to find a specific
element in the array.
5. Check Array Properties: A function to verify certain properties of the
array (e.g., sorted, unique values).
6. Split / Merge Arrays: Functions to split an array into sub-arrays or to
merge multiple arrays.
7. Find Minimum / Maximum Value of the Array: A function to
determine the smallest or largest value.
8. Sort the Array in Ascending/Descending Order: A function to sort
the array.
9. Add/Delete/Modify an Element in the Array: Functions to
manipulate elements in the array.
PRF193 - Data Handling 13
INPUT ARRAY
• Requirement:

PRF193
• Allow the user to input array a with n elements.
• Idea:
1.Define an array with a fixed number of
elements, MAX.
2.Input the actual number of
elements n that will be used in the array.
3.Input each element of the array
from index 0 to n - 1.
0 1 2 3 n-1 MAX -
1
… … …

PRF193 - Data Handling 14


INPUT ARRAY
• Requirement:

PRF193
• Allow the user to input array a with n elements.
• Idea:
#define MAX 10
int a[MAX];
for (int i = 0; i < n; i++)
cin >> a[i];

0 1 2 3 n-1 MAX -
1
… … …

PRF193 - Data Handling 15


OUTPUT ARRAY
• Requirement:

PRF193
• Given an array a with n elements, display the
content of array a on the screen.
• Idea:
• Output the value of each element in the array
from index 0 to n - 1.
0 1 2 n-1 MAX -
1
… … …

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


+)
cout << a[i];
PRF193 - Data Handling 16
SEARCH FOR AN ELEMENT IN AN ARRAY
• Requirement:

PRF193
• Check if element x is present in array a of size n. If
found, return the first occurrence of its position.
• Idea:
• Examine each element of array a. If the current
element is equal to x, return that position.
• If x is not found, return -1.

x position=
1
0 1 2 n-1 MAX -
1
a x b … x … …

PRF193 - Data Handling 17


CHECK ARRAY PROPERTIES
• Requirement:
• Given an array a with n elements, determine whether all

PRF193
elements in the array are prime numbers.
• Ideas:
1.Method 1:
1.Count the number of prime numbers in the array. If this
count is equal to n, then the array consists entirely of prime
numbers.
2.Method 2:
1.Count the number of non-prime numbers in the array. If
this count is 0, then the array consists entirely of prime
numbers.
3.Method 3:
1.Check if there is any element in the array that is not a
prime number. If such an element exists, then the
array does not consist entirely of prime numbers.
PRF193 - Data Handling 18
EXTRACT ELEMENTS THAT MEET CONDITIONS
• Requirement:

PRF193
• Given an array a with na elements, extract
the prime numbers from array a into array b.
• Idea:
1.Initialize j = 0 to keep track of the position in
array b.
2.Traverse each element of array a.
3.If the element is a prime number, add it
to array b at position b[j], then increment j.

PRF193 - Data Handling 19


SPLIT AN ARRAY INTO SUB-ARRAYS
• Requirement:

PRF193
• Given an array a with na elements,
split array a into two arrays: b (containing even
numbers) and c (containing the remaining
numbers).
• Idea:
1.Initialize j = 0 to keep track of the position in
array b.
2.Traverse each element of array a using a loop.
3. for (int i = 0; i < na; i++) If it is even (a[i] % 2 == 0), add
it to array b at position b[j] and increment j.

PRF193 - Data Handling 20


MERGE TWO ARRAYS INTO ONE ARRAY
• Merge Two Arrays into One Array

PRF193
• Requirement:
• Given array a with na elements and array b wit
h nb elements, merge both arrays in that order
into array c, with nc elements.
• Idea:
1.Copy elements from array a to array c.
1.After copying, nc = na.
2.Continue adding
elements from array b to array c.
1.After adding, nc = nc + nb.

PRF193 - Data Handling 21


FIND THE MAXIMUM VALUE OF AN ARRAY
• Requirement:
• Given an array a with n elements, find

PRF193
the maximum value in the array (max).
• Idea:
1.Assume the initial max value is the value of
the first element: a[0].
2.Iterate through the remaining elements
and update max if a larger value is found.

ma 8
7
?
x
0 1 2 n–1 MAX -
1
7 2 8 … 8 … …

PRF193 - Data Handling 22


SORT ARRAY IN ASCENDING ORDER
• Requirement:
• Given an array a of size n, sort the array such that

PRF193
its elements are in ascending order.
• Idea:
• Use two variables, i and j, to compare all pairs of
elements in the array.
• Swap elements if they are in the wrong order (i.e.,
the left element is larger than the right one).

temp 5
8

0 1 2 n–1 MAX -
1
5
1 1
5 8
6 … 6
8 … …

i j j j j
PRF193 - Data Handling 23
ADD AN ELEMENT TO AN ARRAY
• Requirement:
• Insert an element x into array a of

PRF193
size n at position vt.
• Idea:
1."Shift" the elements starting from position vt one
position to the right.
2.Insert x at position vt in the array.
3.Increase n by 1 to account for the new element.
x Insert
?
0 1 2 3 n–1 n MAX -
1
a b c … z … …

vt

PRF193 - Data Handling 24


REMOVE AN ELEMENT FROM AN ARRAY
• Requirement:

PRF193
• Remove an element from array a of
size n at position vt.
• Idea:
1."Shift" the elements to the left, starting from the
position right after vt to overwrite the element
at vt.
Remov
2.Decrease
e? n by 1 to account for the removed
element.
0 1 2 n-1 n–1 MAX -
1
a x b … z … …

vt
PRF193 - Data Handling 25
INPUT A STRING
• Use the scanf function with the format
specifier "%s".

PRF193
• It only accepts characters from the keyboard until
a whitespace or newline character is encountered.
• The resulting string does not include the
whitespace or newline character.
char input[50];
printf("Enter a string: ");
scanf("%s", input);

printf("The received string is: %s\n",


input);

PRF193 - Data Handling 26


INPUT A STRING
Use gets Function

PRF193
• The gets() function reads characters from the
keyboard until a newline character (\n) is
encountered.
• The resulting string includes all characters that the
user entered, except for the newline character.
• However, note that gets() has
been deprecated and is generally unsafe because
it doesn't protect against buffer overflow, which can
cause
char security vulnerabilities.
input[50];
printf("Enter a string: ");
gets(input);

_
printf("The received string is: %s\n",
input);
PRF193 - Data Handling 27
COMMON STRING MANIPULATION FUNCTIONS
IN C/C++
• C String Functions (<string.h>):
1.strcpy(dest, src) : Copy src string to dest.

PRF193
2.strncpy(dest, src, n) : Copy n characters from src to dest.
3.strcat(dest, src) : Concatenate src to the end of dest.
4.strlen(str): Get the length of str.
5.strcmp(s1, s2): Compare s1 and s2.
6.strstr(haystack, needle) : Find needle in haystack.
• C++ String Functions (<string>):
1.append(str): Append str to the end.
2.length(): Get the length of the string.
3.substr(pos, len): Get substring starting
at pos with len characters.
4.find(sub):Find sub in the string.
5.compare(str): Compare two strings.
PRF193 - Data Handling 28
STRINGS

PRF193
• A string is a sequence of characters treated as a group.
• We have already used some string literals:
• "filename"
• "output string"
• Strings are important in many programming contexts:
• names
• other objects (numbers, identifiers, etc.)

PRF193 - Data Handling 29


STRINGS IN C

Strings

PRF193
Representation in C
String Literals
String Variables
String Input/Output
printf, scanf, gets, fgets, puts, fputs
String Functions
strlen, strcpy, strncpy, strcmp, strncmp,
strcat, strncat, strchr, strrchr, strstr, strspn,
strcspn, strtok
Reading from/Printing to Strings
sprintf, sscanf

PRF193 - Data Handling 30


STRINGS IN C
• No explicit type, instead strings are maintained as arrays of
characters

PRF193
• Representing strings in C/C++
• stored in arrays of characters
• array can be of any length
• end of string is indicated by a delimiter, the zero character ‘\0’

"A String" A S t r i n g \0

PRF193 - Data Handling 31


STRING LITERALS

• String literal values are represented by sequences of

PRF193
characters between double quotes (‘’)
• Examples
• “” - empty string
• “hello”
• “a” versus ‘a’
• ‘a’ is a single character value (stored in 1 byte) as the ASCII
value for a
• “a” is an array with two characters, the first is a, the second is
the character value \0

PRF193 - Data Handling 32


REFERRING TO STRING LITERALS

PRF193
• String literal is an array, can refer to a single character from the literal as
a character
• Example:
printf(“%c”,”hello”[1]);
→Outputs the character ‘e’
• During compilation, C/C++ creates space for each string literal (the
number of characters in the literal + 1 for the null terminator \0).
• Referring to the literal refers to that space (as if it is an array).

PRF193 - Data Handling 33


DUPLICATE STRING LITERALS

PRF193
• Each string literal in a C\C++ program is stored at a
different location in memory
• So even if the string literals contain the same string, they
are not equal (in the == sense)
• Example:
char string1[6] = “hello”;
char string2[6] = “hello”;
• but string1 does not equal string2 (they are stored at different
locations)

PRF193 - Data Handling 34


STRING VARIABLES

• Allocate an array of a size large enough to hold the string

PRF193
(plus 1 extra value for the null terminator \0)
• Examples (with initialization):
char str1[6] = “Hello”;
char str2[] = “Hello”;
char *str3 = “Hello”;
char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’\0’};
• Note, each variable is considered a constant in that the
space it is connected to cannot be changed
str1 = str2; /* not allowable, but we can copy
the contents of str2 to str1 (more later) */

PRF193 - Data Handling 35


STRING IN C++
• To use the data type string in C++, the program must include
the header file string

PRF193
• The statement:
• string name = "William Jacob";
• declares name to be a string variable and also initializes
name to "William Jacob"
• The first character, 'W', is in position 0
• The second character, 'i', is in position 1
• name is capable of storing any size string

PRF193 - Data Handling 36


STRING IN C++
• Binary operator + and the array subscript operator [], have
been defined for the data type string

PRF193
• + performs the string concatenation operation
• Example:
• str1 = "Sunny";
• str2 = str1 + " Day";
• stores "Sunny Day" into str2

PRF193 - Data Handling 37


ADDITIONAL STRING OPERATIONS IN C++
• Length

PRF193
• Returns the number of characters in the string.
• Size
• Synonym for length(); gives the number of characters.
• Find
• Finds the first occurrence of a substring or character.
• Substring (substr)
• Extracts a substring from the string.
• Swap
• Exchanges content with another string.

PRF193 - Data Handling 38


LENGTH FUNCTION
• Returns the number of characters currently in the string

PRF193
• Syntax: strVar.length();

where strVar is variable of the type string


length returns an unsigned integer
• The value returned can be stored in an integer variable

PRF193 - Data Handling 39


LENGTH FUNCTION

PRF193
PRF193 - Data Handling 40
SIZE FUNCTION
• size is the same as the function length

PRF193
• Both functions return the same value
• Syntax: strVar.size();

• where strVar is variable of the type string
• As in the case of the function length, the function size has no
arguments

PRF193 - Data Handling 41


FIND FUNCTION
• Searches a string for the first occurrence of a particular
substring

PRF193
• Returns an unsigned integer value of type string::size_type
• Or string::npos if unsuccessful
• Syntax:
• strVar.find(strExp); strVar.find(strExp, pos);

• strExp can be a string or a character

PRF193 - Data Handling 42


FIND FUNCTION (CONTINUED)

PRF193
PRF193 - Data Handling 43
SUBSTR FUNCTION
• Returns a particular substring of a string

PRF193
• Syntax: strVar.substr(expr1, expr2);

• expr1 and expr2 are expressions evaluating to unsigned integers


• expr1 specifies a position within the string (starting position of
the substring)
• expr2 specifies the length of the substring to be returned

PRF193 - Data Handling 44


SUBSTR FUNCTION (CONTINUED)

PRF193
PRF193 - Data Handling 45
SWAP FUNCTION
• Interchanges contents of two string variables

PRF193
• Syntax: strVar1.swap(strVar2);

• where strVar1 and strVar2 are string variables
• Suppose you have the following statements:
• string str1 = “Dream”;
• string str2 = “Future”;
• After str1.swap(str2); executes, the value of str1 is
“Dream” and the value of str2 is “Future”

PRF193 - Data Handling 46


PROGRAMMING EXAMPLE: PIG LATIN STRINGS
• Program prompts user to input a string

PRF193
• Then outputs the string in the pig Latin form
• The rules for converting a string into pig Latin form are as
follows:
• If the string begins with a vowel, add the string "-way" at the end
of the string
• Example: the pig Latin form of "eye" is "eye-way"

PRF193 - Data Handling 47


PROGRAMMING EXAMPLE: PIG LATIN STRINGS (CONTINUED)

• Rules (continued):

PRF193
• If the string does not begin with a vowel, first add "-" at the end
of the string
• Then move the first character of the string to the end of the string
until the first character of the string becomes a vowel
• Next, add the string "ay" at the end
• Example: pig Latin form of "There" is "ere-Thay"

PRF193 - Data Handling 48


PROGRAMMING EXAMPLE: PIG LATIN STRINGS (CONTINUED)

• Rules (continued):

PRF193
• Strings such as "by" contain no vowels
• The letter 'y' can be considered a vowel
• For this program the vowels are a, e, i, o, u, y, A, E, I, O, U, and Y
• Strings such as "1234" contain no vowels
• The pig Latin form of a string that has no vowels in it is the string
followed by the string "-way"
• Example: pig Latin form of "1234" is "1234-way"

PRF193 - Data Handling 49


PROGRAMMING EXAMPLE: PROBLEM ANALYSIS
• If str denotes a string:

PRF193
• Check the first character, str[0], of str
• If it is a vowel, add "-way" at the end of str
• If it is not a vowel:
• First add "-" at the end of the string
• Remove the first character of str from str and put it at end of str
• Now the second character of str becomes the first character of str

PRF193 - Data Handling 50


PROGRAMMING EXAMPLE: PROBLEM ANALYSIS (CONTINUED)

• If str denotes a string (continued):

PRF193
• This process is repeated until either
• The first character of str is a vowel
• All characters of str are processed, in which case str
does not contain any vowels

PRF193 - Data Handling 51


PROGRAMMING EXAMPLE: ALGORITHM DESIGN
• The program contains the following functions:

PRF193
• isVowel determines if a character is a vowel
• rotate moves first character of str to the end of str
• pigLatinString finds pig Latin form of str
• Steps in the algorithm:
• Get str
• Use pigLatinString to find the pig Latin form of str
• Output the pig Latin form of str

PRF193 - Data Handling 52


PROGRAMMING EXAMPLE: ISVOWEL

PRF193
PRF193 - Data Handling 53
PROGRAMMING EXAMPLE: FUNCTION ROTATE
• Takes a string as a parameter

PRF193
• Removes the first character of the string
• Places it at end of the string by extracting the substring starting
at position 1 until the end of the string, then adding the first
character of the string

PRF193 - Data Handling 54


PROGRAMMING EXAMPLE: FUNCTION PIGLATINSTRING
• If pStr[0] is a vowel, add "-way" at end

PRF193
• If pStr[0] is not a vowel:
• Move first character of pStr to the end of pStr
• The second character of pStr becomes the first character of pStr
• Now pStr may or may not contain a vowel
• Use a bool variable, foundVowel, which is set to true if pStr
contains a vowel and false otherwise
• Initialize foundVowel to false

PRF193 - Data Handling 55


PROGRAMMING EXAMPLE: FUNCTION PIGLATINSTRING
(CONTINUED)
• If pStr[0] is not a vowel, move str[0] to the end of pStr by calling
the function rotate

PRF193
• Repeat third step until either the first character of pStr becomes a
vowel or all characters of pStr have been checked
• Convert pStr into the pig Latin form
• Return pStr

PRF193 - Data Handling 56


PROGRAMMING EXAMPLE: MAIN ALGORITHM
• Get the string

PRF193
• Call pigLatinString to find the pig Latin form of the string
• Output the pig Latin form of the string

PRF193 - Data Handling 57


C++ KEY CONCEPTS
1. The namespace keyword must appear in the using statement.
1. Example: using namespace std;

PRF193
2. A string is a sequence of zero or more characters. Strings in C++ are
enclosed in double quotes ("").
1. Example: string str = "Hello";
In C++, [] is used as the array subscript operator to access elements in arrays
and strings.
Example: char name[] = "Alice"; cout << name[0]; // Output: A
The length() function returns the number of characters currently in the
string.
2. Example: string str = "Hello"; cout << str.length();
3. // Output: 5
• The size() function returns the number of characters currently in the
string.
• Example: string str = "Hello"; cout <<
str.size(); // Output: 5
PRF193 - Data Handling 58
C++ KEY CONCEPTS
• The find() function searches a string to locate the first occurrence of
a particular substring. Returns the position of the first occurrence,

PRF193
or string::npos if not found.
• Example:
• string str = "Hello, World!";
• cout << str.find("World"); // Output: 7
• The substr() function returns a substring starting from a specified
position and optionally with a specified length.
• Example: string str = "Hello, World!";
• cout << str.substr(7, 5); // Output: World
• The swap() function swaps the contents of two string variables.
• Example: string str1 = "Hello";
• string str2 = "World"; str1.swap(str2);
• cout << str1 << " " << str2;
• // Output: World Hello
PRF193 - Data Handling 59
PRACTICE EXERCISES
• 1. Input and Output Operations

PRF193
• Input Array
• Output Array
• Check Operations
• Is the array composed entirely of even numbers?
• Is the array composed entirely of prime numbers?
• Is the array sorted in ascending order?

PRF193 - Data Handling 60


PRACTICE EXERCISES
• 2. Calculation Operations

PRF193
• How many numbers are divisible by 4 but not
divisible by 5?
• Sum of all prime numbers in the array.
• Search Operations
• Last occurrence of element x in the array.
• Position of the first prime number in the array,
if any.
• Find the smallest number in the array.
• Find the smallest positive number in the array.

PRF193 - Data Handling 61


PRACTICE EXERCISES
• 3. Processing Operations

PRF193
• Extract prime numbers from array a and place them
in array b.
• Split array a into two arrays: b (containing positive
integers) and c (containing the remaining numbers).
• Sort the array in descending order.
• Sort the array so that positive numbers appear first
in descending order, followed by negative numbers
in ascending order, and zeros at the end.
• Insert/Delete/Edit operations.
1.Replace all prime numbers in the array with 0.
2.Insert 0 immediately after each prime number in the
array.
3.Remove all prime numbers from the array.
PRF193 - Data Handling 62
PRACTICE EXERCISES
• 4. Write a program to perform the following tasks:

PRF193
1.Input an array of n elements from the user.
2.Print the entered array.
3.Check if there are any odd numbers in the
array. If there are, print those odd numbers.
4.Sort the array in descending order.
5.Print the sorted array.

PRF193 - Data Handling 63


PRACTICE EXERCISES
• 5. Write a program to perform the following tasks:

PRF193
1.Input an array of n elements from the user.
2.Print the entered array.
3.Check if there are any even numbers in the array. If
there are, print those even numbers.
4.Sort the even numbers in ascending order.
5.Print the sorted even numbers.

PRF193 - Data Handling 64


PRACTICE EXERCISES
• 6. Write a program to perform the following tasks:

PRF193
1.Input an array of n elements from the user.
2.Print the entered array.
3.Check if there are any odd numbers in the array. If
there are, print those odd numbers.
4.Sort the odd numbers found in ascending order.
5.Print the sorted odd numbers.

PRF193 - Data Handling 65


PRACTICE EXERCISES
• 7. Learn more about the following functions:

PRF193
• atoi, atol, atof: Convert strings to numbers.
• itoa, ltoa, ultoa: Convert numbers to strings.
• strtok: Tokenizes a string into parts based on a
delimiter.
• 8. Write a function upper(char s[]) that converts all
characters in a string to uppercase (similar to
the strupr function).
• 9. Write a function lower(char s[]) that converts all
characters in a string to lowercase (similar to
the strlwr function).
• 10. Write a function proper(char s[]) that converts
the first character of each word in a string to
uppercase.
PRF193 - Data Handling 66
PRACTICE EXERCISES
• 11. Write a function standard(char s[]) that removes
all leading and trailing spaces from the string s, and

PRF193
reduces multiple spaces between words to a single
space.
• 12. Write a function that removes all spaces from
the string s.
• 13. Count how many words are in the string s. Print
each word on separate lines.
• 14. Find the longest word in the string s and print it.
• 15. Extract n characters:
• The first n characters,
• The last n characters,
• Or starting from position pos.
PRF193 - Data Handling 67
DERIVED TYPES
• C allows a number of derived types:

PRF193
• Array - group of similar elements (same type)
• Pointer - location of a variable
• Enumerated - set of named values
• Structure - group of related elements (different types)
• Union - single type allowing different types of values
• Provides a mechanism (type definition) to give names
to these types

PRF193 - Data Handling 68


OUTLINE
• Type Definition
• Enumerated Type

PRF193
• definition, representation
• Structured Type
• definition, initialization, assignment, comparison
• passing as parameter (value, ref), return value
• pointer selection operator
• arrays within structures
• structures within structures (nested structures)
• arrays of structures (tables)
• reading group, writing group, insert, remove, sort, print
• Union Type
• definition, use within structures

PRF193 - Data Handling 69


TYPE DEFINITION
• Syntax: typedef type Name ;
• Name becomes a name you can use for the type

PRF193
• Examples:
• typedef int INTEGER;
• INTEGER x; /* x is an integer */

• typedef char *STRING;


• STRING sarray[10];
• /* sarray is an array of char *’s, equivalent to
declaring:
• char *sarray[10]; */

PRF193 - Data Handling 70


ENUMERATED TYPES
New types where the set of possible values is enumerated
(listed)

PRF193
• Used to make code more readable
• Declaring an enumerated variable:
• enum { Constant_List } VarName;
• List of constants is a set of identifiers separated by commas
• Example:
• enum { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
Day;

PRF193 - Data Handling 71


ENUMERATED TYPE USE
• enum { Sun, Mon, Tue, Wed, Thu, Fri, Sat } day;

PRF193
• day = Tue;

• for (day = Sun; day <= Sat; day++)


• if ((day == Sun) || (day == Sat))
• printf(“Weekend\n”);
• else
• printf(“Weekday\n”);

• printf(“%d\n”,Wed); /* Would print 3 */


• printf(“%s\n”,Tue); /* Would print garbage */

PRF193 - Data Handling 72


ENUMERATED TYPE DETAILS
• The names in an enumerated type are replaced by
integer values by the compiler

PRF193
• enum { Sun, Mon, Tue, Wed, Thu, Fri, Sat } Day;
• Sun is 0, Mon is 1, Tue is 2, etc.
• You can cause compiler to use different values:
• give different initial value (C numbers from there):
• enum { Sun = 1, Mon, Tue, Wed, Thu, Fri, Sat }
Day;
• Sun is 1, Mon is 2, Tue is 3, etc.
• give a value for each
• enum { First = 1, Second = 2, Third = 4,} X;
• important to use different values (C does not check)

PRF193 - Data Handling 73


BUILDING ENUMERATED TYPES
• Declaring type: (outside of function)

PRF193
• Tag: enum Tag { ConstList };
• Defined type: typedef enum { ConstList }
TypeName;
Examples:
• enum DayType1 { Sun, Mon, Tue, Wed, Thu, Fri,
Sat };
• typedef enum { Sun, Mon, Tue, Wed, Thu, Fri, Sat
} DayType2;
• Variable declarations:
Tag: enum Tag VarName;
Defined type: TypeName VarName;
Examples:
• enum DayType1 DayVar1;
• DayType2 DayVar2;
PRF193 - Data Handling 74
STRUCTURES
• A Structure is a collection of related data items, possibly of

PRF193
different types.
• A structure type in C++ is called struct.
• A struct is heterogeneous in that it can be composed of data of
different types.
• In contrast, array is homogeneous since it can contain only data
of the same type.

PRF193 - Data Handling 75


STRUCTURES
• Structures hold data that belong together.
• Examples:

PRF193
• Student record: student id, name, major, gender,
start year, …
• Bank account: account number, name, currency,
balance, …
• Address book: name, address, telephone number, …
• In database applications, structures are called records.

PRF193 - Data Handling 76


STRUCTURES
• Individual components of a struct type are called members (or

PRF193
fields).
• Members can be of different types (simple, array or struct).
• A struct is named as a whole while individual members are
named using field identifiers.
• Complex data structures can be formed by defining arrays of
structs.

PRF193 - Data Handling 77


STRUCT BASICS
• Definition of a structure:

PRF193
struct <struct-type>{
<type> <identifier_list>; Each identifier
<type> <identifier_list>; defines a member
... of the structure.
} ;

• Example:
struct Date { The “Date” structure
int day; has 3 members,
int month;
day, month & year.
int year;
} ;

PRF193 - Data Handling 78


STRUCT EXAMPLES
• Example:

PRF193
struct StudentInfo{
The “StudentInfo”
int Id;
int age;
structure has 4 members
char Gender; of different types.
double CGA;
};

• Example:
struct StudentGrade{ The “StudentGrade”
char Name[15]; structure has 5
char Course[9];
int Lab[5];
members of
int Homework[3]; different array types.
int Exam[2];
};
PRF193 - Data Handling 79
STRUCT EXAMPLES
• Example:

PRF193
struct BankAccount{ The “BankAcount”
char Name[15]; structure has simple,
int AcountNo[10]; array and structure
double balance; types as members.
Date Birthday;
};

• Example:
struct StudentRecord{ The “StudentRecord”
char Name[15]; structure has 4
int Id;
members.
char Dept[5];
char Gender;
};
PRF193 - Data Handling 80
STRUCT BASICS
• Declaration of a variable of struct type:
• <struct-type> <identifier_list>;

PRF193
• Example:
• StudentRecord Student1, Student2;

Name Name
Student1 Student2
Id Gender Id Gender
Dept Dept
Student1 and Student2 are variables of StudentRecord
type.

PRF193 - Data Handling 81


DEMO. 1: STRUCT BASICS
• The members of a struct type variable are accessed with
the dot (.) operator:

PRF193
Student1
• <struct-variable>.<member_name>;

• Example: Name
• strcpy(Student1.Name, "Tran An Nhien");
Id Gender
Student1.Id = 12345;
strcpy(Student1.Dept, "COMP"); Dept
Student1.gender = ‘F';
cout << "The student is ";
switch (Student1.gender){
Tran An Nhien
case 'F': cout << "Ms. "; break;
case 'M': cout << "Mr. "; break;
} 12345 F
cout << Student1.Name << endl;
COMP

PRF193 - Data Handling 82


DEMO. 1: STRUCT BASICS

PRF193
PRF193 - Data Handling 83
DEMO. 2: STRUCT-TO-STRUCT ASSIGNMENT
• The values contained in one struct type variable can be
assigned to another variable of the same struct type.

PRF193
Student1
• Example:
• strcpy(Student1.Name, Tran An Nhien
"Tran An Nhien"); 12345 F
Student1.Id = 12345;
strcpy(Student1.Dept, "COMP");
Student1.gender = ‘F'; COMP

Student2 = Student1;

Tran An Nhien
12345 F
Student2 COMP

PRF193 - Data Handling 84


DEMO. 2: STRUCT-TO-STRUCT ASSIGNMENT

PRF193
PRF193 - Data Handling 85
DEMO. 3-5: NESTED STRUCTURES
• We can nest structures inside structures.

PRF193
• Examples: (P.x, P.y)
struct point{ (L.p2.x, L.p2.y)
double x, y;
}; (L.p1.x, L.p1.y)
point P;
(T.p2.x, T.p2.y)
struct line{
point p1, p2;
};
line L; (T.p3.x, T.p3.y)

struct triangle{
point p1, p2,(T.p1.x,
p3; T.p1.y)
};
triangle T;
PRF193 - Data Handling 86
DEMO. 3-5: NESTED STRUCTURES
• We can nest structures inside structures.

PRF193
• struct line{
point p1, p2;
};
line L;
(L.p2.x, L.p2.y)

(L.p1.x, L.p1.y)
line
p1 p2
x y x y

PRF193 - Data Handling 87


DEMO. 3-5: NESTED STRUCTURES
• Assign values to the variables P, L, and T using the picture:

PRF193
point P;
line L; (4, 11)
triangle T;
(10, 9)

(2, 7)

(6, 5)

Ex. 3: Graph a point


(8, 3)
Ex. 4: Graph a line
Ex. 5: Graph a triangle
(2, 0)

PRF193 - Data Handling 88


DEMO. 3-5: NESTED STRUCTURES
• point P;
line L;

PRF193
triangle T; (4, 11)
• P.x = 4;
• P.y = 11; (10, 9)

• L.p1.x = 2; (2, 7)
• L.p1.y = 7;
• L.p2.x = 10; (6, 5)
• L.p2.y = 9;

• T.p1.x = 2;
• (8, 3)
T.p1.y = 0;
• T.p2.x = 6;
• T.p2.y = 5; (2, 0)
• T.p3.x = 8;
• T.p3.y = 3;

PRF193 - Data Handling 89


DEMO. 3: GRAPHING A POINT

PRF193
x

0 1 2 3 4 5 6 7 8 0 10 11 12 13 14 15
1 (x1, y1)
2 *
y
3
4
5

PRF193 - Data Handling 90


DEMO 3
struct point {int x, y;};

void user_input(point&);

PRF193
void graph_point(char grid[NUMBER_ROWS][NUMBER_COLS], point);
void print_grid(char grid[NUMBER_ROWS][NUMBER_COLS]);
void set_background(char grid[][NUMBER_COLS]);

void user_input(point& P){ // pass by reference


// get user input and check that it is on the grid
do{
cout << "Enter column (x<" << NUMBER_COLS << ") & row (y<"
<< NUMBER_ROWS <<") of the 1st point: ";
cin >> P.x >> P.y;
} while ((P.y<0) || (P.y >= NUMBER_ROWS) ||
(P.x<0) || (P.x >= NUMBER_COLS));
}
// Put a point on the grid
void graph_point(char grid[][NUMBER_COLS], point P){
grid[P.y][P.x] = '*';
}
PRF193 - Data Handling 91
DEMO 3

PRF193
PRF193 - Data Handling 92
DEMO. 4: TRAJECTORY BETWEEN 2 POINTS

PRF193
0 1 2 3 4 5 6 7 8 0 10 11 12 13 14 15
1 * (x1, y1)
2 *
y
3 *
4 *
5 * (x2, y2)
• The equation of a line going through two points
(x1, y1) & (x2, y2) can be represented by:
• (y-y1)/ (x-x1) = (y2-y1)/(x2-x1)
• or y = ((y2-y1)/(x2-x1)) (x-x1) + y1
where (y2-y1)/(x2-x1) is called the slope.

PRF193 - Data Handling 93


DEMO. 4
• // use struct to graph line between two points
• #include <ctype> // for tolower

PRF193
• #include <iostream>
• using namespace std;

• int const NUMBER_ROWS = 11;


• int const NUMBER_COLS = 31;

• struct point {int x, y;};


• struct line {point p1, p2;};

• void user_input (line&);


• void graph_line (char grid[NUMBER_ROWS]
[NUMBER_COLS], line);
• void print_grid(char grid[NUMBER_ROWS]
[NUMBER_COLS]);
• void set_background (char grid[][NUMBER_COLS]);

PRF193 - Data Handling 94


DEMO. 4
• // Graph line between two points
• int main(){

PRF193
• // set an array for the grid
• char grid[NUMBER_ROWS][NUMBER_COLS];
• line line1;
• int row1=0, col1=0, row2=0, col2=0;
• char do_another;

• // function call to fill background of grid with ‘-’


• set_background(grid);
• do{ // do-while loop allows multiple lines
• // get user input
• user_input(line1);
• // put ‘*’ into array to graph the line(s) on the grid
• graph_line(grid, line1);
• // print the grid from the array to the screen
• print_grid(grid);
• cout << "Do you want to add another line (y/n)? ";
• cin >> do_another;
• do_another = tolower(do_another);
• } while (do_another == 'y');
• return 0;
• }
PRF193 - Data Handling 95
DEMO. 4: MORE ON GRAPHING LINE
• //A function to get user input and check that it is
on the grid.

PRF193
• void user_input(line& line1){
• do{
• cout << "Enter column (x<" << NUMBER_COLS
• << ") & row (y<" << NUMBER_ROWS
• << ") coordinates of the 1st
point: ";
• cin >> line1.p1.x >> line1.p1.y;
• } while ((line1.p1.y<0) ||
• (line1.p1.y>=NUMBER_ROWS) ||
• (line1.p1.x<0) ||
• (line1.p1.x >= NUMBER_COLS));
• // use another do-while loop for the 2nd point,
col2 and row2
• }
PRF193 - Data Handling 96
DEMO. 4: MORE ON GRAPHING LINE
• void graph_line(char grid[][NUMBER_COLS], line line1){
• int row, col;

PRF193
• double rise, run, slope;
• // one point
• if((line1.p1.y==line1.p2.y)&&(line1.p1.x==line2.p2.x))
• grid[line1.p1.y][line1.p1.x] = '*';
• else if(line1.p2.x==line1.p1.x){ // infinite slope
• if (line1.p1.y < line1.p2.y){
• for(row=line1.p1.y; row <= line1.p2.y; row++)
• grid[row][line1.p1.x] = '*';
• }
• else{
• for(row=line1.p1.y; row >= line1.p2.y; row--)
• grid[row][line1.p1.x] = '*';
• }
• }

PRF193 - Data Handling 97


DEMO. 4: MORE ON GRAPHING LINE
• else{
• rise=line1.p2.y-line1.p1.y; run=line1.p2.x-line1.p1.x;

PRF193
• slope = (double)rise / run; // run cannot = 0
• if (run >0){
• for(col = line1.p1.x; col <= line1.p2.x; col++){
• // line1.p1.y is offset for starting point
• row=(int)(slope*(col–line1.p1.x)+line1.p1.y);
• grid[row][col] = '*';
• }
• }
• else{
• for(col=line1.p1.x; col >= line1.p2.x; col--){
• row=(int)(slope*(col–line1.p1.x)+line1.p1.y);
• grid[row][col] = '*';
• }
• }
• }
• }

PRF193 - Data Handling 98


DEMO. 4

PRF193
PRF193 - Data Handling 99
ARRAYS OF STRUCTURES
• An ordinary array: One type of data

PRF193
0 1 2 … 98 99

• An array of structs: Multiple types of data in each array


element.

0 1 2 … 98 99

PRF193 - Data Handling 100


ARRAYS OF STRUCTURES
• We often use arrays of structures.
• Example:

PRF193
StudentRecord Class[100];
strcpy(Class[98].Name, "Tran An Nhien");
Class[98].Id = 12345;
strcpy(Class[98].Dept, "COMP");
Class[98].gender = ‘F';
Class[0] = Class[98];
Tran An Nhien
12345 F
COMP

...

0 1 2 … 98 99

PRF193 - Data Handling 101


ARRAYS INSIDE STRUCTURES
• We can use arrays inside structures.
• Example:

PRF193
struct square{
point vertex[4]; (4, 3) (10, 3)
};
square Sq;
(4, 1) (10, 1)
• Assign values to Sq using the given square

x y x y x y x y

PRF193 - Data Handling 102


UNION TYPES
Tag Syntax: Defined Type Syntax:
• union Tag { • typedef union {

PRF193
• Type1 FName1; • Type1 FName1;
• Type2 FName2; • Type2 FName2;
• /* as needed */ • /* as needed */
• }; • } TName;
• union Tag Vname; • TName Vname;
Example: Example:
• union Utype1 { • typedef union {
• char A; • char A;
• int B; • int B;
• float C; • float C;
• }; • } Utype2;
• union Utype1 V; • Utype2 V;

PRF193 - Data Handling 103


UNIONS IN STRUCTURES
• Union types often used in structures where fields of

PRF193
structure depend item represented
• Example:
• F - Ms
• M - Mr
• Often use another value in structure to determine
which applies

PRF193 - Data Handling 104


UNIONS IN STRUCTURES
• // Define the union • int main(){
• Student1.name = "Tran An Nhien";
• union SUnionInfo {

PRF193
• char Name[22]; • Student1.whichgender = CEnum::F;
• int Id; • Student1.sinfo.Id = 12345;
• char Dept[22]; •
• // Print the student's information
• char gender;
• cout << "Name: ";
• }; • switch (Student1.whichgender) {
• case CEnum::F: cout << "Ms. ";
• // Define the enum break;
• case CEnum::M: cout << "Mr. ";
• enum class CEnum { F, •M }; break;
• }
• // Define the struct • cout << Student1.name << endl;
• struct StudentRecord {
• // Access the union member
• string name; • cout << "ID: " <<
• CEnum whichgender; Student1.sinfo.Id << endl;
• SUnionInfo sinfo; • return 0;
• }
• }Student1;
PRF193 - Data Handling 105
SUMMARY
• Arrays:

PRF193
• Definition: A collection of elements of the same data type, stored
sequentially in memory.
• Declaration: DataType ArrayName[Size];
• Benefits: Efficient storage and manipulation of large amounts of
data.
• Access: Elements are accessed by index, starting from 0.
• Pointers:
• Definition: A variable that stores the address of another variable.
• Declaration: DataType *PointerName;
• Operations: Use & to get an address, * to dereference and access
the value.

PRF193 - Data Handling 106


SUMMARY
• Enumerations (enum):

PRF193
• Definition: A set of named constants to improve code readability.
• Declaration: enum { EnumValues };
• Value Assignment: Defaults to starting from 0.
• Structures (struct):
• Definition: A user-defined data type that groups different types of
variables.
• Declaration: struct { ... };
• Access: Use the dot (.) operator to access members.
• Unions:
• Definition: Allows storing different data types in the same memory
location.
• Declaration: union { ... };
• Note: Only one member can hold a value at a time.
PRF193 - Data Handling 107

You might also like