The document discusses various topics related to arrays, strings, and string handling functions in C programming language. It explains that arrays are collections of variables of the same type that can be accessed using indexes. One-dimensional and multi-dimensional arrays are declared along with examples. Common string functions like strlen(), strcpy(), strcat() etc. are described with examples to manipulate strings in C. Pointers and their usage with arrays and strings are also covered briefly.
An array is a collection of similar data types stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, float, etc. Elements of an array are accessed using indexes and they are stored sequentially in memory. Strings in C are arrays of characters terminated by a null character. Common functions to manipulate strings include strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().
Introduction to Arrays and Strings.pptxDawitTekie1
An array is a data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Chapter 1 Introduction to Arrays and StringsDawitTekie1
An array is a data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. A string is a sequence of characters. In most programming languages, strings are treated as arrays of characters, but they often come with special functionality for manipulation.
Arrays allow storing multiple values of the same type under one common name. They come in one-dimensional and two-dimensional forms. One-dimensional arrays store elements indexed with a single subscript, while two-dimensional arrays represent matrices with rows and columns indexed by two subscripts. Arrays can be passed to functions by passing their name and size for numeric arrays, or just the name for character/string arrays since strings are null-terminated. Functions can operate on arrays to perform tasks like finding the highest/lowest element or reversing a string.
C programming language provides arrays as a data structure to store a fixed-size collection of elements of the same type. An array stores elements in contiguous memory locations. Individual elements in an array can be accessed using an index. Common array operations in C include declaration, initialization, accessing and modifying individual elements, and passing arrays to functions.
This document discusses strings in C programming. It defines strings as arrays of characters terminated with a null character. It describes four methods of initializing strings: assigning a string literal with or without size, assigning characters individually with size, and assigning characters individually without size. It also covers string functions like strlen(), strcpy(), strcat(), and strcmp() to get the length, copy, concatenate, and compare strings. Finally, it discusses string arrays as two-dimensional character arrays where each string is terminated with a null character. An example program is provided to print an array of strings.
Arrays allow storing multiple values of the same type sequentially in memory. An array is declared with the type, name, and size. Elements are accessed using indexes from 0 to size-1. Strings are represented as character arrays terminated with a null character. Arrays can be passed to and returned from functions, and multidimensional arrays store arrays within arrays. Standard libraries provide functions for string and character manipulation.
- Arrays allow storing multiple values of the same type sequentially in memory. They have a fixed size or dimension.
- To declare an integer array of size 4, we write "int arr[4]". Individual elements can be accessed using indexes from 0 to dimension-1.
- Strings in C++ are arrays of characters that end with a null character. Common string functions like strcpy(), strcat(), strlen() allow manipulating strings.
The document discusses different types of arrays in C including one-dimensional, two-dimensional, and multi-dimensional arrays. It explains how to declare, initialize, and access array elements. Examples are provided to demonstrate array operations like addition, multiplication, and passing arrays to functions. The use of arrays to store strings and various string handling functions are also covered.
Arrays are ordered sets of elements of the same type that allow direct access to each element through an index. In C++, arrays have a fixed size that is declared, with elements accessed using square brackets and integers representing their position. Multidimensional arrays arrange data in tables and can be thought of as arrays of arrays. Elements are accessed using multiple indices separated by commas within the brackets.
This document discusses arrays in C programming. It defines an array as a collection of variables of the same type that are referenced by a common name. It describes single-dimensional and multi-dimensional arrays. Single-dimensional arrays are comprised of finite, homogeneous elements while multi-dimensional arrays have elements that are themselves arrays. The document provides examples of declaring, initializing, accessing, and implementing arrays in memory for both single and double-dimensional arrays. It includes sample programs demonstrating various array operations.
This document provides information about strings in C++. It defines a string as a collection of characters within double quotes. Strings are stored as character arrays terminated by a null character. The document discusses declaring and initializing strings, inputting strings from the user, and functions for manipulating strings like strcat(), strcmp(), and memcpy(). It also covers arrays of strings and comparing, concatenating, copying and other operations on strings.
The document discusses arrays and strings in C programming. It covers key topics like:
- Declaring and initializing arrays and accessing array elements. Arrays have 0 as the first index.
- Difference between initialization and assignment of arrays. Arrays cannot be assigned.
- String arrays which are arrays of characters terminated by a null character.
- Common string functions like strcpy(), strcat(), strlen(), strcmp() etc.
- Two dimensional arrays and how elements are stored in row major order in contiguous memory.
- Examples of declaring, initializing and accessing 2D arrays.
C programming language allows for the declaration of arrays, which can store a fixed number of elements of the same data type. Arrays provide an efficient way to store and access related data sequentially in memory. Individual elements in an array are accessed via an index, and multi-dimensional arrays can model tables of data with multiple indices to access each element.
Arrays & Strings can be summarized as follows:
1. Arrays are fixed-size collections of elements of the same data type that are used to store lists of related data. They can be one-dimensional, two-dimensional, or multi-dimensional.
2. Strings in C are arrays of characters terminated by a null character. They are commonly used to store text data. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings.
3. Arrays are declared with a data type, name, and size. They can be initialized with a block of comma-separated values. Individual elements are accessed using indexes in square brackets. Two-dimensional arrays represent tables
An array is a collection of variables of the same data type stored in contiguous memory locations. There are two types of arrays: single dimensional and multi-dimensional arrays. A single dimensional array stores elements in adjacent memory locations. Multi-dimensional arrays can store arrays of arrays. Two dimensional arrays are commonly used to represent matrices. Arrays allow traversing, searching, and initializing elements. Functions can accept arrays as arguments which are treated as pointers to the first element.
Two-dimensional arrays in C++ allow the creation of arrays with multiple rows and columns. A 2D array is initialized and accessed using two indices, one for the row and one for the column. 2D arrays can be processed using nested for loops, with the outer loop iterating through each row and the inner loop iterating through each column. Functions can accept 2D arrays as parameters, but the number of columns must be specified since arrays are stored in row-major order.
Arrays can be passed to functions by reference, so any changes made to the array elements inside the function are reflected back in the calling function; the array name itself represents the base address of the array, which is passed to the function, while the size must be passed explicitly as a parameter; this allows the function to loop through the array and perform operations on each element using the indexes.
This document discusses strings in C++. It begins by explaining that strings are stored as character arrays terminated by a null character. It then covers declaring and initializing strings, accessing characters within strings, inputting and outputting strings using cin, gets(), and getline(), and comparing and copying strings. The document also discusses two-dimensional character arrays for storing arrays of strings. It provides examples of initializing, inputting, and displaying 2D string arrays.
An array is a group of data items of same data type that share a common name. Ordinary variables are capable of holding only one value at a time. If we want to store more than one value at a time in a single variable, we use arrays.
An array is a collective name given to a group of similar variables. Each member in the group is referred to by its position in the group.
Arrays are alloted the memory in a strictly contiguous fashion. The simplest array is a one-dimensional array which is a list of variables of same data type. An array of one-dimensional arrays is called a two-dimensional array.
This document discusses strings in C programming. It defines strings as arrays of characters terminated with a null character. It describes four methods of initializing strings: assigning a string literal with or without size, assigning characters individually with size, and assigning characters individually without size. It also covers string functions like strlen(), strcpy(), strcat(), and strcmp() to get the length, copy, concatenate, and compare strings. Finally, it discusses string arrays as two-dimensional character arrays where each string is terminated with a null character. An example program is provided to print an array of strings.
Arrays allow storing multiple values of the same type sequentially in memory. An array is declared with the type, name, and size. Elements are accessed using indexes from 0 to size-1. Strings are represented as character arrays terminated with a null character. Arrays can be passed to and returned from functions, and multidimensional arrays store arrays within arrays. Standard libraries provide functions for string and character manipulation.
- Arrays allow storing multiple values of the same type sequentially in memory. They have a fixed size or dimension.
- To declare an integer array of size 4, we write "int arr[4]". Individual elements can be accessed using indexes from 0 to dimension-1.
- Strings in C++ are arrays of characters that end with a null character. Common string functions like strcpy(), strcat(), strlen() allow manipulating strings.
The document discusses different types of arrays in C including one-dimensional, two-dimensional, and multi-dimensional arrays. It explains how to declare, initialize, and access array elements. Examples are provided to demonstrate array operations like addition, multiplication, and passing arrays to functions. The use of arrays to store strings and various string handling functions are also covered.
Arrays are ordered sets of elements of the same type that allow direct access to each element through an index. In C++, arrays have a fixed size that is declared, with elements accessed using square brackets and integers representing their position. Multidimensional arrays arrange data in tables and can be thought of as arrays of arrays. Elements are accessed using multiple indices separated by commas within the brackets.
This document discusses arrays in C programming. It defines an array as a collection of variables of the same type that are referenced by a common name. It describes single-dimensional and multi-dimensional arrays. Single-dimensional arrays are comprised of finite, homogeneous elements while multi-dimensional arrays have elements that are themselves arrays. The document provides examples of declaring, initializing, accessing, and implementing arrays in memory for both single and double-dimensional arrays. It includes sample programs demonstrating various array operations.
This document provides information about strings in C++. It defines a string as a collection of characters within double quotes. Strings are stored as character arrays terminated by a null character. The document discusses declaring and initializing strings, inputting strings from the user, and functions for manipulating strings like strcat(), strcmp(), and memcpy(). It also covers arrays of strings and comparing, concatenating, copying and other operations on strings.
The document discusses arrays and strings in C programming. It covers key topics like:
- Declaring and initializing arrays and accessing array elements. Arrays have 0 as the first index.
- Difference between initialization and assignment of arrays. Arrays cannot be assigned.
- String arrays which are arrays of characters terminated by a null character.
- Common string functions like strcpy(), strcat(), strlen(), strcmp() etc.
- Two dimensional arrays and how elements are stored in row major order in contiguous memory.
- Examples of declaring, initializing and accessing 2D arrays.
C programming language allows for the declaration of arrays, which can store a fixed number of elements of the same data type. Arrays provide an efficient way to store and access related data sequentially in memory. Individual elements in an array are accessed via an index, and multi-dimensional arrays can model tables of data with multiple indices to access each element.
Arrays & Strings can be summarized as follows:
1. Arrays are fixed-size collections of elements of the same data type that are used to store lists of related data. They can be one-dimensional, two-dimensional, or multi-dimensional.
2. Strings in C are arrays of characters terminated by a null character. They are commonly used to store text data. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings.
3. Arrays are declared with a data type, name, and size. They can be initialized with a block of comma-separated values. Individual elements are accessed using indexes in square brackets. Two-dimensional arrays represent tables
An array is a collection of variables of the same data type stored in contiguous memory locations. There are two types of arrays: single dimensional and multi-dimensional arrays. A single dimensional array stores elements in adjacent memory locations. Multi-dimensional arrays can store arrays of arrays. Two dimensional arrays are commonly used to represent matrices. Arrays allow traversing, searching, and initializing elements. Functions can accept arrays as arguments which are treated as pointers to the first element.
Two-dimensional arrays in C++ allow the creation of arrays with multiple rows and columns. A 2D array is initialized and accessed using two indices, one for the row and one for the column. 2D arrays can be processed using nested for loops, with the outer loop iterating through each row and the inner loop iterating through each column. Functions can accept 2D arrays as parameters, but the number of columns must be specified since arrays are stored in row-major order.
Arrays can be passed to functions by reference, so any changes made to the array elements inside the function are reflected back in the calling function; the array name itself represents the base address of the array, which is passed to the function, while the size must be passed explicitly as a parameter; this allows the function to loop through the array and perform operations on each element using the indexes.
This document discusses strings in C++. It begins by explaining that strings are stored as character arrays terminated by a null character. It then covers declaring and initializing strings, accessing characters within strings, inputting and outputting strings using cin, gets(), and getline(), and comparing and copying strings. The document also discusses two-dimensional character arrays for storing arrays of strings. It provides examples of initializing, inputting, and displaying 2D string arrays.
An array is a group of data items of same data type that share a common name. Ordinary variables are capable of holding only one value at a time. If we want to store more than one value at a time in a single variable, we use arrays.
An array is a collective name given to a group of similar variables. Each member in the group is referred to by its position in the group.
Arrays are alloted the memory in a strictly contiguous fashion. The simplest array is a one-dimensional array which is a list of variables of same data type. An array of one-dimensional arrays is called a two-dimensional array.
its all about Artificial Intelligence(Ai) and Machine Learning and not on advanced level you can study before the exam or can check for some information on Ai for project
The Fluke 925 is a vane anemometer, a handheld device designed to measure wind speed, air flow (volume), and temperature. It features a separate sensor and display unit, allowing greater flexibility and ease of use in tight or hard-to-reach spaces. The Fluke 925 is particularly suitable for HVAC (heating, ventilation, and air conditioning) maintenance in both residential and commercial buildings, offering a durable and cost-effective solution for routine airflow diagnostics.
Raish Khanji GTU 8th sem Internship Report.pdfRaishKhanji
This report details the practical experiences gained during an internship at Indo German Tool
Room, Ahmedabad. The internship provided hands-on training in various manufacturing technologies, encompassing both conventional and advanced techniques. Significant emphasis was placed on machining processes, including operation and fundamental
understanding of lathe and milling machines. Furthermore, the internship incorporated
modern welding technology, notably through the application of an Augmented Reality (AR)
simulator, offering a safe and effective environment for skill development. Exposure to
industrial automation was achieved through practical exercises in Programmable Logic Controllers (PLCs) using Siemens TIA software and direct operation of industrial robots
utilizing teach pendants. The principles and practical aspects of Computer Numerical Control
(CNC) technology were also explored. Complementing these manufacturing processes, the
internship included extensive application of SolidWorks software for design and modeling tasks. This comprehensive practical training has provided a foundational understanding of
key aspects of modern manufacturing and design, enhancing the technical proficiency and readiness for future engineering endeavors.
ELectronics Boards & Product Testing_Shiju.pdfShiju Jacob
This presentation provides a high level insight about DFT analysis and test coverage calculation, finalizing test strategy, and types of tests at different levels of the product.
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYijscai
With the increased use of Artificial Intelligence (AI) in malware analysis there is also an increased need to
understand the decisions models make when identifying malicious artifacts. Explainable AI (XAI) becomes
the answer to interpreting the decision-making process that AI malware analysis models use to determine
malicious benign samples to gain trust that in a production environment, the system is able to catch
malware. With any cyber innovation brings a new set of challenges and literature soon came out about XAI
as a new attack vector. Adversarial XAI (AdvXAI) is a relatively new concept but with AI applications in
many sectors, it is crucial to quickly respond to the attack surface that it creates. This paper seeks to
conceptualize a theoretical framework focused on addressing AdvXAI in malware analysis in an effort to
balance explainability with security. Following this framework, designing a machine with an AI malware
detection and analysis model will ensure that it can effectively analyze malware, explain how it came to its
decision, and be built securely to avoid adversarial attacks and manipulations. The framework focuses on
choosing malware datasets to train the model, choosing the AI model, choosing an XAI technique,
implementing AdvXAI defensive measures, and continually evaluating the model. This framework will
significantly contribute to automated malware detection and XAI efforts allowing for secure systems that
are resilient to adversarial attacks.
This paper proposes a shoulder inverse kinematics (IK) technique. Shoulder complex is comprised of the sternum, clavicle, ribs, scapula, humerus, and four joints.
2. • An array is a collection of variables of the same type
that are referred to by a common name.
• Arrays offer a convenient means of grouping
together several related variables, in one dimension
or more dimensions:
• product part numbers:
int part_numbers[] = {123, 326, 178, 1209};
• student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4,
4};
• characters:
char alphabet[5] = {’A’, ’B’, ’C’, ’D’,
’E’};
4. One-Dimensional Arrays
A one-dimensional array is a list of related variables
The general form of a one-dimensional array
declaration is:
type variable_name[size]
• type
:
• size:
• variable_name:
base type of the array,
determines the data type of
each element in the array
how many elements the
array will hold the name
of the array
Examples:
int sample[10];
float float_numbers[100];
char last_name[40];
5. Accessing Array Elements
An individual element within an array is
accessed by use of an index. An index
describes the position of an element
within an array.
Note:
In C++ the first element has the index zero!
6. Representation of Arrays in Memory
In C++, any array is mapped to a
contiguous memory location. All memory
elements reside next to each other.
The lowest address corresponds to the first
element, and the highest address to the last
element.
7. Example:
int a[8];
int j;
for(j=0; j<8; j++) a[j] = 7-j;
Then the memory representation of array a looks like
this:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7]
7 6 5 4 3 2 1 0
8. Example: Finding the Maximum
#include <iostream.h> int
main()
{
int i, max = 0; int
list[100];
// initialize the array with
random values
for(i=0; i<100; i++) list[i] = rand();
// findmaximum value
for(i=0; i<100; i++)
if(max < list[i]) max = list[i];
cout << “Maximum value: “ << max;
return(0);
}
9. No Array-to-Array Assignments
You cannot assign one array to another in
C++. The following is illegal:
int a[10], b[10];
// do something
// assign all elements of array b to array a
a = b; // error -- illegal
Instead, you have to do the assignments for each element:
int i;
// assign all elements of array b to array a
for(i=0; i<10; i++) a[i] = b[i];
10. Strings
The most common use for one-dimensional arrays is to store
strings of characters.
In C++, a string is defined as a character array terminated by
a null symbol ( ‘0’ ).
To declare an array str that could hold a 10-character string,
one would write:
char str[11];
Specifying the size as 11 makes room for the null at the end of
the string.
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’
11. Some examples of string constants in C++ are:
"hello there"
"I like C++."
"#$%§@@+*"
""" """"
""
""
The null string, ““, only contains the null
terminator and represents the empty string.
12. Reading a String from the Keyboard
How to read a string entered from the keyboard?
Make an array, that will receive the string, the target of a cin stream. The
following program reads (part of) a string entered by the user:
#include <stdio.h> int
main()
{
char str[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
Cout << str;
return(0);}
13. Problem: Entering the string “This is a test”, the above program
only returns “This”, not the entire sentence.
Reason: The C++ input/output system stops reading a string
when the first whitespace character is encountered.
Solution: Use another C++ library function, gets().
#include <iostream.h>
#include <cstdio.h>
int main()
{
char str[80]; // long enough for user input?
cout << “Enter a string: “;
gets(str); // read a string from the keyboard
cout << “Here is your string: “;
cout << str << endl;
return(0);}
14. Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions. The
most common are:
• strcpy() :
• strcat() :
• strlen() :
• strcmp() :
copy characters from one string to
another concatenation of strings
length of a string
comparison of
strings
15. strcpy(to_string, from_string) — String Copy:
#include <iostream.h>
#include <cstring.h>
int main()
{
char a[10];
strcpy(a, “hello”);
cout << a;
return(0);
}
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
h e l l o 0 ? ? ? ?
16. strlen(string) — String Length
strlen(str) returns the length of the string pointed to by str,
i.e., the number of characters excluding the null terminator.
#include <iostream.h>
#include <cstdio.h>
#include <cstring.h>
int main()
{
char str[80];
cout << “Enter a string: “;
gets(str);
cout << “Length is: “ << strlen(str);
return(0);}
17. strcat(string_1, string_2) — Concatenation of Strings
The strcat() function appends s2to the end of s1. String s2is
unchanged.
// includes ... int
main()
{
char s1[21], s2[11];
strcpy(s1, “hello”);
strcpy(s2, “ there”);
strcat(s1, s2);
cout << s1 << endl;
cout << s2 << endl;
return(0);
}
18. Note:
• The first string array has to be large enough to hold both
strings:
• To be on the safe side:
strlen(s1concats2) >= strlen(s1) + strlen(s2)
‘ ‘ t h e r e 0 ? ? ? ?
h e l l o 0 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9 1011121314151617181920
s1:
0 1 2 3 4 5 6 7 8 9 10
s2:
h e l l o ‘ ‘ t h e r e 0 ? ? ? ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9 1011121314151617181920
strcat(s1,s2):
19. strcmp(string_1, string_2) — Comparison of Strings
The strcmp(str_1, str_2) function compares two strings
and returns the following result:
• str_1 == str_2
• str_1 > str_2
• str_1 < str_2
: 0
: positive number
: negative
number
The strings are compared lexicographically
(i.e., according to dictionary order):
a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca < abd <
...
21. Using the Null Terminator
Operations on strings can be simplified using the fact that all
strings are null-terminated.
// Convert a string to uppercase
// ... includes ...
int main()
{
charstr[80];
int i;
strcpy(str, “this is a test”);
for(i=0; str[i]; i++)
str[i] = toupper(str[i]);
cout << str; return(0); }
22. Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.
To declare a two-dimensional integer array two_dim of size
10,20 we would write:
int matrix[3][4];
This corresponds to a table with 3 rows and 4 columns (for
example).
1 2 3 4
5 6 7 8
9 10 11 12
0 1 2 3
0
1
2
Left
Index
Right
Index
two_dim[1][2]
23. We can generate the array above by using this program:
#include <iostream.h>
int main()
{
int row=3, col=4;
int matrix[row][col];
for(row=0; row < 3; ++row) {
for(col=0; col < 4; ++col) {
matrix[row][col] = (row*4)+ col +1;
cout << matrix[row][col] << ‘ ‘;
}
cout << ‘n’;
}
return(0);}
24. Memory Allocation for Two-Dimensional Arrays
Storage for all array elements is determined at compile time.
The memory used to hold an array is required the entire time
that the array is in existence.
The following formula determines the number of bytes of
memory that will be allocated:
bytes = rows * columns * number_of_bytes_in_type
For example, an integer array (with two-byte integers) with
dimensions 100,100 would require 100 * 100 * 2 = 20,000
bytes.
25. Multidimensional Arrays
C++ allows arrays with more than two dimensions.
The general form of an N-dimensional array declaration is:
type array_name [size_1] [size_2] … [size_N];
For example, the following declaration creates a 4 x 10 x 20
character array, or a matrix of strings:
char string_matrix[4][10][20];
This requires 4 * 10 * 20 = 800 bytes.
If we scale the matrix by 10, i.e. to a 40 x 100 x 20 array, then
80,000 bytes are needed.
26. Array Initialization
The general form of array initialization is similar to that of
other variables:
type array-name[size] = { list-of-values };
The list-of-values has to be a comma-separated list of
constants that are type-compatible with the base type of
the array.
In the following example, a 10-element float array is
initialized with the numbers 1.0 through 10.0:
float i[10] =
{1.,2.,3.,4.,5.,6,7,8,9,10};
Therefore, i[0] will have the value 1.0, and i[9] will
have the value 10.0.
27. Character Array Initialization
Character arrays that will hold strings allow a shorthand
initialization that takes this form:
char array-name[size] = “string”;
For example, the following code fragment initializes str to
the phrase “hello”:
char str[6] = “hello”;
This is the same as writing
char str[6] =
{‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’};
Remember that one has to make sure to make the array long
enough to include the null terminator.
28. Multi-Dimensional Array Initialization
Multi-dimensional arrays are initialized the same way as one-
dimensional arrays.
For example, the following code fragment initializes an array
squares with the numbers 1 through 10 and their squares:
intsquares[9][2] =
{ 1, 1,
2, 4,
3, 9,
4, 16,
5, 25,
6, 36,
7, 49,
8, 64,
9, 81 };
29. For better readability, especially for multi-dimensional arrays,
one can use subaggregate grouping by adding braces
accordingly.
The same declaration as above can also be written as:
int squares[10][2] =
{ {1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};
30. The following program uses the squares array to find the root
of a number entered by the user.
#include <iostream.h>
// declaration of squares array goes here
int main()
{
int i, j;
cout << “Enter a number 1<=i<=100: “;
cin >> i;
// look up i
for(j=0; j<10; j++)
if(squares[j][1] == i) {
cout << "Root: " << squares[j][0];
return(0);}
cout << "No integer root."; return(0);}
32. Arrays of Strings
An array of strings is a special form of a two-dimensional array.
• The size of the left index determines the number of strings.
• The size of the right index specifies the maximum length of
each string.
For example, the following declares an array of 30 strings,
each having a maximum length of 80 characters (with one
extra character for the null terminator):
char string_array[30][81];
33. For accessing an individual string, one simply specifies only
the left index:
firstString = string_array[0];
sixthString = string_array[5];
The following example calls the gets() function with the third
string in the array:
gets(string_array[2]);
34. This program accepts lines of text entered at the keyboard
and redisplays them after a blank line is entered.
// includes go here
int main()
{
int t, i;
char text[100][80];
// quit on blank line
for(t=0; t<100; t++) {
cout << t << “: “;
gets(text[t]);
if(!text[t][0]) break;
}
for(i=0; i<t; i++) // redisplay the strings
cout << text[i] << ‘n’;
return(0);}
35. An Example Using String Arrays
Arrays of strings are commonly used for handling
tables of information.
One such application would be an employee database that
stores
• the name
• telephone number
• hours worked per pay period, and
• hourly wage.
These data we could store in arrays:
charname[20][80]; // employee names
int phone[20]; // phone numbers
float hours[20];
loat wage[20];
// hours worked
// wage
39. Main Function
int main()
{
int choice;
do {
choice = menu(); // get selection
switch(choice) {
case 0: break;
case 1: enter(); break;
case 2: report(); break;
default: cout << “Try again.nn”;
}
} while( choice != 0);
return(0);
}