How to compare two arrays in C programming language? - c

I want to compare two different arrays which are both int. One array is static and contains numbers from 1 to 10 and second arrays asks user to enter ten different numbers and the program checks which elements from both arrays are equal.
#include <stdio.h>
int main(void) {
int array1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int array2[10];
int i;
for (i = 0; i < 11; i++) {
printf("Enter numbers: ");
scanf("%d", &array2);
}
for (i = 0; i < 11; i++) {
if (array1[i] != array2[i]) {
printf("Not equal \n");
} else {
printf("They are equal. \n");
}
}
}
The program always say not equal even if I enter a number that is equal to a number stored in first array.

scanf("%d", &array2);
You are never updating the index of array2 when getting a value from input.
Try
scanf("%d", &array2[i]);
As for comparing, you can also use memcmp to compare memory:
memcmp(array1, array2, sizeof(array1));

Arrays use zero based indices for a start. You are incorrectly populating array2 so you probably want to change your first loop to the following
for (i=0;i<10;i++)
{
printf("Enter numbers: ");
scanf("%d", &array2[i]);
}
as your current code is simply passing the address of array2 as argument to scanf.
Then change the second loop conditional to
for (i=0;i<10;i++)
in your comparison loop so that you do not access items beyond your array boundaries.
Currently your second loop is accessing items at indices 0 to 10 - but there are only 10 items present in array1 so you have undefined behaviour with your current code.

#include <stdio.h>
int main(void) {
int array1[] = {1,2,3,4,5,6,7,8,9,10};
int array2[10];
int i;
for (i=0;i<10;i++) { //fixed the range here
printf("Enter numbers: ");
scanf("%d", &array2[i]); //fixed the indexing
}
for (i=0;i<10;i++) { //fixed the range here
if (array1[i] != array2[i]) {
printf("Not equal \n");
}
else {
printf("They are equal. \n");
}
}
}

I am a beginner and I have this idea about comparing two arrays. Hope It might help someone like me.
/***compare two array: all elements are same or not(if not sorted)***/
#include<stdio.h>
int main()
{
int n;
scanf("%d", &n);
int array1[n], array2[n];
int i, j;
for(i=0; i<n; i++)
{
scanf("%d", &array1[i]);
}
for(i=0; i<n; i++)
{
scanf("%d", &array2[i]);
}
int flg=0;
for(i = 0; i < n; i++)
{
for(j=0; j<n; j++)
{
if(array1[i] == array2[j])
{
flg += 1;
break;
}
}
}
if(flg == n)
{
printf("All The Elements of array1 is present in array2... :)");
}
else
{
printf("All THe Elements of array1 is not present in array2 :(");
}
return 0;
}

I am trying to respond to the answer, even though I am a beginner to C program.
According to your program written above, you are inputting and holding values to int array2[10] which has 11 elements.
Remember that the first element of this array is indexed by zero. Ex: array2[0], until it reaches the last element which is array2[10], you have counted 11.
Now array1 has the pre-defined values write which will be compared to your input values. Enter and store your values into array2[].
#include <stdio.h>
int main(void) {
int array1[] = {1,2,3,4,5,6,7,8,9,10};
int array2[10];
int i;
for (i=0;i<10;i++) { //fixed the range here
printf("Enter numbers: ");
scanf("%d", &array2[i]); //fixed the indexing
if (array1[i] != array2[i]) {
printf("Not equal \n");
}
else {
printf("They are equal. \n");
}
}
}

Related

Adding the same number multiple times to an empty array in C

This is a piece of code to add the same number multiple times to an empty array but when I am printing the now non empty array, I am getting some other values:
#include<stdio.h>
#include<stdlib.h>
void sort_0(int arr[100], int i, int n){
int final_array[100], c=0;
// Count the number of '0' in the array
for(i=0;i<n;i++){
if(arr[i] == 0){
c++;
}
}
// Add the c number of '0' to the final_array
for(i=0;i<c;i++){
scanf("%d",final_array[i]);
}
for(i=0;i<c;i++){
printf("%d ", final_array[i]);
}
}
int main(){
int arr[100], i, n;
// Entering the size of the array
scanf("%d", &n);
// Entering n elements into the array
for(i=0;i<n;i++){
scanf("%d", &arr[i]);
}
sort_0(arr,i,n);
return 0;
}
In the above code, the number of times 0 appears in the array is counted. Then the count is taken as the range and 0 is adding to the empty array final_array count times.
If c = 5, the final_array = {0,0,0,0,0}
Expected Output:
arr = {0,1,4,3,0}
Output = 2
I am not getting any output
Since you don't know how much 0 you'll need to add to your array_final I figured out that a better solution could be to create that array after you have the number of 0 of the first array. Also, I see no reason why you were passsing i to the function since you can simply define it in the function itself.
void sort_0(int arr[10], int n, int* c){
int i;
for(i=0;i<n;i++){
if(arr[i] == 0){
(*c)+= 1;
}
}
}
int main (void) {
int size;
printf("Enter array size: ");
scanf("%d", &size);
int arr[size];
for (int i=0;i<size;i++) {
scanf("%d",&arr[i]);
}
int c = 0;
sort_0(arr, size, &c);
printf("C is: %d\n",c);
int* final_array;
if ((final_array=malloc(c * sizeof(int)))==NULL) // should always check malloc errors
{
perror("malloc");
return -1;
}
for (int i=0;i<c;i++) {
final_array[i]= 0;
}
printf("{");
for (int i=0;i<c-1;i++) {
printf("%d,", final_array[i]);
}
printf("%d}\n",final_array[c-1]);
return 0;
}

How to get the sum of two index in an array in C?

Im making a code for an array that has a dynamic size and filling the array manually.Then, it will print. It will also ask for a number and finding the index that is equal to the two indexes.
I using codeblocks for this code. Id tried for loop to find the two indexes that is eqaul to the inputed number.
#include <stdlib.h>
#include <stdio.h>
void printArray(int *array, int size) {
printf("[");
for (int i = 0; i < size - 1; i++) {
printf("%i,", array[i]);
}
if (size >= 1)
printf("%i", array[size-1]);
printf("]\n");
int num;
printf("Enter number to be calculate: ");
scanf("%d",num);
for(int i= 0; i < size - 1; i++){
if (array[i] + array[size-1] == num){
printf("%d %d", array[i],array[size-1]);
}
size--;
}
}
int main(void) {
int count;
int num;
int sum;
printf("Enter the size of the array:\n");
scanf("%d", &count);
int *array = malloc(count * sizeof(*array));
if (!array) {
printf("There was a problem you entered");
exit(EXIT_FAILURE);
}
printf("Enter the elements of the array:\n");
for (int i = 0; i < count; i++)
scanf("%d", &array[i]);
printArray(array, count);
}
I expect the output:
Index 1 and 5 are eqaul to the inputed number.
but it gives error.
To begin with, the following bug is one of the problem -
scanf("%d",num);
should be -
scanf("%d", &num);
The final loop in printArray is basically iterating through the array one element both upwards & downwards at the same time.
So, for n=6, if sum of either (a[0]+a[5]), (a[1]+a[4]) or (a[2]+a[3]) does not equal the required number , it would show up as unmatched.
This loop should be replaced by a nested loop so that inner loop iterates from j=i+1 to size-1 to allow check for a[i]+a[j] == num for all possible permutations of array indexes.

output different elements from two arrays

I am trying to output different elements from two arrays. So if i have an array A: {9, 0, 1} and B is {0, 8, 1}, I need to output an element which included in the first set, but are not included in the second :9 Can not think how I should compare all elements from the first array with the second one.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10],b[10],c,n,i,j;
printf("enter a number: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter a[%d]: ",i+1);
scanf("%d",&a[i]);
}
printf("\n");
for(j=0;j<n;j++){
printf("Enter b[%d]: ",j+1);
scanf("%d",&b[j]);
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]); }
printf("\n");
for (i = 0; i < n; i++) {
printf("%d ", b[i]); }
printf("\n");
return 0;
}
I'd like to show my thoughts but i think it's stupid:
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(a[i]!= b[j]){
c=a[i];
}
}
printf("%d ",c);
}
This can be easily solved using Binary search. Follow the simple steps.
Step 1: Sort the second array.
Step 2: For each element of the first array, binary search it in the second array, if its not present , print it, otherwise dont.
The time complexity is O(m log n), where m is length of first array and n is length of second array.
If you want a more efficient solution, as suggested by #Sumeet Singh, you can sort the second array with qsort, then find similar elements from the first array with bsearch(binary search).
Your current solution is O(N^2) time, which will be very slow with large n, but you can achieve more efficiency with this approach.
Here is some code I wrote up with demonstrates this:
#include <stdio.h>
#include <stdlib.h>
#define NNUMBERS 10
void get_array_input(int array1[], int array2[], size_t *n);
void search_elements(int array1[], int array2[], size_t n);
void print_arrays(int array[], size_t n);
int cmp_func(const void *a, const void *b);
int main(void) {
int array1[NNUMBERS], array2[NNUMBERS];
size_t n;
/* input from user */
get_array_input(array1, array2, &n);
printf("\nFirst array: ");
print_arrays(array1, n);
printf("\nSecond array: ");
print_arrays(array2, n);
/* sorting the second array */
qsort(array2, n, sizeof(*array2), cmp_func);
printf("\nSorted Second array: ");
print_arrays(array2, n);
/* the search begins */
search_elements(array1, array2, n);
return 0;
}
void get_array_input(int array1[], int array2[], size_t *n) {
size_t i;
printf("Enter n: ");
if (scanf("%zu", n) != 1) {
printf("Invalid n value.\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < *n; i++) {
printf("Enter array1[%zu]: ", i);
if (scanf("%d", &array1[i]) != 1) {
printf("Invalud array value.\n");
exit(EXIT_FAILURE);
}
}
for (i = 0; i < *n; i++) {
printf("Enter array2[%zu]: ", i);
if (scanf("%d", &array2[i]) != 1) {
printf("Invalud array value.\n");
exit(EXIT_FAILURE);
}
}
}
void search_elements(int array1[], int array2[], size_t n) {
size_t i;
void *key;
printf("\nElements in first array which are not in second array: ");
for (i = 0; i < n; i++) {
key = bsearch(&array1[i], array2, n, sizeof(*array2), cmp_func);
if (!key) {
printf("%d ", array1[i]); /* not found, so print it */
}
}
printf("\n");
}
void print_arrays(int array[], size_t n) {
size_t i;
for (i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
/* cmp function needed for qsort and bsearch */
/* many ways to write these */
int cmp_func(const void *a, const void *b) {
const int *num1 = (const int *)a;
const int *num2 = (const int *)b;
if (*num1 > *num2) {
return +1;
} else if (*num1 < *num2) {
return -1;
}
return 0;
}
Input:
Enter n: 3
Enter array1[0]: 9
Enter array1[1]: 0
Enter array1[2]: 1
Enter array2[0]: 0
Enter array2[1]: 8
Enter array2[2]: 1
Output:
First array: 9 0 1
Second array: 0 8 1
Sorted Second array: 0 1 8
Elements in first array which are not in second array: 9
You are on the right path. You are taking each value from the first array and comparing to each value in the second.
What you need to do now is to only print a[i] if there isn't any b[j] such that they are the same. The easiest way is to set a flag (say, unique=1). You can give this flag any name you find suitable, but in this case I'm thinking it says that the number a[i] is "unique" to the array a. So in this case you start with the premise that, yes, you won't find a[i] in the arrayb, and then you try to disprove your assumption. If at any time of you search you find an instance of a[i] == b[j], then your premise was wrong, so you set unique=0.
After you have compared this a[i] against all elements in b, you review your flag. And you print the appropriate message depending on whether you found this element in b or not.
Note that this assumes that the same value doesn't appear twice in a.
I have edited your code a little bit and this code gives you desired output:
#include <stdio.h>
int main(void){
int a[10],b[10],c,n,i,j;
int counter=0;
printf("enter a number: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter a[%d]: \n",i+1);
scanf("%d",&a[i]);
}
printf("\n");
for(j=0;j<n;j++){
printf("Enter b[%d]: \n",j+1);
scanf("%d",&b[j]);
}
for(i=0;i<n;i++){
counter=0;
for(j=0;j<n;j++){
if(a[i]!=b[j]){
counter++;
}
}
if(counter == n){
printf("%d ",a[i]);
}
}
return 0;
}
Let's explain this code a little bit:
In the last nested for loop, outer loop takes one element from array a. Inner loop gets every element of array b in order to compare it to taken element from array a. If none of the elements of array b is equal to a's taken element, counter will be equal to n(array size). Then we can print this element taken from a(it means there is no match between this taken element and array b's all of elements.

While loop with user input validation to fill array, then search array for largest number.

I am working on a program that will accept user input to fill an array and then quit when the user enters q. Next the array is passed to a function that finds the largest value in the array. My program seems like it would work, but I believe that user input for the array is incorrect and I am not sure how to solve it.
#include <stdio.h>
#define SIZE 30
int maxnum(int userarray[], int maxx);
int main()
{
int i;
int nums[SIZE];
int largest;
printf("Type integer numbers (up to 30), followed by q to quit:\n");
while(scanf("%d", &nums[i]) == 1)
{
for(i = 0; i < SIZE; i++)
{
//blank
}
}
largest = maxnum(nums, SIZE);
printf("The largest number is: %d\n", largest);
return 0;
}
int maxnum(int userarray[], int maxx)
{
int i;
int maxnumber;
maxnumber = userarray[0];
for(i = 1; i < maxx; i++)
{
if(maxnumber < userarray[i])
{
maxnumber = userarray[i];
}
}
return maxnumber;
}
First i is unitialized.
Then your inner for loop is strange (why someone would do that??) and sets i to SIZE in the end, which is not good.
I don't give more details, but the value of i is trash all the time because of those 2 mistakes it should be:
int i = 0;
while((i<SIZE) && (scanf("%d", &nums[i]) == 1))
{
i++;
}
so you read one by one, and protect against array out of bounds by the second condition.
After that you're passing NUMS
largest = maxnum(nums, SIZE);
whereas the array could contain fewer valid values. Just pass
largest = maxnum(nums, i);
Here is another solution for your problem.
In main() function
int n,i=0;
while(scanf("%d",&n) == 1){
nums[i++] = n;
}
n = maxnum(nums, i);
printf("The largest number is: %d\n", n);
Note : Initialize the value of i=0, Then input and update nums[] array
In maxnum() function
for(i = 0; i < maxx; i++) {
if(maxnumber < userarray[i]){
maxnumber = userarray[i];
}
}
Note: Start i=0 and find the max mumber and return the value

C Program, User input into a single array

I'm trying to use three integers that are inputted by a user in a single line into an array using CodeBlocks. But i don't really know how to go about this. Can anyone help me?
Thanks!
main()
{
int arr[3];
int onenum;
int twonum;
int threenum;
printf("Enter an Input: ");
scanf("%d %d %d",&onenum,&twonum,&threenum);
printf("Your input is: %d %d %d \n",onenum,twonum,threenum);
int arr [onenum, twonum, threenum];
return 0;
}
Use this
int i;
int arr[3];
printf("Enter numbers");
for(i=0;i<3;i++){
scanf("%d",&arr[i]);
}
This will store the 3 numbers entered by user in array arr.
Like this:
void main()
{
int arr[3];
int i;
printf("Enter an Input: ");
for(i = 0; i < 3; i++)
{
scanf("%d", &arr[i]);
}
printf("Your input is: ");
for(i = 0; i < 3; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Let's use a loop from which runs from i=0 to i=2 because you have to add 3 numbers in array.
void main()
{
int arry[3],i=0;
printf("enter numbers");
for(i=0;i<3;i++)
{
scanf("%d",&arry[i]);
}
for(i=0;i<3;i++)
{
printf("%d \n",arry[i]);
}
}
Array is a collection of data.
For beginning you can think a array with different index as a different variable of same data type means arry[0] and arry[1] in this example as different variables of same data type integer.It will help you for beginning with array but keep in mind that arry is the only one variable the index inside capital bracket tells the variable where to look.

Resources