Arrays and Strings
1 Arrays
// declare an array of integers of size 10
int arr[10];
// declare and initialise an array of integers of size 10
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// get length of array arr
int arr_length = sizeof(arr)/sizeof(arr[0]);
// get standard input data inside array
for(int i=0; i<arr_length; i++)
{
scanf("%d", &arr[i]);
}
// declare a 2-by-3 integer array
int matrix[2][3];
// declare and initialise a 2-by-3 integer array
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
// get rows number
int row_num = sizeof(matrix)/sizeof(matrix[0]);
// get columns number
int column_num = sizeof(matrix[0])/sizeof(matrix[0][0]);
// get standard input data inside 2D array
for(int i=0; i<row_num; i++)
{
for(int j=0; j<column_num; j++)
{
scanf("%d", &arr[i][j]);
}
}
2 Strings
// declare a string of maximum length 50
char text[50];
// read string from standard input
// if string contains white space,
// only part before first white space is stored
scanf("%s", text);
// using fgets, strings with white space
// can be read
fgets(text, sizeof(text), stdin);
// functions
// strcpy(), strcmp(), strcat(), strlen()Last modified: Saturday, 23 November 2024, 5:48 PM