Skip to main content

Posts

Showing posts with the label Cpp Arrays and String

C++ Arrays

Arrays & Strings C++ Arrays An array is a one of the data structure in C++, that can store a fixed size sequential collection of elements of same data type. Define an Array in C++ Syntax: type arrayName [ arraySize ]; An array type can be any valid C++ data types, and array size must be an integer constant greater than zero. Example: double salary [ 15000 ]; Initialize an Array in C++ Arrays can be initialized at declaration time: int age [ 5 ]={ 22 , 25 , 30 , 32 , 35 }; Initializing each element separately in loop: int newArray [ 5 ]; int n = 0 ; // Initializing elements of array seperately for ( n = 0 ; n < sizeof ( newArray ); n ++) { newArray [ n ] = n ; } A Pictorial Representation of the Array Accessing Array Elements in C++ int newArray [ 10 ]; int n = 0 ; // Initializing elements of array seperately for ( n = 0 ; n < sizeof ( newArray ); n ++) { newArray [ n ] = n ; } int a = newArray [ 5 ]; // Assigning 5th element of array value to integer ...

C++ Strings

C++ Strings In C++, the one-dimensional array of characters are called strings, which is terminated by a null character  \0 . Strings Declaration in C++ There are two ways to declare a string in C++: Example: Through an array of characters: char greeting [ 6 ]; Through pointers: char * greeting ; Strings Initialization in C++ Example: char greeting [ 6 ] = { 'C' , 'l' , 'o' , 'u' , 'd' , '\0' }; or char greeting [] = "Cloud" ; Memory Representation of above Defined string in C++ Example: #include <iostream> using namespace std ; int main () { char greeting [ 6 ] = { 'C' , 'l' , 'o' , 'u' , 'd' , '\0' }; cout << "Tutorials" << greeting << endl ; system ( "pause" ); return 0 ; } Program Output:

C++ Manipulating Strings

C++ Manipulating Strings A string is a sequence of character. As you know that C++ do not support built in string type, you have use earlier those null character based terminated array of characters to store and manipulate strings. These strings are termed as  C Strings . It often become inefficient performing operations on C strings. Programmers can also define their own string classes with appropriate member functions to manipulate strings. ANSI standard C++ introduces a new class called  string  which is an improvised version of C strings in several ways. In many cases, the strings object may be treated like any other built in data type. String is treated as another container class for C++. The C Style String The C style string belongs to C language and continues to support in C++ also strings in C are one dimensional array of characters which gets terminated by  \0  (null character). This is how the strings in C are declared: char ch[6] = {'H', 'e', 'l', ...

For Programs Click Here