Comparison Between two array with C - c

i am working on a school problem. I am supposed to compare two arrays and find the number of mismatches and perfect matches. Example : I have Array[4]={8,4,8,8} and ArrayB[4]={4,8,8,4}. It should print out 1 perfect match and 3 mismatches. My code is like this : . The perfect match works but mismatch does not. Please help: Mis_match means it has the SAME value but at different position in array. Perfect match means it has the SAME value and the same position in both arrays.
int m,n,j;
int perfect = 0;
int mis_match=0;
for (m=0;m<4;m++)
{
if(A[m]=B[m])
perfect++;
A[m]==B[m]=-1;
else
for (n=0;n<4;n++)
{
for (j=0;j<4;j++)
{
if(A[n]== B[j])
mis_match++;
break;
}
}
printf("we have %d perfect matches, %d mismatches", perfect,mis_match);
return 0;

You seem to have a few mistakes here. First:
int perfect, mis_match; // need to be intialized.
So you have to set them to 0.
int perfect = 0;
int mis_match = 0;
You also have to note that: if(A[m]=B[m]) (In your first loop) should be if(A[m]==B[m]) (You got comparison operator wrong).
In the second mismatch set, if the array size is the same, then you can simply just do array length - matches = mismatches Since if it's not a match, it's a mismatch.

Code:
int a[4] = {8,4,8,8};
int b[4] = {4,8,8,4};
int mc = 0;
for(int i=0; i < 4; ++i)
if (a[i] == b[i])
++mc;
printf("we have %d perfect matches, %d mismatches", mc, 4 - mc);

Whatever I understand you need not to use any nested loops it increases the time complexity. I think it simply.
Here is the code--
int main(){
int A[4] = {8,4,8,8};
int B[4] = {4,8,8,4};
int perfect = 0;
int mis_match = 0;
for ( int i = 0; i < 4; i++ ){
if( A[i] == B[i] )
perfect++;
else
mis_match++;
}
printf("we have %d perfect matches, %d mismatches", perfect,mis_match);

First of all, you need to initialize the variable mis_match to 0. You do not even need this variable actually. You just check each element of the first array with each element of the second array and increment perfect if they match. Then calculate the difference between the size of the array and perfect. That is the number of mismatches.
Your modified code should look like this
int perfect=0,m=4;
int A[4]={8,4,8,8},B[4]={4,8,8,4};
for(i=0;i<m;i++)
{
if(A[i]==B[i])
perfect++;
}
printf("We have %d perfect matches and %d mismatches",perfect,m-perfect);
You have used if(A[m]=B[m]), which is wrong. This statement will assign the value ofB[m] in A[m] instead of checking whether they are equal. You need to use the == operator to check their equality.

Related

checking if a array has numbers in it from 0 to length -1 in C

I have got an assignment and i'll be glad if you can help me with one question
in this assignment, i have a question that goes like this:
write a function that receives an array and it's length.
the purpose of the function is to check if the array has all numbers from 0 to length-1, if it does the function will return 1 or 0 otherwise.The function can go through the array only one.
you cant sort the array or use a counting array in the function
i wrote the function that calculate the sum and the product of the array's values and indexes
int All_Num_Check(int *arr, int n)
{
int i, index_sum = 0, arr_sum = 0, index_multi = 1, arr_multi = 1;
for (i = 0; i < n; i++)
{
if (i != 0)
index_multi *= i;
if (arr[i] != 0)
arr_multi *= arr[i];
index_sum += i;
arr_sum += arr[i];
}
if ((index_sum == arr_sum) && (index_multi == arr_multi))
return 1;
return 0;
}
i.e: length = 5, arr={0,3,4,2,1} - that's a proper array
length = 5 , arr={0,3,3,4,2} - that's not proper array
unfortunately, this function doesnt work properly in all different cases of number variations.
i.e: length = 5 , {1,2,2,2,3}
thank you your help.
Checking the sum and product is not enough, as your counter-example demonstrates.
A simple solution would be to just sort the array and then check that at every position i, a[i] == i.
Edit: The original question was edited such that sorting is also prohibited. Assuming all the numbers are positive, the following solution "marks" numbers in the required range by negating the corresponding index.
If any array cell already contains a marked number, it means we have a duplicate.
int All_Num_Check(int *arr, int n) {
int i, j;
for (i = 0; i < n; i++) {
j = abs(arr[i]);
if ((j >= n) || (arr[j] < 0)) return 0;
arr[j] = -arr[j];
}
return 1;
}
I thought for a while, and then i realized that it is a highly contrained problem.
Things that are not allowed:
Use of counting array.
Use of sorting.
Use of more than one pass to the original array.
Hence, i came up with this approach of using XOR operation to determine the results.
a ^ a = 0
a^b^c = a^c^b.
Try this:
int main(int argc, char const *argv[])
{
int arr[5], i, n , temp = 0;
for(i=0;i<n; i++){
if( i == 0){
temp = arr[i]^i;
}
else{
temp = temp^(i^arr[i]);
}
}
if(temp == 0){
return 1;
}
else{
return 0;
}
}
To satisfy the condition mentioned in the problem, every number has to occour excatly once.
Now, as the number lies in the range [0,.. n-1], the looping variable will also have the same possible range.
Variable temp , is originally set to 0.
Now, if all the numbers appear in this way, then each number will appear excatly twice.
And XORing the same number twice results in 0.
So, if in the end, when the whole array is traversed and a zero is obtained, this means that the array contains all the numbers excatly once.
Otherwise, multiple copies of a number is present, hence, this won't evaluate to 0.

C language: I want to see if a value of a[] is less than all the values of b[]

I have to solve an exercise in C. The exercise asks me to get 2 arrays (a, b) from input and see if there is a value of a[] which is less than all the values of b.
Both array have 3 elements.
The code I wrote is the following:
for (int i = 0; i < 3; ++i)
{
while(k<3)
{
if(a[i]<a[k])
{
count++;
if (count==3)
{
break;
}
}
k++;
}
count=0;
}
if (count==3)
{
printf("TRUE");
}
else
{
printf("FALSE");
}
The problem with the code is that it prints false in any input I give.
Any help would be appreciated.
P.S. I left out the scanning from keyboard of the arrays and the declaration of i and k to keep the code short and clearer.
For starters do not use magic numbers like 3. Instead use named constants.
In this statement
if(a[i]<a[k])
you are comparing elements of the same array a instead of comparing an element of a with an element of the array b.
Also before the while loop you have to set the variables count and k to 0.
for (int i = 0; i < 3; ++i)
{
k = 0;
count = 0;
while(k<3)
And the break statement breaks the while loop but it does not break the outer for loop.
The code does not determine the position of the target element of the array a that is less than all elements of the array b.
You could write a separate function that does the task.
Here is a demonstrative program.
#include <stdio.h>
size_t find_less_than( const int a[], const int b[], size_t n )
{
size_t i = 0;
for ( _Bool found = 0; !found && i < n; i += !found )
{
size_t j = 0;
while ( j < n && a[i] < b[j] ) j++;
found = j == n;
}
return i;
}
int main(void)
{
enum { N = 3 };
int a[N], b[N];
printf( "Enter %d values of the array a: ", N );
for ( size_t i = 0; i < N; i++ ) scanf( "%d", &a[i] );
printf( "Enter %d values of the array b: ", N );
for ( size_t i = 0; i < N; i++ ) scanf( "%d", &b[i] );
size_t i = find_less_than( a, b, N );
if ( i != N )
{
printf( "The element at position %zu with the value %d of the array a\n"
"is less than all elements of the array b\n", i, a[i] );
}
else
{
puts( "There is no element in the array a\n"
"that is less than all elements of the array b\n" );
}
return 0;
}
Its output might look like
Enter 3 values of the array a: 3 0 1
Enter 3 values of the array b: 1 2 3
The element at position 1 with the value 0 of the array a
is less than all elements of the array b
Writing programs is mechanics. Of course, it seems challenging at first, but it rapidly becomes easier; you only need to translate the description of a solution ("first do this, then do that") into a programming language.
The real art is coming up with good solutions. A good solution does not waste time or space, for example. And it also scales to larger problems.
In this problem, the obvious solution is to take each element in turn from a and see if it is less than every element of b. In the worst case, that will involve comparing every element of a with every element of b. That doesn't matter much if they both only have three elements, but suppose they had a million elements. Then that procedure could end up comparing every element of a with every element of b, a total of 1,000,000,000,000 comparisons. Even on modern hardware, that would take a long time.
But there is an easy improvement. If an element from a is not less than any element of b, then it is not less than the smallest element of b. Conversely, if it is less than every element of b, then it is obviously less than the smallest element of b.
So it is not necessary to compare with every element of b; only with the smallest element of b. We don't initially know what that element is, but it is straight-forward to scan b once to find it, and then use it in a scan of a. That lets us solve the million element problem with at most 1,999,999 comparisons, which I think you will agree is a lot more practical.
Sometimes nested loops are necessary. But when you see one, you should always at least ask yourself, "is there a better solution?" Because the art and joy of programming isn't the mechanical translation of algorithm into code; it is the eureka moment in which that better solution reveals itself to you.
To check if there is a value in a that is less than all the values of b, you can use a double for loop:
for (int i = 0; i < 3; ++i)
{
int count= 0;
for (int j = 0; j < 3; ++j)
{
if(a[i]<b[j])
{
count++;
}
}
if (count==3) break;
}
if (i<3) printf("%d\n", a[i]);
Another approach, which is faster, is to first find the smallest of a and then check for each b if this is smaller:
int smallest= a[0];
for (int i = 1; i < 3; ++i)
if (a[i]<smallest) smallest=a[i];
int count= 0;
for (int i = 0; i < 3; ++i)
if(<b[i]<smallest)
count++;
if (count==3) printf("yes\n");
The first version has a nested loop, and so has n*n iterations. The second has only n+n iterations (also called O(n2) and O(n+n)).

C - Passing a 3D arrays of chars to a function

I'm trying to write a program that analyzes a (3 x 4) matrix of strings provided by the user. Ultimately, it needs to output the longest string present in the matrix, along with that string's length.
My program seems to read the input correctly, as judged its success in echoing back the input strings, but it does not correctly output the longest word. I'm sure I'm committing some kind of pointer-related error when I pass the value of longest word, but I do not have any idea how to solve it.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 4
#define N 5
#define MAX_DIM 20
void findMAX(char matrice[N][M][MAX_DIM]) {
char maxr;
int index;
int i, j, it;
index = 0;
maxr = *(*(*(matrice+0)+0)+MAX_DIM);
for (i = 0; i < N-1; i++) {
for (j = 0; j < M-1; j++) {
if (index < strlen(matrice[i][j])) {
index = strlen(matrice[i][j]);
// I save the longer line's value
it = i;
// I save the maximum's value
maxr = *(*(*(matrice+i)+j)+MAX_DIM);
}
}
}
printf ("The MAX is: -/%s/- and it's long: -/%d/- \n", maxr, index);
printf ("It is content in the: %d line, which is: \n", it);
for (j = 0; j < N-1; j++) {
printf("%s ", matrice[it][j]);
}
}
void leggi(char matrice[N][M][MAX_DIM]) {
int i, j;
for (i = 0; i < N-1; i++) {
for (j = 0; j < M-1; j++) {
printf ("Insert the element matrix [%d][%d]: ", i, j);
scanf ("%s", matrice[i][j]);
fflush(stdin);
}
}
}
void stampa(char matrice[N][M][MAX_DIM]) {
int i, j;
printf("\n(4 x 3) MATRIX\n");
for (i = 0; i < N-1; i++) {
for (j = 0; j < M-1; j++) {
printf("%s ", matrice[i][j]);
}
printf("\n\n");
}
}
int main(int argc, char *argv[]) {
char matrix[N][M][MAX_DIM]; //Matrix of N*M strings, which are long MAX_DIM
printf("************************************************\n");
printf("** FIND THE LINE WITH THE MAXIMUM ELEMENT **\n");
printf("** IN A (4 x 3) MATRIX **\n");
printf("************************************************\n");
printf ("Matrix Reading & Printing\n");
leggi (matrix);
stampa (matrix);
findMAX(matrix);
return 0;
}
First of all to address some misconceptions conveyed by another answer, consider your 3D array declared as
char matrix[N][M][MAX_DIM];
, where N, M, and MAX_DIM are macros expanding to integer constants.
This is an ordinary array (not a variable-length array).
If you want to pass this array to a function, it is perfectly acceptable to declare the corresponding function parameter exactly the same way as you've declared the array, as indeed you do:
void findMAX(char matrice[N][M][MAX_DIM])
But it is true that what is actually passed is not the array itself, but a pointer to its first element (by which all other elements can also be accessed. In C, multidimensional arrays are arrays of arrays, so the first element of a three-dimensional array is a two-dimensional array. In any case, that function declaration is equivalent to both of these:
void findMAX(char (*matrice)[M][MAX_DIM])
void findMAX(char matrice[][M][MAX_DIM])
Note in particular that the first dimension is not conveyed. Of those three equivalent forms, I find the last clearest in most cases.
It is quite odd, though, the way you access array elements in your findMAX() function. Here is the prototypical example of what you do:
maxr = *(*(*(matrice+i)+j)+MAX_DIM);
But what an ugly and confusing expression that is, especially compared to this guaranteed-equivalent one:
maxr = matrice[i][j][MAX_DIM];
Looking at that however, and it how you are using it, I find that although the assignment is type-correct, you are probably using the wrong type. maxr holds a single char. If you mean it to somehow capture the value of a whole string, then you need to declare it either as an array (into which you will copy strings' contents as needed), or as a pointer that you will set to point to the string of interest. The latter approach is more efficient, and I see nothing to recommend the former for your particular usage.
Thus, I think you want
char *maxr;
... and later ...
maxr = matrice[0][0];
... and ...
maxr = matrice[i][j];
That sort of usage should be familiar to you from, for example, your function stampo(); the primary difference is that now you're assigning the expression to a variable instead of passing it directly to a function.
And it turns out that changing maxr's type that way will correct the real problem here, which #AnttiHaapala already pointed out in comments: this function call ...
printf ("The MAX is: -/%s/- and it's long: -/%d/- \n", maxr, index);
requires the second argument (maxr) to be a pointer to a null-terminated array of char in order to correspond to the %s directive in the format string. Before, you were passing a single char instead, but with this correction you should get mostly the expected result.
You will probably, however, see at least one additional anomaly. You final loop in that function has the wrong bound. You are iterating with j, which is used as an index for the second dimension of your array. That dimension's extent is M, but the loop runs to N - 1.
Finally, I should observe that it's odd that you allocate space for a 5 x 4 array (of char arrays) and then ignore the last row and column. But that's merely wasteful, not wrong.
Try something like this:
void findMAX(char matrice[N][M][MAX_DIM]){
// char maxr
char maxr[MAX_DIM];
int index;
int i, j, it;
index = 0;
// maxr = *(*(*(matrice+0)+0)+MAX_DIM);
strncpy(maxr, *(*(matrice+0)+0), MAX_DIM);
for (i = 0; i < N-1; i++)
{
for (j = 0; j < M-1; j++)
{
if (index < strlen(matrice[i][j]))
{
index = strlen(matrice[i][j]);
it = i;
// maxr = *(*(*(matrice+i)+j)+MAX_DIM);
strncpy(maxr, *(*(matrice+i)+j), MAX_DIM);
}
}
}
printf ("The MAX is: -/%s/- and it's long: -/%d/- \n", maxr, index);
printf ("It is content in the: %d line, which is: \n", it);
// for (j = 0; j < N-1; j++){
for (j = 0; j < M-1; j++){
printf("%s ", matrice[it][j]);
}
}
It's possible to pass multi-dimensional arrays to C functions if the size of the minor dimensions is known at compile time. However the syntax is unacceptable
void foo( int (*array2d)[6] )
Often array dimensions aren't known at compile time and it is necessary to create a flat array and access via
array2D[y*width+x]
Generally it's easier just to use this method even if array dimensions are known.
To clarify in response to a comment, C99 allows passing of variable size arrays using the more intuitive syntax. However the standard isn't supported by Microsoft's Visual C++ compiler, which means that you can't use it for many practical purposes.

sum of positive integers in a array C

I'm trying to find the sum of all positive numbers in an array. So far, I have come up with this;
int largest_sum_sequence(int list, int size)
{
int sum = 0, *index = 0;
for (index < size; index = size; index++)
{
if (list[index] > 0)
{
sum = sum + list[index];
}
}
printf("%d", sum);
return sum;
}
My program keeps crashing. I'm pretty sure it has something to do with index. Whenever I use list[index] it says that I need to use a pointer for index, but I don't know how to do that properly. Help is appreciated!
You do not want index to be a pointer, and your for loop is incorrect. Try:
int sum = 0, index = 0;
for (; index < size; index++)
The compiler tells you actually exactly what to do.
First of all you need an array or a pointer as a parameter, like
int largest_sum_sequence(int *list, int size)
{
....
}
or
int largest_sum_sequence(int list[], int size)
{
....
}
where the latter might be easier to read.
The second thing is, you don't want to iterate with a pointer through the list, but more with a simple integer.
so you declare
int sum = 0, index = 0;
The for() loop isn't quite correct either. Instead of initializing something, you test if index < size and discard the result. This is syntactically correct, but doesn't make sense.
The first part in the for-statement is executed before the loop starts, but doesn't influence the starting itself. It is meant for initializing the loop variable (index in this case). The second part is the termination condition. The loop terminates if the condition evaluates to false. The last part of the loop is for incrementing (or decrementing, more abstract, changing) the loop variable.
Having said this, it is halfway obvious it should look like:
for (index = 0; index < size; ++index) {
....
}
Assuming your list isn't very long (such that the sum could exceed 2^{31} - 1), the rest is correct. Although I'd add an \n to the printf() pattern.
Where is the list coming from? Can't answer that from your code, but you've room for mistakes here too :-)
Function argument doesn't except an array.
Quick function I wrote.
int getSums(int myArray[], int size)
{
int total = 0;
int index = size;
for ( int i = 0; i < index; i++)
{
if (myArray[i] > 0)
total += myArray[i];
}
return ( total );
};

Trying to find if the element of an int array is equal to a number entered in C

I'm trying to use a for loop to iterate over the elements of an integer array and find out if a particular element in that array is equal to some other integer.
Here's what I've got, and it doesn't seem to work:
int squaresArray[1000];
int numberOfSquares = 1000;
int i = 0;
for (i; i<=numberOfSquares; i++)
{
squaresArray[i] = i*i;
if (number == squaresArray[i]){
printf("%d is a perfect square\n", number);}
break;
}
According to what I know about for loops this should work, but it prints nothing even when the number should be equal to some element of the array.
You're breaking on the first iteration due to misplaced brackets (i.e. break is not in the scope of the if-statement). Change it to:
if (number == squaresArray[i]) {
printf("%d is a perfect square\n", number); // no closing bracket here
break;
} // <--
Also, your loop condition should probably be i < numberOfSquares. After all, numberOfSquares (1000) is an out of bounds index for an array of length 1000. Moreover, you don't need a loop initialization statement if you've already declared/initialized i in the loop's enclosing scope. Hence, we're left with
int i = 0;
for (; i < numberOfSquares; i++)
If you're using C99 and above, you can limit the scope of i to only the loop, which should be preferred:
for (int i = 0; i < numberOfSquares; i++)

Resources