nested loop comparing ints in an array - c

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++)

Related

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Ă .

How to keep while loop in bubble sort function in C

I'm trying to make my own bubble-sort function in C.
As you can see in the code below this, I'm trying to only using while / if loop to create this function. I put 5 numbers (1,3,2,5,4) so that size of array of this would be 5, and I got 5 (I checked it with Python(C)tutor. However, It works well until tab[j] gets 3. I'm trying to figure it out, but couldn't figure it out why it keeps going out when tab[j] gets 3.
Could you anybody explain what's wrong to me? I would appreciate it.
Here is my code below:
#include <stdio.h>
void ft_sort_integer_table(int *tab, int size)
{
int i;
int j;
int tem;
i = 0;
j = 0;
while(tab[i] < size)
{
if(tab[j] > tab[j+1])
{
tem = tab[j];
tab[j] = tab[j+1];
tab[j+1] = tem;
printf("%d ", tab[j]);
j++;
}
else if(tab[j] < tab[j+1])
{
printf("%d ",tab[j]);
j++;
}
i++;
}
}
int main(void)
{
int tab[] = {1,3,2,5,4};
int size = sizeof(tab)/sizeof(*tab);
ft_sort_integer_table(tab, size);
return(0);
}
You'll need an inner loop in your bubble sort, which is responsible for moving the largest element to the back and performing swaps i times (these large elements are "bubbling up"). Start the inner loop at 0 on each iteration and iterate through size - i (we know that the last i elements are sorted and in their final positions).
i controls your outer loop and should be incremented at the end of the loop (just as you would with a for loop). j controls the inner loop and should be incremented at the end of the loop.
While you're at it, it's a good idea to move your printing out of the sort function, which causes an unnecessary side effect and might frustrate your debugging efforts.
Also, it's worth mentioning that (1) for loops are more semantically appropriate here and (2) there is an optimization available by adding a boolean--as soon as you have a pass through the inner loop that performs no swaps, end early!
#include <stdio.h>
void ft_sort_integer_table(int *tab, int size)
{
int i = 0, j, tem;
while (i < size)
{
j = 0;
while (j < size - i)
{
if (tab[j] > tab[j+1])
{
tem = tab[j];
tab[j] = tab[j+1];
tab[j+1] = tem;
}
j++;
}
i++;
}
}
int main(void)
{
int tab[] = {1,3,2,5,4,6,7,1,5,6,8,9,1,4,5,1,2};
int size = sizeof(tab) / sizeof(*tab);
ft_sort_integer_table(tab, size);
for (int i = 0; i < size; i++)
{
printf("%d ", tab[i]);
}
return(0);
}
Output:
1 1 1 1 2 2 3 4 4 5 5 5 6 6 7 8 9
I'm trying to figure it out, but couldn't figure it out why it keeps
going out when tab[j] get 3.
From your code above, j increment in the same fashion as i. That means both variables will have the same value since j will be incremented by one after the if-then-else statement, and i will also be incremented by one at the end of each loop. Therefore, tab[j] is referencing the same value as tab[i]
With that being said, the boolean condition in the while loop checks whether the value in the tab[i] is less than the value of size.
When i == 3, tab[i] == 5 since in the loop, only the values in the array of index less then i are swapped/changed. Since the size variable holds that value of 5, tab[i] < size will result in a false value and exit the loop.
More information on bubble sort can be found here, https://www.geeksforgeeks.org/bubble-sort/

How to read 2D arrays in 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]);
}
}

How to count the number of different elements in a matrix? C programming language

I have an integer matrix and need to count the number of different integers besides 0 present in the matrix.
For example, in this one,
0 0 1 0
3 0 0 0
0 7 7 7
9 0 0 7
the program should give as result 4, because you can find 4 different integers apart from 0.
Keep in mind that I have to apply this to a matrix which is initialized this way:
celula ** matrizInit(int linhas, int colunas){
int i, j;
celula ** matriz;
matriz = (celula **)malloc(sizeof(celula)*linhas);
for(i = 0; i < linhas ; i++){
matriz[i] = (celula *)malloc(sizeof(celula)*colunas);
for(j = 0; j < colunas; j++){
matriz[i][j].linha = 0;
matriz[i][j].coluna = 0;
}
}
return matriz;
}
And each integer field can be accessed using matriz[i][j].[INSERT_FIELD_OF_THE_STRUCTURE].
Thanks in advance!
If the integers you're looking for range from 1 to 9, my idea would be to get an array and store there the occurrences, then loop through the array counting them.
bool inMatrix[9] = {false};
So if you found the number 5, you'd flag the position 4 (since in C arrays start at 0, which we'll leave for 1).
inMatrix[number-1] = true;
Then loop the occurrences array and count the trues
for (occurrences=0,i=0; i < 9; i++) {
if (inMatrix[i]) occurrences++;
}
And you have the number in occurrences. VoilĂ .
But if the integer range is wide, you'll definitely have to store all the numbers in a set, restricting repeated numbers and then count the elements of the set.

What needs to be modified to get desired result in this C code

I have written a small piece of code that would perform Run length encoding kind of stuff on 1-D array but still far from desired result.
main()
{
int a[8]={2,0,0,0,3,0,0,9};
int i,temp,ct=0,flag,m;
int found[90]={0};
for(i=0;i<=7;i++)
{
if(!a[i])
{
ct++;
if(!found[a[i]])
{
flag=i;
found[a[i]]=1;
}
}
}
a[flag]=ct;
m=ct;
for(i=0;i<m;i++)
{
printf("%d",a[i]);
}
}/* end of main*/
Now for above array i would like to have output something below
2 5 0 3 9
But with my piece of code am getting
2 5 0 0 3
Can I have any suggestion on that?
Shouldn't run length encoding turn 2,0,0,0,3,0,0,9 into 2 1 0 3 3 1 2 0 9 1?
1) The first thing I see is wrong is that you aren't looking at the entire array. You're using < to stop before 8, but also stopping at 7, so you only evaluate array items 0 - 6.
2) If ct stands for count it's never reset (ct=0 only on declaration). Also it's assignment is this: a[flag]= ct; which overwrites your original data. It basically tracks the value of i.
This is my version I've just put together:
#define SZ 8
main()
{
int a[SZ]={2,0,0,0,3,0,0,9};
int i; //absolute position
int runningCount = 1; //because we start at array index 1 and not zero
for (i = 1; i <= SZ; i++) {
if (a[i - 1] == a[i]) //value same as one before it...
runningCount++;
else { // new value found. print last one, and the count of the last one.
printf("%d %d ", a[i - 1], runningCount);
runningCount = 1; //reset for next loop
}
}
return 0;
}
The output is 2 1 0 3 3 1 0 2 9 1
Ok based on the comment left below, your algorithm would actually look like this:
#define SZ 8
main()
{
int a[SZ]={2,0,0,0,3,0,0,9};
int i; //absolute position
int zero_count = 0; //target zeros specifically...
for (i = 0; i < SZ; i++) {
if (a[i] == 0)
zero_count++;
}
//now write it out in a bizarre, unparsable format again...
for (i = 0; i < SZ; i++) {
if (a[i] != 0) //write out all non zero values
printf("%d ", a[i]);
if (i == 0) { //this says put the zero count after the first number was printed
printf("%d 0 ", zero_count); //inserting it into a strange place in the array
}
}
return 0;
}
which outputs: 2 5 0 3 9
You need a <= in your for loop:
for(i=0;i<=7;i++)
instead of
for(i=0;i< 7;i++)
Otherwise you miss the last element.
All you appear to be doing is (a) counting the number of times 0 occurs in the array, and (b) replacing the first occurrence of 0 with that count. It's not clear how this is meant to be a useful encoding.
In any case, you're not getting your desired result, at least in part, because you're only modifying one element of the array. I suspect what you want, or at least think you want, is to shift the non-zero elements of the array to the left as you encounter them.
What is the utility of compressing the array in the way you propose? Is some other piece of code going to have to reconstruct the original, and if so how do you expect to do so from your desired result?

Resources