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().
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 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().
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.
Arrays in C are collections of similar data types stored in contiguous memory locations that can be accessed via indexes, they can be declared with a specified data type and size and initialized with values, and multi-dimensional arrays allow the storage of two-dimensional data structures like matrices through multiple subscripts denoting rows and columns.
This document discusses C arrays. It defines an array as a collection of similar data items stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, etc. The document lists advantages like code optimization and ease of traversal using for loops. Disadvantages include fixed size arrays that cannot dynamically grow. It demonstrates declaring and initializing single-dimensional arrays and accessing elements. Multi-dimensional or 2D arrays are explained as arrays of arrays to store data in table/matrix form using row and column subscripts. Functions to search, pass arrays to functions and built-in string functions like length, copy, concatenate, comparison are also covered.
The document discusses multidimensional arrays in C++. It provides examples of declaring and initializing 2D arrays, accessing elements, and iterating through elements using for loops. It also gives examples of user input and output of 2D arrays, including a program that takes user input to populate a 2D integer array and then displays the populated array.
The Array is the most commonly used Data Structure.
An array is a collection of data elements that are of the same type (e.g., a collection of integers, collection of characters, collection of doubles).
OR
Array is a data structure that represents a collection of the same types of data.
The values held in an array are called array elements
An array stores multiple values of the same type – the element type
The element type can be a primitive type or an object reference
Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc.
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptxAbhimanyuChaure
This is an presentation of c programming language which is taught at indian institute of technology kanpur in first year first semester under bachelor of technology or bachelor of science.
At the end of this lecture students should be able to;
Describe the C arrays.
Practice the declaration, initialization and access linear arrays.
Practice the declaration, initialization and access two dimensional arrays.
Apply taught concepts for writing programs.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
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.
Arrays in C are collections of similar data types stored in contiguous memory locations that can be accessed via indexes, they can be declared with a specified data type and size and initialized with values, and multi-dimensional arrays allow the storage of two-dimensional data structures like matrices through multiple subscripts denoting rows and columns.
This document discusses C arrays. It defines an array as a collection of similar data items stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, etc. The document lists advantages like code optimization and ease of traversal using for loops. Disadvantages include fixed size arrays that cannot dynamically grow. It demonstrates declaring and initializing single-dimensional arrays and accessing elements. Multi-dimensional or 2D arrays are explained as arrays of arrays to store data in table/matrix form using row and column subscripts. Functions to search, pass arrays to functions and built-in string functions like length, copy, concatenate, comparison are also covered.
The document discusses multidimensional arrays in C++. It provides examples of declaring and initializing 2D arrays, accessing elements, and iterating through elements using for loops. It also gives examples of user input and output of 2D arrays, including a program that takes user input to populate a 2D integer array and then displays the populated array.
The Array is the most commonly used Data Structure.
An array is a collection of data elements that are of the same type (e.g., a collection of integers, collection of characters, collection of doubles).
OR
Array is a data structure that represents a collection of the same types of data.
The values held in an array are called array elements
An array stores multiple values of the same type – the element type
The element type can be a primitive type or an object reference
Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc.
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptxAbhimanyuChaure
This is an presentation of c programming language which is taught at indian institute of technology kanpur in first year first semester under bachelor of technology or bachelor of science.
At the end of this lecture students should be able to;
Describe the C arrays.
Practice the declaration, initialization and access linear arrays.
Practice the declaration, initialization and access two dimensional arrays.
Apply taught concepts for writing programs.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
A review on techniques and modelling methodologies used for checking electrom...nooriasukmaningtyas
The proper function of the integrated circuit (IC) in an inhibiting electromagnetic environment has always been a serious concern throughout the decades of revolution in the world of electronics, from disjunct devices to today’s integrated circuit technology, where billions of transistors are combined on a single chip. The automotive industry and smart vehicles in particular, are confronting design issues such as being prone to electromagnetic interference (EMI). Electronic control devices calculate incorrect outputs because of EMI and sensors give misleading values which can prove fatal in case of automotives. In this paper, the authors have non exhaustively tried to review research work concerned with the investigation of EMI in ICs and prediction of this EMI using various modelling methodologies and measurement setups.
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...IJECEIAES
Medical image analysis has witnessed significant advancements with deep learning techniques. In the domain of brain tumor segmentation, the ability to
precisely delineate tumor boundaries from magnetic resonance imaging (MRI)
scans holds profound implications for diagnosis. This study presents an ensemble convolutional neural network (CNN) with transfer learning, integrating
the state-of-the-art Deeplabv3+ architecture with the ResNet18 backbone. The
model is rigorously trained and evaluated, exhibiting remarkable performance
metrics, including an impressive global accuracy of 99.286%, a high-class accuracy of 82.191%, a mean intersection over union (IoU) of 79.900%, a weighted
IoU of 98.620%, and a Boundary F1 (BF) score of 83.303%. Notably, a detailed comparative analysis with existing methods showcases the superiority of
our proposed model. These findings underscore the model’s competence in precise brain tumor localization, underscoring its potential to revolutionize medical
image analysis and enhance healthcare outcomes. This research paves the way
for future exploration and optimization of advanced CNN models in medical
imaging, emphasizing addressing false positives and resource efficiency.
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Sinan KOZAK
Sinan from the Delivery Hero mobile infrastructure engineering team shares a deep dive into performance acceleration with Gradle build cache optimizations. Sinan shares their journey into solving complex build-cache problems that affect Gradle builds. By understanding the challenges and solutions found in our journey, we aim to demonstrate the possibilities for faster builds. The case study reveals how overlapping outputs and cache misconfigurations led to significant increases in build times, especially as the project scaled up with numerous modules using Paparazzi tests. The journey from diagnosing to defeating cache issues offers invaluable lessons on maintaining cache integrity without sacrificing functionality.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
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);
}