How to read 2D arrays in C? - c

I'm learning about 2D arrays in C and I'm a bit confused. I have the following program which reads a 2D arrays and adds its values in another array.
#include <stdio.h>
int main() {
int arr[4][5] = {{1,2,3,4,5},
{3,1,1,5,2},
{4,1,4,1,5},
{2,5,3,3,4}};
int many[4];
int i;
for (i=0;i<4;i++) {
many[i] = arr[i][i] + arr[i][i];
printf("%d\n", many[i]);
}
The output of this program is:
2
2
8
6
But I think it should be 3, 3, 9, 7 because the for loop starts at 1 and the first column and row gets 1 and second column and row get 2 because there is already 1 which means 1+1 = 2 and 2 + 1 = 3, for second number it is same idea.
For the third number I got 9 because we get 4 from row 2 column 2. 4 + 4 + 1 = 9 and for last number I got 7 because last row has 3 in row 3 column 3.

The output you get is absolutely right for this loop.
for (i=0;i<4;i++)
{
many[i] = arr[i][i] + arr[i][i];
printf("%d\n", many[i]);
}
You can easily get to know it by tracing.
so let's trace it...
during i=0
arr[0][0] denotes 1st element (as indices start from 0) of 1st array which is 1
many[0] = arr[0][0]+arr[0][0] // 1+1=2
during i=1
arr[1][1] denotes 2nd element of 2nd array which is also 1
many[0] = arr[1][1]+arr[1][1] // 1+1=2
during i=2
arr[2][2] denotes 3rd element of 3rd array which is 4
many[2] = arr[2][2]+arr[2][2] // 4+4=8
during i=3
arr[3][3] denotes 4th element of 4th array which is 3
many[3] = arr[3][3]+arr[3][3] // 3+3=6
Therefore,The output of this program is:
2
2
8
6
Note: arr[m][n] denotes (n+1)th element of (m+1)th array

You need 2 loops to iterate through your 2D array
#include <stdio.h>
int main() {
int arr[4][5] = {{1,2,3,4,5},
{3,1,1,5,2},
{4,1,4,1,5},
{2,5,3,3,4}};
int many[4];
int i;
int j;
for(i=0;i<4;i++)
{
many[i] = 0;
for(j=0;j<5;j++)
{
many[i] += arr[i][j];
}
printf("%d\n", many[i]);
}
}

Related

Why does this program print 0 instead of the specific set of values from a specified array? [duplicate]

This question already has answers here:
How to initialize 3D array in C++
(4 answers)
Closed 2 years ago.
I'd like to know why the printf function in this tiny program returns 0 instead of the array of numbers 3 2 2:
int main(){
int mat[2][2][2] = {{3,1,1},{2,2,2}};
printf("first x, 2nd y, 2nd z = %d\n",mat[0][1][1]);
}
While working with X by Y matrices in C retrieving any value XxY was a breeze, but once I added another dimension I ran into this problem. I think I must've a misunderstanding of the way C deals with coordinates in arrays. Thanks a lot!
In
int mat[2][2][2] = {{3,1,1},{2,2,2}};
you declare a 3D array but you give initialization for a 2D, the values are not placed where you expect
#include <stdio.h>
int main(){
int mat[2][2][2] = {{3,1,1},{2,2,2}};
for (int i = 0; i != 2; ++i)
for (int j = 0; j != 2; ++j)
for (int k = 0; k != 2; ++k)
printf("%d %d %d -> %d\n", i, j, k, mat[i][j][k]);
return 0;
}
Execution :
pi#raspberrypi:/tmp $ ./a.out
0 0 0 -> 3
0 0 1 -> 1
0 1 0 -> 1
0 1 1 -> 0
1 0 0 -> 2
1 0 1 -> 2
1 1 0 -> 2
1 1 1 -> 0
pi#raspberrypi:/tmp $
Furthermore because your array has 8 int but the init value has only 6 the compiler initializes the two not specified entries with 0
The problem is that this array element mat[0][1][1] does not have an explicit initializer. So it was zero-initialized.
Then you have such a declaration
int mat[2][2][2] = {{3,1,1},{2,2,2}};
then the first element of the array mat[0] as an aggregate is initialized by this list { 3, 1, 1 } and the second element of the array mat[1] is initialized by this list { 2, , 2, 2 }.
As for elements of the element mat[0] that are in turn aggregates braces are not specified then the elements of mat[0] are initialized sequentially like
mat[0][0][0] = 3
mat[0][0][1] = 1
mat[0][1][0] = 1
All other elements of the element (array) mat[0] are zero initialized.
Here is a demonstrative program.
#include <stdio.h>
int main(void)
{
int a[2][2][2] = {{3,1,1},{2,2,2}};
printf( "%d, %d, %d\n", a[0][0][0], a[0][0][1], a[0][1][0] );
printf( "%d, %d, %d\n", a[1][0][0], a[1][0][1], a[1][1][0] );
return 0;
}
Its output is
3, 1, 1
2, 2, 2
This code will give you why your result is 0:
int main(){
int mat[2][2][2] = {{3,1,1},{2,2,2}};
for(int i = 0; i < 2; i++)
for(int j = 0; j < 2; j++)
for(int k = 0; k < 2; k++)
printf("mat[%d][%d][%d] = %d \n", i, j, k, mat[i][j][k]);
return 0;
}
output:
mat[0][0][0] = 3
mat[0][0][1] = 1
mat[0][1][0] = 1
mat[0][1][1] = 0
mat[1][0][0] = 2
mat[1][0][1] = 2
mat[1][1][0] = 2
mat[1][1][1] = 0
When you declare:
int mat[2][2][2] = {{3,1,1},{2,2,2}};
it means you are lying at program that it's 2D array, not 3D.
You have a 3-dimensional array, but you're initializing a 2 level array with 1 extra value. Consider something like:
#include <cstdio>
int main(){
int mat[2][2][2] = {
{{3, 3}, {1, 1}},
{{1, 1}, {1, 1}}
};
printf("first x, 2nd y, 2nd z = %d\n", mat[0][1][1]);
}
You've specified an array with three dimensions, but only specified two. Furthermore, each element is supposed to have two entries, but you've got three.
If you turn on warnings you should see warnings like these:
test.c:4:26: warning: suggest braces around initialization of subobject [-Wmissing-braces]
int mat[2][2][2] = {{3,1,5},{2,2,2}};
...more like that...
test.c:6:44: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("z for first coordinate = %d\n",mat[0][2]);
~~ ^~~~~~~~~
test.c:6:44: warning: array index 2 is past the end of the array (which contains 2 elements)
[-Warray-bounds]
printf("z for first coordinate = %d\n",mat[0][2]);
^ ~
test.c:4:5: note: array 'mat' declared here
int mat[2][2][2] = {{3,1,5},{2,2,2}};
^
int mat[2][2][2] would initialize like this.
int mat[2][2][2] = {
{
{3,1}, {1,1},
},
{
{1,1}, {2,2},
}
};
You'll never get 3 2 2 from mat[0][1][1]. It will only ever return a single value. In this case, 1.
If you wish to store a list of 2 3D coordinates, use [2][3] instead.
int mat[2][3] = {{3,1,1},{2,2,2}};
Asking what z is for the first x and second y doesn't make sense. It's like asking what the altitude of Denver, New Jersey is (Denver is in Colorado). First x and second y are part of two different coordinates and have different z's.
Instead, you can get the z for the first coordinate like so.
printf("z for first coordinate = %d\n",mat[0][2]);
The first coordinate is mat[0] and its z is the 3rd attribute which is the 2nd index. mat[0][2].

How to shift an array elements by n places in C

If we have an array, for example, Arr[] = {1,2,3,4,5} and I want to shift the elements by 2, how can I do that?
the the array should be: {3,4,5,1,2}.
I tried to slove this way:
#include <stdio.h>
int main(void) {
int broj,pom,i,niza1[10],niza2[10],raz,tem=0,rest=0;
scanf("%d%d",&broj,&pom);//broj= number of elements and pom=shifting
for (int i=0;i<broj;i++){
scanf ("%d",&niza1[i]);
}
raz=broj-pom;//difrence between thenumber of elements and shifting
for (int i=raz;i<=broj;i++){
niza2[tem]=niza1[i-1];
tem++;
}
for (int i=0;i<broj;i++){
printf("%d",niza2[i]);
}
return 0;
}
input: 5 2
1 2 3 4 5
resault: 3 4 5 0 0
How can I add the last two numbers inside the array?
You are only copying broz - raz elements into new array.
raz=broj-pom;//difrence between thenumber of elements and shifting
for (int i=raz;i<=broj;i++){
niza2[tem]=niza1[i-1];
tem++;
}
should be
I removed unnecessary tem variable.
(i+raz)%broj you need % to wrap the copying.
raz=broj-pom;//difrence between thenumber of elements and shifting
for (int i=0;i<broj;i++){
niza2[i]=niza1[(i+raz)%broj];
}

Stuck on code about arrays and moving digits in it

There are two arrays:
s: 7 3 6 2 8
c: 0 12 5 23 14
new array: 8 3 7 6 2
Basically, you look at array c and if it has an even number, you print the one from the array s. For example, 14 is even so you print 8. You need to print them in that order, from right to left.
So I read the first two arrays, but I don't know how to put the rest of the code. If you put:
array s: 1 2 3
array c: 4 4 4
you will get: 3 2 1, which we need, but if I put 1 odd number, I will get some error number. I don't know how to put the rest of array s, after I put the even numbers.
for(d=0; d<ns; d++)
{
scanf("%d", &s[d]); //here we have the first array
}
for(d=0; d<nc; d++)
{
scanf("%d", &c[d]); //second array
}
for(d=0; d<ns; d++)
{
if(c[d]%2==0) //I check here if the nb. from second array are even
{
r[d]=s[d]; //I try to put the numbers from the first array
}
}
for(d=ns-1; d>-1; d--)
{
printf("%d ", r[d]); //I print the new array
}
}
Your problem description is not very clear, but you want to do this:
You have two arrays s and c of the same size N.
First, walk through the array backwards. If the value in c is even, add the corresponding value from s to the result array.
Finally, add the remaining elements of s to the array. The result array will now have N elements, too.
The first thing to notice is that if you look at c[4] and decide to add element s[4] to the result array, the index for that array is 0, because you add elements from the front. In general, if you want to append to an array, you do:
int array[5]; // space for 5 ints
int n = 0; // current length; start with empty array
array[n++] = 5; // array == [5]; n == 1
array[n++] = 8; // array == [5, 8]; n == 2
array[n++] = 15; // array == [5, 8, 15]; n == 3
Your backwards loop works, but it is a bit clumsy, in my opinion. In C (and other languages), ranges are described by the inclusive lower bound and an exclusive upper bound. In the range [0, N), the value N is just out of bound.
Forwad loops initialize to the lower bound, break on the upper bound and increment after each cycle. Because of this asymetry, backwards loops are simpler when you start with the upper bound, break on the lower bound, but decrement at the start of the loop:
for (i = N; i-- > 0; ) ...
The empty update section looks strange, but in this loop, the index never leaves the valid range and therefore also works with unsigned integers.
Create your arrays:
int s[N] = {7, 3, 6, 2, 8}; // value array
int c[N] = {0, 12, 5, 23, 14}; // control array
int r[N]; // result array
int k = 0; // length of r
Now walk the arrays backwards and pick the items you want:
for (i = N; i-- > 0; ) {
if (c[i] % 2 == 0) {
r[k++] = s[i];
}
}
Walk the array forwards and pick the items you didn't pick in the first pass:
for (i = 0; i < N; i++) {
if (c[i] % 2) {
r[k++] = s[i];
}
}
Voilà.

Sample exercises key words array length and indexes

Trying to improve my JAVA and was hoping for some help with the below exercises as i am struggling a bit. I have got as far as declaring the integers and doing the sums. I cant seem to work out how to do every thing else. Please help
Given an array of integers, find the sum of first half and the sum of second half. If the array length is not even numbered, return -1.
e.g
In array below, LHS sum = 10, RHS sum= 26.
1 2 3 4 5 6 7 8
AND
Given an array of integers, find ‘element to be found’ and return the index .If not found return -1.
e.g
In array below, if ‘element to be found’ = 4, then return index= 3.
1 2 3 4 5 6 7
My (poor) attempt at 1
int a=1;
int b=2;
int c=3;
int d=4;
int e=5;
int f=6;
int g=7;
int h=8;
int LHSSum=a+b+c+d;
int RHSSum=e+f+g+h;
int arrayLength=;
if (arrayLength !=)
then
System.out.println("-1");
For the first question:
int lhs = 0; //Lower half sum
int uhs = 0; //Upper half sum
int myArray = [1,2,3,4,5,6,7,8];
if (arrayLength !=) {
System.out.println("-1");
}
else {
for (i = 0; i < (myArray.length/2); i++)
{
lhs = lhs + myArray[i];
System.out.println(lhs);
}
for (i = (myArray.length/2); i < myArray.length; i++)
{
uhs = uhs + myArray[i];
System.out.println(uhs);
}
}
(I did it in the case of your array length was even)

nested loop comparing ints in an array

this is what I have. it is skipping over the zero. how can I fix that? I'm trying to count the number of times the numbers are duplicated.
void hit_rate(int a, int cmset[])
{
int i, j, k=0;
for(i=0;i<a;i++){
for(j=i;j<a;j++){
if((cmset[i] == cmset[j])){
k++;
}
}
printf("%d\n",k);
k=0;
}
}
cmset k **now** prints
4 2
6 1
0 3
0 2
0 1
1 1
2 1
4 1
While counting duplicates,
e.g. arr[5] = {1, 2, 2, 3, 3};
start with
i = 0; // first loop
j = i; //2nd loop
comapre arr[i] == arr[j]; //condition
By this what happens if you have tested arr[0] with all i = 1..4;
in next iteration, you have need not to check a[1] with arr[0], because it's already done (or checked).
increase the counter(when duplication matches). once it ends the end of the array reset counter. and print it.
I hope it helps. Still confused then I will provide you sample code.
Should be for(j=0;j<a;j++)

Resources