0% found this document useful (0 votes)
3 views2 pages

Array

The document contains programming exercises in C for a Computer Science class, focusing on arrays. It includes code for calculating statistics from an array, generating Fibonacci numbers, printing a 3x3 matrix, and separating even and odd numbers in an array. Each exercise is accompanied by the relevant C code and explanations of the functionality.

Uploaded by

Hafiz Al Sami
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Array

The document contains programming exercises in C for a Computer Science class, focusing on arrays. It includes code for calculating statistics from an array, generating Fibonacci numbers, printing a 3x3 matrix, and separating even and odd numbers in an array. Each exercise is accompanied by the relevant C code and explanations of the functionality.

Uploaded by

Hafiz Al Sami
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Name: SAMI HAFIZ AL STUDENT ID: 2411604115

Class: Computer Science Class-1

Fundamental of Programming: ARRAY Codes


Exercise 1: Find Statistics (Sum, Average, Maximum, Minimum) in
an Array
#include <stdio.h>
int main() {
int len, i, total = 0, hi, lo;
float avg;
printf("How many items? ");
scanf("%d", &len);
int arr[len];
printf("Enter values:\n");
for (i = 0; i < len; i++) {
scanf("%d", &arr[i]);
total += arr[i];
}
hi = lo = arr[0];
for (i = 1; i < len; i++) {
if (arr[i] > hi) hi = arr[i];
if (arr[i] < lo) lo = arr[i];
}
avg = (float)total / len;
printf("Total: %d, Average: %.2f, Max: %d, Min: %d\n", total, avg,
hi, lo);
return 0;
}

Exercise 2: Generate and Display the First 30 Fibonacci Numbers


#include <stdio.h>
int main() {
int f[30];
f[0] = 0; f[1] = 1;
for (int m = 2; m < 30; m++)
f[m] = f[m - 1] + f[m - 2];
for (int m = 0; m < 30; m++)
printf("%d ", f[m]);
printf("\n");
return 0;
}
Exercise 3: Print the Elements of a 3x3 Array (Matrix)
#include <stdio.h>
int main() {
int matrix[3][3] = {
{101, 102, 103},
{201, 202, 203},
{301, 302, 303}
};
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++)
printf("%d ", matrix[r][c]);
printf("\n");
}
return 0;
}

Exercise 4: Separate Even and Odd Numbers in an Array


#include <stdio.h>
void exchange(int *x, int *y) {
int t = *x;
*x = *y;
*y = t;
}
int main() {
int sz, i = 0, j;
printf("Array size: ");
scanf("%d", &sz);
int a[sz];
printf("Data:\n");
for (j = 0; j < sz; j++) scanf("%d", &a[j]);
j = sz - 1;
while (i < j) {
if (a[i] % 2 == 0) i++;
else if (a[j] % 2 == 1) j--;
else exchange(&a[i], &a[j]);
}
for (int k = 0; k < sz; k++) printf("%d ", a[k]);
printf("\n");
return 0;
}

You might also like