Find common value from two arrays - c

I am attempting to write a program which examines values in two arrays of different sizes and adds the common elements into a third array.
I am using the following code:
#include <stdio.h>
int main(void) {
// your code goes here
int A[5], B[8], i, j, s=1;
int* c;
c=(int*)malloc(s*sizeof(int));
for(i=0;i<5;i++)
{scanf("\t %d", &A[i]);}
printf("\n");
for(j=0;j=8;j++)
{scanf("\t %d", &B[j]);}
for(i=0, j=0;i<5,j<8;i++,j++)
{
if(A[i]==B[j])
{
c[i]=A[i];
s++;
printf("\n %d", c[i]);
c=realloc(c, s*sizeof(int));
break;
}
}
return 0;
}
but when I try to execute it, it is giving the problem that the time limit has been exceed. What is causing this problem? For compilation I am using the on-line compiler ideone.

Below is the code that would work.
Except for the mentioned problems in the for loops, assignment to array c was wrong.
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int A[5], B[8], i, j, s=1;
int* c;
c=(int*)malloc(s*sizeof(int));
for(i=0;i<5;i++) {scanf("\t %d", &A[i]);}
printf("\n");
for(j=0;j<8;j++) {scanf("\t %d", &B[j]);}
for(i=0;i<5;i++){
for(j=0;j<8;j++){
if(A[i]==B[j]){
c[s-1] = A[i]; // use s-1 as an index
printf("\n %d", c[s-1]);
s++;
c=(int*)realloc(c, s*sizeof(int));
}
}
}
return 0;
}

Hmmm...where to begin?
Are you only looking for characters that are the same AND in the same position? It LOOKS as though that is what you are trying to do, but as the array A and B have different dimensions, you are going to get into some trouble. And are you ONLY looking for the FIRST match? With the "break", you will stop after the first match.
Assuming you are looking for ALL element common to both lists -- in ANY position -- you will want code more like the following:
#include <stdio.h>
int main(void)
{
int A[5], B[8], C[8];
for (int i = 0; i < 5; i++)
scanf(" %d ", &A[i]);
printf("\n");
for (int i = 0; i < 8; i++)
scanf(" %d ", &B[i]);
int ci = 0;
for (int ai = 0; ai < 5; ai++)
{
for (int bi = 0; bi < 8; bi++)
{
if (A[ai] == B[bi])
{
C[ci] = A[ai];
ci++;
break;
}
}
}
C[ci] = 0;
printf("Common chars: %s\n", C);
return 0;
}
The key to what you want, I think, is the nested for loops, which iterate through EACH of the strings (A and B) separately, while looking for matching characters.

Related

I want to make a program in C which takes an array as an input and tells which number are perfect squares

#include<stdio.h>
#include<math.h>
int perfectSquare(int arr[], int n);
int main()
{
int n , arr[n];
printf("number of elements to store in array");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("enter %d number", i+1);
scanf("%d", &arr[i]);
}
perfectSquare(arr, n);
return 0;
}
int perfectSquare(int arr[], int n)
{
int i;
int a;
for (i = 0; i <= n; i++) //i=4 arr[4]==9 //arr[1]=2 i=1
{
a=sqrt((double)arr[i]); //a=3 //a=1.454=1
if ( a*a==arr[i] ) //a==3*3==9==arr[4] //a*a=1!=arr[2]
printf("%d", arr[i]);
}
}
I am new to coding and I am currently learning c. I came up with this code but it doesn't work can someone tell me what is the problem with this code?
There are a couple of issues with this exercise, but generally you're on the right track. Here, a version of your example with some possible corrections:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perfect_square(int arr[], int n);
int main(void)
{
int i, n, *arr;
printf("number of elements to store in array: ");
scanf("%d", &n);
if (n <= 0)
return -1;
arr = malloc(n*sizeof(int));
if (arr == NULL)
return -2;
for (i = 0; i < n; i++) {
printf("enter number %d: ", i+1);
scanf("%d", &arr[i]);
}
perfect_square(arr, n);
free(arr);
arr = NULL;
return 0;
}
void perfect_square(int arr[], int n)
{
int i, a;
for (i = 0; i < n; i++) {
a = (int)sqrt((double)arr[i]);
if (a*a == arr[i])
printf("%d ", arr[i]);
}
}
Some hints:
Arrays, that have an unknown size at compile time are usually allocated with malloc(), and must be deallocated again with free() (see also: alloca(), calloc(), realloc()). (In "more recent versions of C" there is also the possibility to use variable length arrays, but those can limit the portability of the code).
Always make sure to check the start value and end condition of for-loops, to prevent out of bound errors.
And try to consistently format the code, use good names and nice indentation to improve read-, maintain-, reusablilty.

Do we have to create an even and an odd array?

How can we modify the following code (which initially asks the user for 10 numbers to be entered, get stored in an array, and printed on the screen) so that the even numbers are printed on the first line, and the odd on the second:
#include <stdlib.h>
#include <stdio.h>
int i,j;
int array_1[10];
int main() {
for(i=0;i<10;i++) {
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The elements of the array are: ");
for (j=0;j<10;j++) {
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}
O(n) Solution:
you have to add odd numbers at the back of the array and add the even numbers at the front of the array and keep track of the indexes.
int array_1[10];
int main() {
int even = 0, odd = 10;
for (int i = 0; i < 10; i++) {
printf("Enter a number: ");
int inp;
scanf("%d", &inp);
if (inp % 2 == 0) {
array_1[even++] = inp;
} else {
array_1[--odd] = inp;
}
}
// even numbers
for (int i = 0; i < even; i++) {
printf("%i ", array_1[i]);
}
printf("\n");
// odd numbers
for (int i = 9; i >= odd; i--) {
printf("%i ", array_1[i]);
}
printf("\n");
return 0;
}
Since you asked, here is how I would do it. I suspect this may leave you with more questions than answers through.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define NUMBERS_SIZE 10
typedef bool (*number_validator)(int num);
bool isEven(int num)
{
return (num & 1) == 0;
}
bool isOdd(int num)
{
return (num & 1) != 0;
}
void print(const char *title, int *array, int array_size, number_validator isValid)
{
printf("%s", title);
bool first = true;
for (int i = 0; i < array_size; ++i)
{
if (isValid(array[i]))
{
if (!first)
{
printf(", ");
}
printf("%d", array[i]);
first = false;
}
}
printf("\n");
}
int main()
{
int numbers[NUMBERS_SIZE] = { 0 };
for (int i = 0; i < NUMBERS_SIZE; i++)
{
printf("Enter a number: ");
scanf("%d", &numbers[i]);
}
printf("\n");
print("Even: ", numbers, NUMBERS_SIZE, isEven);
print(" Odd: ", numbers, NUMBERS_SIZE, isOdd);
return 0;
}
Demo on ideone
you can try this way.I have used binary AND(&) instead of MOD(%) as it is faster:
#include <stdlib.h>
#include <stdio.h>
int i,j;
int array_1[10];
int main()
{
for(i=0; i<10; i++)
{
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The Even elements of the array are: ");
for (j=0; j<10; j++)
{
if((array_1[j]&1) == 0)
printf("%d ", array_1[j]);
}
printf("\nThe Odd elements of the array are: ");
for (j=0; j<10; j++)
{
if((array_1[j]&1) != 0)
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}
No need to create a new array. You can just go through it first checking for even numbers, and then again for odd numbers. Also, there's no need to declare i and j before using them. You can just declare them and initialize them in the for loop:
#include <stdlib.h>
#include <stdio.h>
int array_1[10];
int main() {
for(int i=0;i<10;i++) {
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The elements of the array are: ");
// Print even numbers
for (int j=0;j<10;j++) {
if(array_1[j] % 2 == 0)
printf("%d ", array_1[j]);
}
printf("\n");
// Print odd numbers
for (int j=0;j<10;j++) {
if(array_1[j] % 2 != 0)
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}
Edit: As tadman suggested in the comment below, there's a better and cleaner way to do this kind of task. As you can see in the above example, I'm repeating 4 lines of code where only one character changes. This task could be abstracted into a function to reduce code repetition:
void printIfMod(int* arr, size_t array_size, int mod){
for (int j=0;j<array_size;j++) {
if(arr[j] % 2 != mod)
continue;
printf("%d ", arr[j]);
}
printf("\n");
Remember to add a function prototype before main if you place the function after main:
void printIfMod(int* arr, size_t array_size, int mod);
int main(){...}
Now, to print the numbers, call the method with modulo 0 to get even numbers, and 1 to get odd numbers:
// Print even numbers
void printIfMod(&array_1, 10, 0);
// Print odd numbers
void printIfMod(&array_1, 10, 1);
One last note, hard-coding array_size is not wise, and that goes for all arrays. I recommend using sizeof() to dynamically calculate the size of your array:
size_t size = sizeof(array_1) / sizeof(int);
// Print even numbers
void printIfMod(&array_1, size, 0);
// Print odd numbers
void printIfMod(&array_1, size, 1);

undefined reference to 'WinMain' [Error] ld returned 1 exit status, passing matrix as a parameter in function

I'm starting to learn programming in C, and I have this task where I have to write a program with part of the code on another file. But I'm having problems with that last part because I'm using matrices.
Here's the main body:
#include <stdio.h>
#include "otsenkatry.c"
int main()
{
int i, j;
int a[i];
int s, gru;
char A, B, C, D, E;
printf("Introduce the number os students ", &s);
fflush(stdout);
scanf("%d", &s);
printf("Introduce their grades\n");
fflush(stdout);
for (i = 0; i<s; i++)
{
printf("a[%d] = ", i);
fflush(stdout);
scanf("%d", &a[i]);
printf("Grade: %d %d \n", a, otsenkatry(a));
fflush(stdout);//}
}
return 0;
}
And that's the part with the problem:
int otsenkatry (int* a)
{
int i;
int gru;
if (a[i]<51)
{
gru=2;
}
if (a[i]>50 && a[i]<69)
{
gru=3;
}
if (a[i]>69 && a[i]<=85)
{
gru=4;
}
if (a[i]>85 && a[i]<=100)
{
gru=5;
}
return gru;
}
I figured, that it has to do with the pointers, but I don't know how to alter it.
Your matrix has undefined size:
int i, j;
int a[i];
To declare matrix a[] properly you need to pass the size - the value of i variable. Unfortunately, the i variable is declared one line above without initialization with any value.
There are a few problems with your code:
array a not properly declared
printing array a instead of integer
argument of otsenkatry is array, but should be an int
including a .c file
using undefined i value as array index in otsenkatry
the argument &s in the first printf is invalid
the otsenkatry function can be simplified
the variables j, gru, A, B, C, D, E are defined in main but never used
Here is a corrected implementation:
#include <stdio.h>
int otsenkatry (int v) {
if (v<51)
return 2;
if (v<69)
return 3;
if (v<=85)
return 4;
if (v<=100)
return 5;
return 0;
}
int main(){
int i, a[100], s;
printf("Introduce the number of students ");
fflush(stdout);
scanf("%d", &s);
if (s > 100)
s = 100;
printf("Introduce their grades\n");
fflush(stdout);
for (i = 0; i<s; i++) {
printf("a[%d] = ", i);
fflush(stdout);
scanf("%d", &a[i]);
printf("Grade %d: %d \n", a[i], otsenkatry(a[i]));
fflush(stdout);
}
return 0;
}

How to read space-separated integers representing the array's elements and sum them up in C

How to read space-separated integers representing the array's elements and sum them up in C?
I used the below code but it reads all the elements in a new line:
#include <math.h>
#include <stdio.h>
int main() {
int i = 0, N, sum = 0, ar[i];
scanf("%d" , &N);
for (i = 0; i < N; i++) {
scanf("%d", &ar[i]);
}
for (i = 0; i < N; i++) {
sum = sum + ar[i];
}
printf("%d\n", sum);
return 0;
}
Your array ar is defined with a size of 0: the code invokes undefined behavior if the user enters a non zero number for the number of items.
Furthermore, you should check the return value of scanf(): if the user enters something not recognized as a number, your program will invoke undefined behavior instead of failing gracefully.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int i, N, sum;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
int ar[N];
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
return 0;
}
Note that the program will still fail for a sufficiently large value of N as there is no standard way to check if you are allocating too much data with automatic storage. It will invoke undefined behavior (aka stack overflow).
You should allocate the array with malloc() to avoid this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, N, sum;
int *ar;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
ar = malloc(sizeof(*ar) * N);
if (ar == NULL) {
fprintf(stderr, "cannot allocate array for %d items\n", N);
return 1;
}
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
free(ar);
return 0;
}
Finally, there is still a possibility for undefined behavior if the sum of the numbers exceeds the range of type int. Very few programmers care to detect such errors, but it can be done this way:
#include <limits.h>
...
sum = 0;
for (i = 0; i < N; i++) {
if ((sum >= 0 && arr[i] > INT_MAX - sum)
|| (sum < 0 && arr[i] < INT_MIN - sum)) {
fprintf(stderr, "integer overflow for entry %d\n", i);
return 1;
}
sum += ar[i];
}
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
scanf("%d",&ar[i]);
for(i=0; i<N; i++)
sum=sum+ar[i];
printf("%d\n", sum);
return 0;
}
This should be the code.
You have initially declared the array of size 0 (because i=0).
Even though you declared the array of size 0, when I ran it on my machine, it actually executed successfully with the correct output.
This is generally due to undefined behavior which means that we can only guess the output when the code is correct. If the code has undefined behavior, then it can do whatever it wants (and in the worst case the code will execute successfully giving the impression that it's actually correct).
Declaring a Variable Size Array (VLA) is optional in C11 standard. Thus, it depends on the implementation of the compiler whether it will support VLA or not. As pointed out by #DavidBowling in comments, if the compiler does support, then declaring a VLA of size 0 can invoke undefined behavior (which you should avoid in all cases). If it doesn't support, then this will simply give a compilation error and you'll have to declare the array size as some integer constant (example, int arr[100];).
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
}
for(i=0; i<N; i++)
{
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
You should declare the array after accepting the value of N.
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
As this is a very simple question I'll expand it a bit to include some good programming practices.
1. Analyze the problem
We have to complete two tasks here:
Read and store the numbers to array.
Sum the array elements.
Of course you can both read and calculate the same time, but we ❤ the SoC design principle. This will help you later with bigger programs.
2. Create the program structure
In this state we have to consider what function to use, as we already solved the data structure problem (we use array).
Of course, we always can put the whole procedure in main function but this would break the SoC principle.
The main principle here is:
I create a function for a separate procedure.
So we'll have to build two functions. Let's consider the following example:
ReadArrayData will be used to read the data from the standard input (your keyboard in other words) to array. But what will declare as parameters? We surely have to pass the array and the array size. The return type of this function will be void (we don't have to return something).
Keep in mind that if you pass array to function you can manipulate it as you please and keep these changes in your main program. This is because the arrays are passed always by reference to a function.
In the end this will be your function prototype:
void ReadArrayData(int arraySize, int array[]);
CalculateArraySum will be used to calculate the sum of the array elements. The function prototype will be the same as for ReadArrayData with the difference that the returning type will be int (we return the sum).
int CalculateArraySum(int arraySize, int array[]);
3. Write your program
#include <stdio.h>
void ReadArrayData(int arraySize, int array[]);
int CalculateArraySum(int arraySize, int array[]);
int main(void) {
int N;
printf("Give the array size: ");
scanf("%d", &N);
int array[N];
ReadArrayData(N, array);
int sumOfArrayElements = CalculateArraySum(N, array);
printf("The sum of array elements is %d.\n", sumOfArrayElements);
return 0;
}
void ReadArrayData(int arraySize, int array[]) {
printf("Give %d elements: ", arraySize);
for (int i = 0; i < arraySize; ++i) {
scanf("%d", &array[i]);
}
}
int CalculateArraySum(int arraySize, int array[]) {
int sum = 0;
for (int i = 0; i < arraySize; ++i) {
sum += array[i];
}
return sum;
}
I know this was a large scaled answer, but I saw you are new to computer programing. I just wanted to present you the main functionality to solve all kinds of problems. This was just a small introduction. In the end, you have to remember what steps we take to solve a problem. With time and as you solve many problems you will learn many many other things.

Take an array of numbers and then display only the distinct number

In the below code I am taking an array to read 4 numbers and I need only to display the distinct number.
#include <stdio.h>
int main(){
int ch[3];
int s[3];
int count = 0;
int i;
int j;
for(i = 0; i < 4; i++){
scanf("%d", &s[i]);
for(i = 0; i < 4; i++){
ch[i] = s[i];
printf("ch= %d", ch[j]);
}
if(ch[i] == s[i]){
count = count + 1;
printf("%d =", count);
}
}
}
Somewhat I'm not getting the output, it is giving me a weird output.
Question:
What could be the cause of the strange output?
int ch[3];
int s[3];
This mean valid references to these arrays can be made from 0 to 2 , whereas your for loop is looping 4 times.
printf("ch= %d",ch[j]);
you mean ch[i] ?
what do you use "int j" for ?
Cant understand the question but i wrote a code for taking 4 inputs and giving the distinct number among them as an output(or the numbers which have only occurred once).
#include <stdio.h>
int main(){
int ch[4];
int s[4];
int i;
int j;
for(j=0;j<4;j++){
ch[j]=0;
}
for( i=0;i<4;i++){
scanf("%d",&s[i]);
}
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if(s[i]==s[j]){
ch[i]++;
}
}
}
for(i=0;i<4;i++){
if(ch[i]==1){
printf("\n%d is the distinct number.", s[i]);
}
}
}

Resources