My sorting function gives unexpected output - c

I write a generalized C language program that given a sequence of numbers, sorts, even numbers in ascending order, odd numbers in descending order and places all even numbers in the initial part of an array then odd numbers.
Example: 2, 5, 1, 0, 4, 7, 9, 3, -2, 10, 20, 15
Expect: -2, 0, 2, 4, 10, 20, 15, 9, 7, 5, 3, 1
Six functions are required. The solution must be provided using only the mentioned functions.No global variables shall be declared. Use appropriate data types, return types and function arguments.
Input() – takes total number of elements and values as input from the user. Stores the values in “input” array.
SortEven() – sorts the even numbers in ascending order and stores them in an array named “even”
SortOdd() – sorts the odd numbers in descending order and stores them in an array named “odd”
Merge() – places all the even numbers in the initial part of array named “result” then odd numbers.
Display() – displays the contents of “result” array.
main() – calls the Input() module to begin the execution.
Program:
#include <stdio.h>
int main() {
input();
}
int input() {
int n;
printf("Enter The Number Of Elements You Want To Enter : ");
scanf("%d", &n);
int a[n], i, ev = 0, od = 0;
for (i = 0; i < n; i++) {
printf("Enter Number : ");
scanf("%d", &a[i]);
if (a[i] % 2 == 0) {
ev++;
} else {
od++;
}
}
sorteven(a, ev, od, n);
}
int sorteven(int a[], int ev, int od, int n) {
int i, j = 0, swap, even[ev];
for (i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
even[j] = a[i];
j++;
}
}
for (i = 0; i < ev - 1; i++) {
for (j = 0; j < ev - i - 1; j++) {
if (even[j] > even[j + 1]) {
swap = even[j];
even[j] = even[j + 1];
even[j + 1] = swap;
}
}
}
sortodd(a, ev, od, n, even);
}
int sortodd(int a[], int ev, int od, int n, int even[]) {
int i, k = 0, swap, odd[od], j;
for (i = 0; i < n; i++) {
if (a[i] % 2 != 0) {
odd[k] = a[i];
k++;
}
}
for (i = 0; i < od - 1; i++) {
for (j = 0; j < od - i - 1; j++) {
if (odd[j] < odd[j + 1]) {
swap = odd[j];
odd[j] = odd[j + 1];
odd[j + 1] = swap;
}
}
}
merge(a, ev, od, n, even, odd);
}
int merge(int a[], int ev, int od, int n, int even[], int odd[]) {
int merge[n], i;
for (i = 0; i < ev; i++) {
merge[i] = even[i];
}
for (i = ev; i < n; i++) {
merge[i] = odd[i];
}
display(merge, n);
}
int display(int merge[], int n) {
int i;
printf("OUTPUT : ");
for (i = 0; i < n; i++) {
printf(" %d ", merge[i]);
}
}

When looking in the source code, the problem is located in the merge() function.
Both sorteven() and sortodd()are well implemented, but when merging both sub-arrays, the for(i=ev;i<n;i++) is not correct.
To add the odd[] array at the end of the even[] array, write:
int j;
// point to the first item of odd[]
for(i=ev,j=0;i<n;i++,j++)
{
merge[i]=odd[j];
}
Instead of:
only odd[0] to odd[od-1] are allocated and defined.
for(i=ev;i<n;i++)
{
merge[i]=odd[i];
}
Outputs of:
{ 2, 5, 1, 0, 4, 7, 9, 3, -2, 10, 20, 15 };
Are:
OUTPUT : -2 0 2 4 10 20 15 9 7 5 3 1

Related

How do I reverse a specific row of a multidimensional array in C?

I have a multidimensional array with 3 rows and 4 columns. The program should use reverseRow()function to reverse a specific row from an array. Like, let's say user's input is 2, then it should reverse second row and print it.
I have tried a swap method, but it didn't work. I also tried using pointers, but it didn't work as well. Can someone explain it for me? How do I reverse a specific row?
#include <stdlib.h>
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int n = sizeof(arr) / sizeof(arr[0]);
void reverseRow(int low, int high)
{
if (low < high)
{
int temp = arr[low][0];
arr[low][0] = arr[high][0];
arr[high][0] = temp;
reverseRow(low + 1, high - 1);
for (int i = 0; i < n; i++)
for (int j = 3; i > 0; j--)
printf("%d ", arr[i][j]);
}
}
void printMenu()
{
printf("\n");
printf("You can choose one of these services: \n");
printf("1. Get the elements of a specific row reversed \n");
printf("Please select one to try ");
int answer;
scanf("%d", &answer);
switch (answer)
{
case 1:
reverseRow(0, n - 1);
break;
case 2:
printf("Bye!\n");
break;
default:
printf("please select carefully! \n");
break;
}
}
int main()
{
printMenu();
return 0;
}
Best regards.
You're reversing the first column, not a user-selected row.
You're not passing the row number to the function.
The loop that prints the array is printing all the columns in reverse order, and it's using n as the number of rows, not columns. I've renamed the variables to be clearer and fixed the printing loop.
#include <stdio.h>
#include <stdlib.h>
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int rows = sizeof(arr) / sizeof(arr[0]);
int cols = sizeof(arr[0]) / sizeof(arr[0][0]);
void reverseRow(int rownum, int low, int high)
{
if (low < high)
{
int temp = arr[rownum][low];
arr[rownum][low] = arr[rownum][high];
arr[rownum][high] = temp;
reverseRow(rownum, low + 1, high - 1);
} else {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
}
void printMenu()
{
printf("\n");
printf("You can choose one of these services: \n");
printf("1. Get the elements of a specific row reversed \n");
printf("Please select one to try ");
int answer;
scanf("%d", &answer);
switch (answer)
{
case 1:
printf("Please select row number: ");
int row;
scanf("%d", &row);
if (row >= rows || row < 0) {
printf("Invalid row\n");
break;
}
reverseRow(row, 0, cols - 1);
break;
case 2:
printf("Bye!\n");
break;
default:
printf("please select carefully! \n");
break;
}
}
int main()
{
printMenu();
return 0;
}
What is the row of a two-dimensional array?
It is a one dimensional array.
So what you need is to write a function that reverses a one-dimensional array.
An iterative function can look the following way
void reverseRow( int *a, size_t n )
{
for ( size_t i = 0; i < n / 2; i++ )
{
int tmp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = tmp;
}
}
A recursive function can look the following way
void reverseRow( int *a, size_t n )
{
if ( !( n < 2 ) )
{
int tmp = a[0];
a[0] = a[n-1];
a[n-1] = tmp;
reverseRow( a + 1, n - 2 );
}
}
And either function is called like for example
reverseRow( arr[1], 4 );
that reverses the second row of the original array.
Or if the number of row (starting from 0) is stored in some variable as for example row then the function is called like
reverseRow( arr[row], 4 );
To output the reversed row you need to write a separate function.
Here is a demonstration program.
#include <stdio.h>
void reverseRowIterative( int *a, size_t n )
{
for (size_t i = 0; i < n / 2; i++)
{
int tmp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = tmp;
}
}
void reverseRowRecursive( int *a, size_t n )
{
if (!( n < 2 ))
{
int tmp = a[0];
a[0] = a[n - 1];
a[n - 1] = tmp;
reverseRowRecursive( a + 1, n - 2 );
}
}
void printRow( const int *a, size_t n )
{
for (size_t i = 0; i < n; i++)
{
printf( "%2d ", a[i] );
}
putchar( '\n' );
}
int main( void )
{
enum { M = 3, N = 4 };
int arr[M][N] =
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
for ( size_t i = 0; i < M; i++ )
{
reverseRowIterative( arr[i], N );
printRow( arr[i], N );
}
putchar( '\n' );
for (size_t i = 0; i < M; i++)
{
reverseRowRecursive( arr[i], N );
printRow( arr[i], N );
}
putchar( '\n' );
}
The program output is
4 3 2 1
8 7 6 5
12 11 10 9
1 2 3 4
5 6 7 8
9 10 11 12

Concentric square matrix

I have coding problem to write concentric square matrix (biggest number is in the middle) For example user needs to write an matrix For example:
5 5 5 5 5
5 6 6 6 5
5 6 7 6 5
5 6 6 6 5
5 5 5 5 5
My program has to output "Yes" because this is, by my program's rules, a concentric square matrix.
5 5 5 5 5
5 6 6 6 5
5 6 7 8 5
5 6 6 6 5
5 5 5 5 5
This is not a concentric square matrix because 8 is in 4th column and 3rd row.
This is my code:
#include <stdio.h>
int main() {
int mat[100][100];
int i,j;
int n;
scanf("%d",&n);
printf("Unesite matricu; ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&mat[i][j]);
}
}
}
I don't know how to do the rest of it so if someone can help me, I would be happy :))
Comment::
I forgot to say that only odd numbers can be the dimension of the matrix (1,3,11,27). The only final output of the program has to be "YES (if the matrix is a concentric square matrix) or "NO" (if it's not). I know how to make a concentric square matrix when the user inputs a number (for example, 4) and the matrix has 2*n-1 dimensions. And through the loops, the program automatically makes the matrix (if you know what I mean). But for my matrix, the user has to input all the elements of the matrix and the program has to check if the matrix is concentric or not.
Would you please try the following:
#include <stdio.h>
int main() {
int mat[100][100];
int ii[] = {0, 1, 0, -1}; // incremental numbers of i
int jj[] = {1, 0, -1, 0}; // incremental numbers of j
int i, j;
int n;
int u, v, w; // variables to walk on edges
int val; // value of the element
int prev; // previous value in one outer edge
int length; // length of the edge
// read matrix size and values
printf("Enter the number:\n");
scanf("%d", &n);
printf("Enter the matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &mat[i][j]);
}
}
// loop on the edges
for (u = 0; u < n / 2; u++) { // from outmost edge to inner
i = u; j = u; // index of the north west corner
val = mat[u][u]; // initial value to compare
for (v = 0; v < 4; v++) { // four sides
length = n - u * 2 - 1; // length of the edge
for (w = 0; w < length; w++) {
i += ii[v]; // one step ahead on the edge
j += jj[v]; // same as above
if (mat[i][j] != val || (u > 0 && mat[i][j] <= prev)) {
// if u == 0, skip the comparison with prev
printf("No at [%d][%d] (val=%d)\n", i, j, mat[i][j]);
return 1;
}
}
}
prev = mat[i][j];
}
// finally examine the center value (if n is odd number)
if (n % 2) {
if (mat[u][u] <= prev) {
printf("No at [%d][%d] (val=%d)\n", u, u, mat[u][u]);
return 1;
}
}
printf("Yes\n");
return 0;
}
The basic concept is to generate a series of indexes of the edge
such as:
[0, 1], [0, 2], [0, 3], [0, 4],
[1, 4], [2, 4], [3, 4], [4, 4],
[4, 3], [4, 2], [4, 1], [4, 0],
[3, 0], [2, 0], [1, 0], [0, 0]
by using the variables i, j and the arrays ii[], jj[].
The example above is the indexes for the outermost edge and go into
the inner edge in the next iteration. Then the values of the index
is compared with the other value in the same edge and the previous
value in the outer edge.
[Edit]
Here is an alternative which does not use an array other than mat[100][100]:
#include <stdio.h>
int main() {
int mat[100][100];
int i, j;
int ii, jj; // incremental values for i and j
int n;
int u, v, w; // variables to walk on edges
int val; // value of the element
int prev; // previous value in one outer edge
int length; // length of the edge
// read matrix size and values
printf("Enter the number:\n");
scanf("%d", &n);
printf("Enter the matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &mat[i][j]);
}
}
// loop on the edges
for (u = 0; u < n / 2; u++) { // from outmost edge to inner
i = u; j = u; // index of the north west corner
val = mat[u][u]; // initial value to compare
for (v = 0; v < 4; v++) { // four sides
ii = (v & 1) * ((v & 1) - (v & 2));
// assigned to {0, 1, 0, -1} in order
jj = ((v + 1) & 1) * (((v + 1) & 1) - ((v + 1) & 2));
// assigned to {1, 0, -1, 0} in order
length = n - u * 2 - 1; // length of the edge
for (w = 0; w < length; w++) {
i += ii; // one step ahead on the edge
j += jj; // same as above
if (mat[i][j] != val || (u > 0 && mat[i][j] <= prev)) {
// if u == 0, skip the comparison with prev
printf("No at [%d][%d] (val=%d)\n", i, j, mat[i][j]);
return 1;
}
}
}
prev = mat[i][j];
}
// finally examine the center value (if n is odd number)
if (n % 2) {
if (mat[u][u] <= prev) {
printf("No at [%d][%d] (val=%d)\n", u, u, mat[u][u]);
return 1;
}
}
printf("Yes\n");
return 0;
}
I created an answer using more functions than just main(). It is more verbose than what is required for your homework — it prints out the matrix it reads and diagnoses the first problem it comes across. It works with both positive and negative numbers, and with matrices with odd or even numbers of elements.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
enum { MAT_SIZE = 100 };
static int err_error(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
exit(EXIT_FAILURE);
}
static int err_shell(int r, int c, int a_val, int e_val)
{
printf("Element M[%d][%d] = %d vs expected value %d\n", r, c, a_val, e_val);
return 0;
}
static int check_shell(int shell, int n, int matrix[MAT_SIZE][MAT_SIZE])
{
int lb = shell;
int ub = n - shell - 1;
int val = matrix[lb][lb];
/* Check the horizontals */
for (int c = lb; c <= ub; c++)
{
if (matrix[lb][c] != val)
return err_shell(lb, c, matrix[lb][c], val);
if (matrix[ub][c] != val)
return err_shell(ub, c, matrix[ub][c], val);
}
/* Check the verticals */
for (int r = lb; r <= ub; r++)
{
if (matrix[r][lb] != val)
return err_shell(r, lb, matrix[r][lb], val);
if (matrix[r][ub] != val)
return err_shell(r, ub, matrix[r][ub], val);
}
return 1;
}
static int check_matrix(int n, int matrix[MAT_SIZE][MAT_SIZE])
{
for (int i = 0; i <= n / 2; i++)
{
if (check_shell(i, n, matrix) == 0)
return 0;
}
for (int i = 0; i < (n - 1) / 2; i++)
{
if (matrix[i][i] >= matrix[i+1][i+1])
{
printf("Shell %d has value %d but inner shell %d has value %d\n",
i, matrix[i][i], i+1, matrix[i+1][i+1]);
return 0;
}
}
return 1;
}
static int read_size(void)
{
int n;
if (scanf("%d", &n) != 1)
err_error("failed to read an integer\n");
if (n <= 0 || n > MAT_SIZE)
err_error("matrix size %d is not in the range 1..%d\n", n, MAT_SIZE);
return n;
}
static void read_matrix(int n, int matrix[n][n])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (scanf("%d", &matrix[i][j]) != 1)
err_error("failed to read M[%d][%d]\n", i, j);
}
}
}
static int max_field_width(int n, int matrix[MAT_SIZE][MAT_SIZE])
{
int min_val = matrix[0][0];
int max_val = matrix[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i][j] < min_val)
min_val = matrix[i][j];
if (matrix[i][j] > max_val)
max_val = matrix[i][j];
}
}
int fld_width = snprintf(0, 0, "%d", max_val);
if (min_val < 0)
{
int min_width = snprintf(0, 0, "%d", min_val);
if (min_width > fld_width)
fld_width = min_width;
}
return fld_width;
}
static void print_matrix(const char *tag, int n, int matrix[MAT_SIZE][MAT_SIZE])
{
printf("%s (%d):\n", tag, n);
int w = max_field_width(n, matrix) + 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("%*d", w, matrix[i][j]);
}
putchar('\n');
}
}
int main(void)
{
int matrix[MAT_SIZE][MAT_SIZE];
int n = read_size();
read_matrix(n, matrix);
print_matrix("Input", n, matrix);
if (check_matrix(n, matrix))
printf("YES: Matrix is a valid concentric matrix\n");
else
printf("NO: Matrix is not a valid concentric matrix\n");
return 0;
}
One detail is that this code can be made to use a VLA (variable-length array) by simply replacing MAT_SIZE by n in each function definition and modifying main() to read:
static int check_shell(int shell, int n, int matrix[n][n]) { … }
static int check_matrix(int n, int matrix[n][n]) { … }
static void read_matrix(int n, int matrix[n][n]) { … }
static int max_field_width(int n, int matrix[n][n]) { … }
static void print_matrix(const char *tag, int n, int matrix[n][n]) { … }
int main(void)
{
int n = read_size();
int matrix[n][n];
read_matrix(n, matrix);
print_matrix("Input", n, matrix);
if (check_matrix(n, matrix))
printf("YES: Matrix is a valid concentric matrix\n");
else
printf("NO: Matrix is not a valid concentric matrix\n");
return 0;
}
This reads the matrix size before allocating the matrix, instead of allocating a fixed size matrix first.
The read_size() function enables this change — that input must be done separately from the main matrix scanning code.

Split array into two arrays by index even or odd in c

How to separate the even position number of an array from the odd position number in C.
Example
int arr[]= {2,3,4,5,6,7,8,9,1};
int odd[]= {2,4,6,8,1};
int even[] = {3,5,7,9};
Use % to get the remainder. If the remainder is nonzero, then the index is odd, otherwise even. But index starts from 0 and not 1, thus the first element's index is 0 and is even. if you want to sort according to that (seems to be you do), add 1 to index.
#include <stdio.h>
int main() {
int arr[] = {2, 3, 4, 5, 6, 7, 8, 9, 1}; // our array
const size_t max_size = sizeof(arr) / sizeof(arr[0]);
int odd[max_size];
size_t odd_cnt = 0;
int even[max_size];
size_t even_cnt = 0;
for (size_t i = 0; i != max_size; ++i) {
if ((i + 1) % 2) { // if (i + 1) % 2 is nonzero, i + 1 is odd
odd[odd_cnt++] = arr[i];
} else {
even[even_cnt++] = arr[i];
}
}
for (size_t i = 0; i != odd_cnt; ++i) {
printf("%d ", odd[i]);
}
printf("\n");
for (size_t i = 0; i != even_cnt; ++i) {
printf("%d ", even[i]);
}
printf("\n");
return 0;
}

How can I make a new array, by counting the no.of appearances of value and printing it next to that value?

I should make new array out of existing one (ex. 1 0 4 5 4 3 1) so that the new one contains digits already in existing array and the number of their appearances.
So, the new one would look like this: 1 2 0 1 4 2 5 1 3 1 (1 appears 2 times, 0 appears 1 time.... 3 appears 1 time; the order in which they appear in first array should be kept in new one also); I know how to count no. of times a value appears in an array, but how do I insert the no.of appearances? (C language)
#include <stdio.h>
#define max 100
int main() {
int b, n, s, i, a[max], j, k;
printf("Enter the number of array elements:\n");
scanf("%d", &n);
if ((n > max) || (n <= 0)) exit();
printf("Enter the array:\n");
for (i = 0; i < n; i++)
scanf("%d", a[i]);
for (i = 0; i < n; i++) {
for (j = i + 1; j < n;) {
if (a[j] == a[i]) {
for (k = j; k < n; k++) {
a[k] = a[k + 1];
}}}}
//in the last 5 rows i've tried to compare elements, and if they are same, to increment the counter, and I've stopped here since I realised I don't know how to do that for every digit/integer that appears in array//
If you know that the existing array consists of digits between 0 and 9, then you can use the index of the array to indicate the value that you are incrementing.
int in[12] = {1,5,2,5,6,5,3,2,1,5,6,3};
int out[10] = {0,0,0,0,0,0,0,0,0,0};
for (int i = 0; i < 12; ++i)
{
++out[ in[i] ];
}
If you provide any code snippet, its easy for the community to help you.
Try this, even you optimize the no.of loops :)
#include <stdio.h>
void func(int in[], int in_length, int *out[], int *out_length) {
int temp[10] = {0}, i = 0, j = 0, value;
//scan the input
for(i=0; i< in_length; ++i) {
value = in[i];
if(value >= 0 && value <= 9) { //hope all the values are single digits
temp[value]++;
}
}
// Find no.of unique digits
int unique_digits = 0;
for(i = 0; i < 10; ++i) {
if(temp[i] > 0)
unique_digits++;
}
// Allocate memory for output
*out_length = 2 * unique_digits ;
printf("digits: %d out_length: %d \n",unique_digits, *out_length );
*out = malloc(2 * unique_digits * sizeof(int));
//Fill the output
for(i = 0, j = 0; i<in_length && j < *out_length; ++i) {
//printf("\n i:%d, j:%d val:%d cout:%d ", i, j, in[i], temp[in[i]] );
if(temp[in[i]] > 0 ) {
(*out)[j] = in[i];
(*out)[j+1] = temp[in[i]];
temp[in[i]] = 0; //Reset the occurrences of this digit, as we already pushed this digit into output
j += 2;
}
}
}
int main(void) {
int input[100] = {1, 0, 4, 5, 4, 3, 1};
int *output = NULL, output_length = 0, i = 0;
func(input, 7, &output, &output_length );
for(i=0; i < output_length; i+=2) {
printf("\n %d : %d ", output[i], output[i+1]);
}
return 0;
}

Count how often an int from an array appears in another array in C

I'm trying to solve an exercise that wants me to first create 2 arrays, sort them in ascending order and then count how many times a number from the first array appears in the second array. I'm almost finished. Everything seems to work perfectly fine except for one line that ruins the whole code. And I can't figure out why. I'm very new to C this is my very first exercise in this language.
Here's the code. I have commented the line that is not working:
#include <stdio.h>
void sort(int a[]) {
int i, j, l, t;
l = sizeof(a) / sizeof(a[0]);
for (i = 0; i < l + 1; i++) {
for (j = 0; j < (l - i); j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}
void numberOfTimes(int a[], int b[]) {
int al = sizeof(a) / sizeof(a[0]);
int bl = sizeof(b) / sizeof(b[0]);
int i, p, c = 0;
for (i = 0; i <= al; i++) {
for (p = 0; i <= bl; p++) {
if (a[i] == b[p]) {
c++; // <-------- This line doesn't work. Why?
}
}
printf("(%d, %d) ", a[i], c);
}
}
void main() {
int maxarraylen = 1000, i;
int a[maxarraylen];
int b[maxarraylen];
int v, t;
printf("Type elements of A seperated by spaces. Do not enter duplicates (type 'end' to stop): ");
while (scanf("%d", &a[i]) == 1)
i++;
scanf("%*s");
i = 0;
printf("Type elements of B seperated by spaces(type 'end' to stop): ");
while (scanf("%d", &b[i]) == 1)
i++;
scanf("%*s");
sort(a);
sort(b);
numberOfTimes(a, b);
}
The idea is that the code will first sort both arrays and then print it out in the format (n, m). n is an int from array a and m is how many times it appears in array b.
For example you enter this:
a = {3, 2 ,1}
b = {1, 3, 2, 3, 3, 2, 1}
And the code does first sort:
a = {1, 2, 3}
b = {1, 1, 2, 2, 3, 3, 3}
And then prints out how many times a number from an array a appears in b:
(1, 2) (2, 2) (3, 3)
You cannot compute the array size from a pointer received as an argument: l = sizeof(a)/sizeof(a[0]); only works if a is an array, not a pointer.
You must pass the array sizes to functions sort and numberOfTimes. In your code, the array size is not what you need, but the number of elements actually parsed for each array. You must store these numbers specifically.
Note that your sorting code is incorrect, you should not adjust j's upper bound to avoid accessing array elements beyond the end. The same is true for the numberOfTimes function. The count c must be set to 0 for each new element of a that you search in b.
Note that your code does not take advantage of the fact that a and b are sorted.
Here is a corrected version:
#include <stdio.h>
void sort(int a[], int l) {
int i, j, t;
for (i = 0; i < l; i++) {
for (j = 0; j < l - i - 1; j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}
void numberOfTimes(int a[], int al, int b[], int bl) {
int i, p, c;
for (i = 0; i < al; i++) {
c = 0;
for (p = 0; p < bl; p++) {
if (a[i] == b[p]) {
c++; // <-------- This line doesn't work. Why?
}
}
printf("(%d, %d) ", a[i], c);
}
}
int main(void) {
int maxarraylen = 1000, i;
int a[maxarraylen];
int b[maxarraylen];
int al, bl, v, t;
printf("Type elements of A separated by spaces. Do not enter duplicates (type 'end' to stop): ");
for (i = 0; i < maxarraylen; i++) {
if (scanf("%d", &a[i]) != 1)
break;
}
scanf("%*s");
al = i;
printf("Type elements of B separated by spaces(type 'end' to stop): ");
for (i = 0; i < maxarraylen; i++) {
if (scanf("%d", &b[i]) != 1)
break;
}
scanf("%*s");
bl = i;
sort(a, al);
sort(b, bl);
numberOfTimes(a, al, b, bl);
return 0;
}

Resources