Jul 23, 2024
char
, int
, float
, double
data_type array_name[size];
a
, b
, c
array_name[index]
Example Code:
int main() {
int a[10];
a[0] = 56;
a[9] = 90;
// Taking input in a loop
for (int i = 0; i < 10; i++) {
scanf("%d", &a[i]);
}
// Calculating sum
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += a[i];
}
// Calculating average
float average = (float)sum / 10.0;
printf("Average: %f", average);
}
data_type array_name[rows][columns];
Example Code:
int main() {
int marks[2][4] = {
{10, 20, 30, 40},
{50, 60, 70, 80}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", marks[i][j]);
}
printf("\n");
}
return 0;
}
char str[length];
char a[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
char a[10] = "Hello";
Example Code:
int main() {
char a[10] = "Hello";
printf("The string is: %s", a);
return 0;
}
scanf
Example Code:
int main() {
char word1[20], word2[20], word3[20], word4[20];
printf("Enter four words: \n");
scanf("%s %s %s %s", word1, word2, word3, word4);
printf("Word1: %s\nWord2: %s\nWord3: %s\nWord4: %s\n", word1, word2, word3, word4);
return 0;
}
Example Code:
int main() {
int a[10], n, key, flag = 0;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the number to be searched: ");
scanf("%d", &key);
for (int i = 0; i < n; i++) {
if (a[i] == key) {
flag = 1;
break;
}
}
if (flag) {
printf("Number found!");
} else {
printf("Number not found!");
}
return 0;
}
Example Code:
int main() {
int a[] = {3, 5, 7, 9, 13, 17, 33, 47, 88, 95};
int key = 17;
int start = 0, end = 9, mid;
while (start <= end) {
mid = (start + end) / 2;
if (a[mid] == key) {
printf("Found at %d", mid);
return 0;
} else if (a[mid] < key) {
start = mid + 1;
} else {
end = mid - 1;
}
}
printf("Not found");
return 0;
}
Example Code:
int main() {
int array[5] = {5, 3, 8, 2, 1};
int size = 5;
for (int i = 0; i < size - 1; i++) {
int min_index = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min_index]) {
min_index = j;
}
}
// Swap
int temp = array[i];
array[i] = array[min_index];
array[min_index] = temp;
}
// Print sorted array
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
return 0;
}
Example Code:
int main() {
int array[5] = {13, 24, 36, 17, 12};
int size = 5;
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
// Print sorted array
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
return 0;
}