"C" compares the same elements in two arrays

Source: Internet
Author: User
We all know that to determine whether there are identical elements in two arrays, only two layers for loops are required, but in the inside of the For loop, we have to notice when to jump out of the loop, which is very important, cannot be output all the time, but not both output and output.

Here is the first method:

#define _crt_secure_no_warnings 1 
#include <stdio.h>
#include <stdlib.h>
int main ()
{
	int arr1[4] = {0};
	int arr2[5] = {0};
	int i = 0,j=0,k=0;
	printf ("Please enter array 1 (4 elements): \ n");
	for (i = 0;i<sizeof (arr1)/sizeof (arr1[0)); i++)
	{
		scanf ("%d", &arr1[i]);
	printf ("Please enter array 2 (5 elements): \ n");
	For (i=0;i<sizeof (ARR2)/sizeof (arr2[0)); i++)
	{
		scanf ("%d", &arr2[i]);

	for (j = 0; j<sizeof (arr1)/sizeof (Arr1[0]); j + +)
	{for
		(k = 0;k<sizeof (arr2)/sizeof (arr2[0)); k++)
		{
			if (arr1[j] = = Arr2[k])
			{
				printf ("has the same element.) \ n ");
			}
			if (k<sizeof (ARR2)/sizeof (arr2[0]))	
			{break
				;
			}
		}
		if (j>=sizeof (arr1)/sizeof (arr1[0))	
		printf ("No identical elements.") \ n ");
	}
	return 0;
}

The above method needs to be judged more, and judge the place to be sure, the following method will be simpler:

#define _crt_secure_no_warnings 1 
#include <stdio.h>
#include <stdlib.h>
int main ()
{
	int arr1[4] = {0};
	int arr2[5] = {0};
	int i = 0,j=0,k=0;
	printf ("Please enter array 1 (4 elements): \ n");
	for (i = 0;i<sizeof (arr1)/sizeof (arr1[0)); i++)
	{
		scanf ("%d", &arr1[i]);
	printf ("Please enter array 2 (5 elements): \ n");
	For (i=0;i<sizeof (ARR2)/sizeof (arr2[0)); i++)
	{
		scanf ("%d", &arr2[i]);

	for (j = 0; j<sizeof (arr1)/sizeof (Arr1[0]); j + +)
	{for
		(k = 0;k<sizeof (arr2)/sizeof (arr2[0)); k++)
		{
			if (arr1[j] = = Arr2[k])
			{
				printf ("has the same element.) \ n ");
				return 0;
	}}} printf ("Does not have the same element.) \ n ");
	return 0;
}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.