Skip to content

Instantly share code, notes, and snippets.

@isaacssemugenyi
Created September 11, 2023 11:59
Show Gist options
  • Save isaacssemugenyi/7a84888dfd24bb5e961e7b7b599333e1 to your computer and use it in GitHub Desktop.
Save isaacssemugenyi/7a84888dfd24bb5e961e7b7b599333e1 to your computer and use it in GitHub Desktop.
Multi dimensional array
#include <stdio.h>
int main()
{
int Marks[3][5] = {
{71, 75, 67, 73, 45}, // maths
{77, 65, 56, 78, 58}, // physics
{63, 57, 79, 88, 33} // chemistry
};
int out_index;
int in_index;
int overall_sum = 0;
for (out_index = 0; out_index < 3; out_index++)
{
for (in_index = 0; in_index < 5; in_index++)
{
overall_sum += Marks[out_index][in_index];
}
}
float overall_avg = float(overall_sum) / float(out_index * in_index);
printf("Overall average marks %.2f", overall_avg);
return 0;
}
#include <stdio.h>
int main()
{
int Marks[3][5] = {
{71, 75, 67, 73, 45}, // maths
{77, 65, 56, 78, 58}, // physics
{63, 57, 79, 88, 33} // chemistry
};
int out_index;
int in_index;
int sum_of_even_marks = 0;
for (out_index = 0; out_index < 3; out_index++)
{
for (in_index = 0; in_index < 5; in_index++)
{
if (Marks[out_index][in_index] % 2 == 0)
{
sum_of_even_marks += Marks[out_index][in_index];
}
}
}
printf("The sum of even numbers is %d", sum_of_even_marks);
return 0;
}
#include <stdio.h>
int main()
{
int Marks[3][5] = {
{71, 75, 67, 73, 45}, // maths
{77, 65, 56, 78, 58}, // physics
{63, 57, 79, 88, 33} // chemistry
};
printf("First Marks %d\nLast marks %d", Marks[0][0], Marks[2][4]);
// a. Average marks in Physics
int p_index;
int p_sum = 0;
for (p_index = 0; p_index < 5; p_index++)
{
p_sum = p_sum + Marks[1][p_index];
}
float p_avg = float(p_sum) / float(p_index);
printf("Average marks for Physics is %.2f", p_avg); // physics
// b. Average marks in maths
int m_index;
int m_sum = 0;
while (m_index < 5)
{
m_sum = m_sum + Marks[0][m_index];
m_index++;
}
float m_avg = float(m_sum) / float(m_index);
printf("\nAverage marks for Maths is %.2f", m_avg); // maths
// c. Average marks in Chemistry
int c_index;
int c_sum = 0;
do
{
c_sum = c_sum + Marks[2][c_index];
c_index++;
} while (c_index < 5);
float c_avg = float(c_sum) / float(c_index);
printf("\nAverage marks for Chemistry is %.2f", c_avg); // chemistry
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment