Arrays and Strings in Programming


Arrays and Strings in Programming

Arrays and Strings in Programming

# Arrays

Concept: An array is a contiguous block of memory used to store elements of the same data type. The data type of the array is the same as the data type of the elements it contains.

Elements of an array: Each component that makes up an array is called an element of the array.

How to distinguish elements in an array: Use array indices. Elements are numbered sequentially, starting from 0 and ending at n-1, where n is the number of elements in the array.

Syntax for declaring an array:

“`

[];

“`

Initializing an array: Assigning values to the elements of the array at the time of declaration. It is possible to not declare the number of elements when initializing.

Syntax for initializing an array:

“`

[] = {};

“`

Accessing an element in an array:

“`

[]

“`

Example:

“`c

#include

int main() {

int a[] = {1, 2, 3, 4, 5};

printf(“%d %d”, a[0], *a); // prints: 1 1

return 0;

}

“`

Multidimensional Arrays:

Syntax for declaring a multidimensional array:

“`

[]…[] [=];

“`

Accessing elements of a multidimensional array:

Similar to a one-dimensional array but with additional indices for other dimensions.

# Strings

Concept: A string is an array whose elements are characters. The last character of a string is always ‘’.

Syntax for declaring a string:

  • Incorrect: `string s;`
  • Incorrect: `char s;`
  • Incorrect: `string s[] = “hello”;`
  • Correct: `char s[] = “hello”;`

Example:

“`c

char s1[] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’};

char s2[] = “hello”;

// Prints: hello hello

“`

Note:

  • `int a[10];` The value of `a[1]` is garbage, as it has not been initialized.
  • `int a[10] = {1, 2, 3, 4, 5};` The value of `a[8]` is 0 (default value).



Leave a Reply

Your email address will not be published. Required fields are marked *