My code doesn't run the same way on different compilers - arrays

first of all, I'm just starting to learn C programming on my own so please don't be mad if I'm explaining or doing something wrong, I tried to search similar question to my problem on StackOverflow but I couldn’t find one so please if I'm doing something wrong, take it easy on me I'm only trying to learn.
I have an issue I can't understand, I wrote a sorting list program using the Insertion sort algorithm, that runs differently on different compilers.
when I enter only positive numbers everything works smoothly but if I add some negatives numbers, depending on the compiler, it sometimes works and sometimes does not work at all/ prints a weird result
#include <stdio.h>
#include <string.h>
int main()
{
// gathering sources for sorting an array:
int myArray[5];
int count = 1;
for (int arrayIndex = 0; arrayIndex < 5; arrayIndex++)
{
printf("\nEnter the #%d array element: ", count);
scanf(" %d", &myArray[arrayIndex]);
count++;
}
// calculate the last array index
int myInt = myArray[0];
int arrayLength = ((sizeof(myArray)) / (sizeof(myInt))) - 1;
// printing the unsorted array
printf("\nthe array was: ");
for (int i = 0; i <= arrayLength; i++)
{
printf(" %d ", myArray[i]);
}
// sorting the array using insertion sorting algorithm:
for (int index = 1; index <= arrayLength; index++)
{
int numberCheck = index;
while (index >= 1 && myArray[numberCheck] < myArray[numberCheck - 1])
{
// swap the places:
int temp;
temp = myArray[numberCheck];
myArray[numberCheck] = myArray[numberCheck - 1];
myArray[numberCheck - 1] = temp;
// move the next element
numberCheck--;
}
}
// printing the sorted array:
printf("\nthe sorted array is now: ");
for (int i = 0; i <= arrayLength; i++)
{
printf(" %d ", myArray[i]);
}
return 0;
}
for example if I enter (0,-2,-4,12,5)
on C Online Compiler - Programiz
I get this result :
the array was: 0 -2 -4 12 5
the sorted array is now: -4 -2 0 5 12
but if I enter the same exact code on the Vscode Zsh compiler (I'm using a MacBook and to my knowledge, I didn't change anything on the compiler settings)
I get the result :
the array was: 0 -2 -4 12 5
the sorted array is now: 5 6

I tested out your code and found a few areas where processing of array elements was going out of bounds. Some places, the value of the index was -1 and some places the value was equal to the array length value (e.g. index values that equate to myArray[5] which again is out of bounds).
Following is a copy of your code with a bit of cleanup to illustrate some usual and customary methods for processing "for" loops and processing arrays.
#include <stdio.h>
#include <string.h>
int main()
{
// gathering sources for sorting an array:
int myArray[5];
int count = 1;
for (int arrayIndex = 0; arrayIndex < 5; arrayIndex++)
{
printf("\nEnter the #%d array element: ", count);
scanf(" %d", &myArray[arrayIndex]);
count++;
}
// calculate the last array index
int myInt = myArray[0];
int arrayLength = ((sizeof(myArray)) / (sizeof(myInt))); /* Omittted the subtraction of 1 */
// printing the unsorted array
printf("\nthe array was: ");
for (int i = 0; i < arrayLength; i++) /* Set loop test to be less than array length */
{
printf(" %d ", myArray[i]);
}
// sorting the array using insertion sorting algorithm:
for (int index = 1; index < arrayLength; index++)
{
int numberCheck = index;
//while (index >= 1 && myArray[numberCheck] < myArray[numberCheck - 1]) /* This line of code was allowing numberCheck - 1 to be less than zero */
while (numberCheck > 0 && myArray[numberCheck] < myArray[numberCheck - 1]) /* Revised version of the test */
{
// swap the places:
int temp;
temp = myArray[numberCheck];
myArray[numberCheck] = myArray[numberCheck - 1];
myArray[numberCheck - 1] = temp;
// move the next element
numberCheck--;
}
}
// printing the sorted array:
printf("\nthe sorted array is now: ");
for (int i = 0; i < arrayLength; i++) /* Revised this to not go out of bounds */
{
printf(" %d ", myArray[i]);
}
printf("\n");
return 0;
}
It appears in the program that you are attempting set up for loop and range testing based on a range of "1" to "array length"; whereas, the usual range processing is from "0" to "less than array length". When I did those bits of cleanup, I was able to acquire a properly sorted array from the five values entered.
#Una:~/C_Programs/Console/Sorting/bin/Release$ ./Sorting
Enter the #1 array element: 700
Enter the #2 array element: 343
Enter the #3 array element: 2
Enter the #4 array element: 58
Enter the #5 array element: 400
Array length: 5
the array was: 700 343 2 58 400
the sorted array is now: 2 58 343 400 700
Note the comments I added to hopefully clarify bits for you. Try that out and see if it meets the spirit of your project.

Related

function that returns the sum of the longest arithmetic sequence(without using arrays)

So I have this problem I'm trying to solve for a couple of days now, and I just feel lost.
The function basically needs to get the size(n) of a sequence.
The user inputs the size, and then the function will ask him to put the numbers of the sequence one after the other.
Once he puts all the numbers, the function needs to return the sum of the longest sequence.
For example, n=8, and the user put [1,3,5,7,11,13,15,16].
The result will be 16 because [1,3,5,7] is the longest sequence.
If n=8 and the user put [1,3,5,7,11,15,19,20], the result will be 52, because although there are 2 sequences with the length of 4, the sum of [7,11,15,19] is bigger then [1,3,5,7].
The sequence doesn't necessarily needs to be increasing, it can be decreasing too.
The function can't be recursive, and arrays can't be used.
I hope it's clear enough what the problem is, and if not, please let me know so I'll try to explain better.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int i, size, num, nextNum, diff, prevDiff, currSeqLength = 0, currSum, prevSum = 0;
printf("Please enter the arithmetic list size: ");
scanf_s("%d", &size);
for (i = 1; i <= size; i++)
{
printf("Please enter num: ");
scanf_s("%d", &num);
while (i == 1)
{
prevSum = num;
nextNum = num;
currSeqLength++;
break;
}
while (i == 2)
{
currSum = prevSum + num;
diff = num - nextNum;
nextNum = num;
currSeqLength++;
break;
}
while (i >= 3)
{
prevDiff = diff;
diff = num - nextNum;
nextNum = num;
if (prevDiff == diff)
{
currSum += num;
currSeqLength++;
break;
}
else
{
prevDiff = diff;
// diff now should be the latest num - previous one
}
}
}
}
This is basically what I've managed so far. I know some things here aren't working as intended, and I know the code is only half complete, but I've tried so many things and I can't seem to put my finger on what's the problem, and would really love some guidance, I'm really lost.
A few problems I encountered.
When I enter a loop in which the difference between the new number and the old one is different than the previous loops(for instance, [4,8,11]), I can't seem to manage to save the old number(in this case 8) to calculate the next difference(which is 3). Not to mention the first 2 while loops are probably not efficient and can be merged together.
P.S I know that the code is not a function, but I wrote it this way so I can keep track on each step, and once the code works as intended I convert it into a function.
I tried out your code, but as noted in the comments, needed to keep track at various stages in the sequence checks which sequence had the longest consistent difference value. With that I added in some additional arrays to perform that function. Following is a prototype of how that might be accomplished.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int len, diff, longest;
printf("Enter the size of your sequence: ");
scanf("%d", &len);
int num[len], seq[len], sum[len];
for (int i = 0; i < len; i++)
{
printf("Enter value #%d: ", i + 1);
scanf("%d", &num[i]);
seq[i] = 0; /* Initialize these arrays as the values are entered */
sum[i] = 0;
}
for (int i = 0; i < len - 1; i++)
{
seq[i] = 1; /* The sequence length will always start at "1" */
sum[i] = num[i];
diff = num[i + 1] - num[i];
for (int j = i; j < len - 1; j++)
{
if (diff == num[j + 1] - num[j])
{
sum[i] += num[j + 1]; /* Accumulate the sum for this sequence */
seq[i] += 1; /* Increment the sequence length for this sequence portion */
}
else
{
break;
}
}
}
longest = 0; /* Now, determine which point in the lise of numbers has the longest sequence and sum total */
for (int i = 1; i < len; i++)
{
if ((seq[i] > seq[longest]) || ((seq[i] == seq[longest]) && (sum[i] > sum[longest])))
{
longest = i;
}
}
printf("The sequence with the longest sequence and largest sum is: [%d ", num[longest]);
diff = num[longest + 1] - num[longest];
for (int i = longest + 1; i < len; i++)
{
if ((num[i] - num[i - 1]) == diff)
{
printf("%d ", num[i]);
}
else
{
break;
}
}
printf("]\n");
return 0;
}
Some points to note.
Additional arrays are defined to track sequence length and sequence summary values.
A brute force method is utilized reading through the entered value list starting with the first value to determine its longest sequence length and continuing on to the sequence starting with the second value in the list and continuing on through the list.
Once all possible starting points are evaluated for length and total, a check is then made for the starting point that has the longest sequence or the longest sequence and largest sum value.
Following is a some sample terminal output utilizing the list values in your initial query.
#Dev:~/C_Programs/Console/Longest/bin/Release$ ./Longest
Enter the size of your sequence: 8
Enter value #1: 1
Enter value #2: 3
Enter value #3: 5
Enter value #4: 7
Enter value #5: 11
Enter value #6: 13
Enter value #7: 15
Enter value #8: 16
The sequence with the longest sequence and largest sum is: [1 3 5 7 ]
#Dev:~/C_Programs/Console/Longest/bin/Release$ ./Longest
Enter the size of your sequence: 8
Enter value #1: 1
Enter value #2: 3
Enter value #3: 5
Enter value #4: 7
Enter value #5: 11
Enter value #6: 15
Enter value #7: 19
Enter value #8: 20
The sequence with the longest sequence and largest sum is: [7 11 15 19 ]
No doubt this code snippet could use some polish, but give it a try and see if it meets the spirit of your project.
I know code-only answers are frowned upon, but this is the simplest I can come up with and its logic seems easy to follow:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int i, size;
int currNum, currDiff;
int prevNum = 0, prevDiff = 0;
int currSum = 0, currSeqLen = 0;
int bestSum = 0, bestSeqLen = 0;
printf("Please enter the arithmetic list size: ");
scanf_s("%d", &size);
for (i = 0; i < size; i++)
{
printf("Please enter num: ");
scanf_s("%d", &currNum);
if (currSeqLen > 0)
{
currDiff = currNum - prevNum;
if (currSeqLen > 1 && currDiff != prevDiff)
{
/* New arithmetic sequence. */
currSeqLen = 1;
currSum = prevNum;
}
prevDiff = currDiff;
}
currSum += currNum;
prevNum = currNum;
currSeqLen++;
if (currSeqLen > bestSeqLen ||
currSeqLen == bestSeqLen && currSum > bestSum)
{
/* This is the best sequence so far. */
bestSeqLen = currSeqLen;
bestSum = currSum;
}
}
printf("\nbest sequence length=%d, sum=%d\n", bestSeqLen, bestSum);
return 0;
}
I have omitted error checking for the scanf_s calls. They can be changed to scanf for non-Windows platforms.

Find the index of the largest element in an array and find elements N indexes to the right and left of that max element

I am writing some c coding involving some array manipulation.
I am trying to achieve the following:
With a given input array, create a new_array consisting of only the first 10 elements
Find the index_of_largest element in the new_array
Take the 2 elements to the left of index_of_largest and 3 to the right and put them all in a new_array2
For example if array[15] = {12,25,99,56,44,79,62,11,10,2,1,3,4,5,6}
then new_array[10] = {12,25,99,56,44,79,62,11,10,2}
then new_array2 [6]={12,25,99,56,44,79}
This is my current code:
#include<stdio.h>
int main()
{
int a[15]={12,25,99,56,44,79,62,11,10,2,1,3,4,5,6}, arr1[10], arr2[5], i, pos=10, k1 = 0, k2 = 0, max_index, max;
for(i = 0; i < 10; i++)
{
if(i < pos)
arr1[k1++] = a[i]; //seperate array
else
arr2[k2++] = a[i];
}
printf("\nElements of First Array -> arr1[%d]\n", k1);
for(i = 0; i < k1; i++)
printf("%d\n", arr1[i]);
max = arr1[0]; //find index of max element
for (i = 0; i < 10; i++)
{
if (arr1[i] > max) {
max = arr1[i];
max_index = i;
}
}
printf("Largest element = %d at index %d", max, max_index);
return 0;
}
output:
Elements of First Array -> arr1[10]
12
25
99
56
44
79
62
11
10
2
Largest element = 99 at index 2
I am able to separate the initial array (1) am able to find the index of the largest element (2). I am not sure how to solve (3) moving forward from my current point.
The largest index will always been in a position in the array so that it will be possible to get the elements to around it. (For example the largest value will not be the first or last index)
I also think I should add a condition so that if there are multiple max values, we take the first one that occurs.
I will in the future wrap all this in a function call but sorry for the messy code at the moment.
You're using %f format specifier, this is for floats and doubles. max is an int, you need to use %d or similar:
printf("Largest element = %d at index %d", max, max_index);
For more information on printf format specifiers, see the man page

Remove unnecessary value entries from multidimensional array in c?

Hi I am working with a scenario where user input multiple contiguous arrays of different lengths and I want to store these array for further use.
I am using multidimensional array for this purpose.
Here is the code :
#include <stdio.h>
int main()
{
int rows,cols;
printf("Enter the number of user input arrays ? ");
scanf("%d",&rows);
printf("Enter the maximum number of inputs in a single array ?"); //Need to remove these lines
scanf("%d", &cols); //Need to remove these lines if possible
int array[rows][cols];
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
array[i][j]=0;
}
}
for(int i=0;i<rows;i++)
{
int count;
printf("Enter the number of inputs for array %d - ", i);
scanf("%d",&count);
for(int j=0;j<count;j++)
{
scanf("%d",&array[i][j]);
}
}
//// Use array for other purpose
////printf("\n\nArray --> \n");
////for(int i=0;i<rows;i++)
////{
////for(int j=0;j<cols;j++)
////{
////printf("%d ",array[i][j]);
////}
////printf("\n");
////}
return 0;
}
Example input :
Enter the number of user input arrays ? 5
Enter the maximum number of inputs in a single array ?5
Enter the number of inputs for array 0 - 5
1 2 6 3 5
Enter the number of inputs for array 1 - 1
3
Enter the number of inputs for array 2 - 2
6 5
Enter the number of inputs for array 3 - 1
3
Enter the number of inputs for array 4 - 1
9
Array created in this case :
1 2 6 3 5
3 0 0 0 0
6 5 0 0 0
3 0 0 0 0
9 0 0 0 0
Now I have number of issues in this case :
I want to reduce the space being used by removing the unnecessary entries in the array.
I would not like to use '0' or any other integer to define an unnecessary entry as it is a valid input.
I would like to remove the line
printf("Enter the maximum number of inputs in a single array ?");
scanf("%d", &cols);
Can anyone provide me help to overcome these issues.
From the design criteria you have described:
Array with user determined number of rows.
Rows have differing lengths, also user determined.
Reduce the space being used. (space only for real inputs, no padding, or filler values.)
Array definition is created at run-time per user inputs, but is not required to change during same run-time session.
Note: One design criteria: //Need to remove these lines if possible is not included in this solution. Without a description of the desired method to instruct user, I do not know how to improve on the the user prompt method.
Jagged arrays may be what you are looking for. Following is a simple example directly from the link that incorporates dynamic memory allocation that can be adapted to the code you have already discussed:
int main()
{
int rows;
//Place you user input prompts and scans here
// User input number of Rows
int* jagged[2];//
// Allocate memory for elements in row 0
jagged[0] = malloc(sizeof(int) * 1);
// Allocate memory for elements in row 1
jagged[1] = malloc(sizeof(int) * 3);
// Array to hold the size of each row
int Size[2] = { 1, 3 }, k = 0, number = 100;
// User enters the numbers
for (int i = 0; i < 2; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[k]; j++) {
*p = number++;
// move the pointer
p++;
}
k++;
}
k = 0;
// Display elements in Jagged array
for (int i = 0; i < 2; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[k]; j++) {
printf("%d ", *p);
// move the pointer to the next element
p++;
}
printf("\n");
k++;
// move the pointer to the next row
jagged[i]++;
}
return 0;
}
This is the concept moved a little closer to what I think you want, adapted from the code above to accept user input similar to what your code does...
int main(int argc, char *argv[])
{
int rows = 0;
int cols = 0;
int i, j;
int number = 100;
printf("Enter the number of user input arrays ? ");
scanf("%d",&rows);
// n Rows
int* jagged[rows];
int Size[rows];//array to keep size if each array
for(i=0;i<rows;i++)
{
printf("Enter the maximum number of inputs for array[%d]: ", i);
scanf("%d", &cols); //Need to remove these lines if possible
// Allocate memory for elements in row 0
jagged[i] = malloc(sizeof(jagged[i]) * cols);
Size[i] = cols;//set size of nth array
}
// User enters the numbers (This is spoofed. You will need to code per comment below.
for (i = 0; i < rows; i++) {
int* p = jagged[i];
for (j = 0; j < Size[i]; j++) {
*p = number++; //Note, this is spoofing user input .
//actual user input would be done exactly as above
//with printf prompts and scans for value
// move the pointer
p++;
}
}
// Display elements in Jagged array
for (i = 0; i < rows; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[i]; j++) {
printf("%d ", *p);
// move the pointer to the next element
p++;
}
printf("\n");
// move the pointer to the next row
jagged[i]++;
}
return 0;
}

C: Create randomly-generated integers, store them in array elements, and print number of integers stored in each element

I'm incredibly new to C (and programming in general) and finding how to manipulate arrays is almost impossible to understand (I know what an array is).
I'm attempting to write a program that generates 100 random integers in a range (1-50), stores them in array elements (1-10, 11-20, 21-30, 31-40, and 41-50), and print the number of randomly generated integers stored in each element, i.e.
1-10 = 20
11-20 = 30
21-30 = 21
31-40 = 19
41-50 = 20
The best I can come up with so far is:
void randomNumbers
{
int count[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = rand() % 50 + 1;
}
for (int i = 0; i <= ARRAY_LENGTH - 1; i++)
{
printf("Index %d -> %d\n", i, count[i]);
}
}
That just says "element 1 = random number, element 2 = random number" etc.
I don't understand how to:
Store the randomly-generated integers in the array's elements
Partition the randomly-generated integers into the corresponding
element
Tell the program to print the number of integers generated in each
element range
The following is the code that generates 100 random integers and groups them into categories based on their value :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i, temp;
int a[5]; // array to store the frequency
for(i=0;i<5;i++)
a[i]=0;
srand(time(0)); // for generating new random integers on every run
for(i=0;i<100;i++)
{
temp = (rand()%50) + 1; // generates random integers b/w 1 to 50
a[(temp-1)/10]++;
}
for(i=0;i<5;i++)
printf("%d->%d = %d\n",i*10+1,(i+1)*10,a[i]); //printing in the desired format
return 0;
}

How to count how many times values were used in the array C?

Here's my problem
If certain number has been entered into an array I need that number to be displayed and occurrence of that number in the array.
for example if user enters number 5 three times then "The number 5 has been entered 3 times so far" and so on
Here's my code so far:
int i,j;
int num_count = 0;
for(i=0;i<6;i++) {
num_count = 0;
for(j=1;j<43;j++) {
if( *(num + i) == j) {
printf("The number %d has been used %d times\n",j,num_count);
}//end if
}//end inner for
}//end outer for
I will like to suggest you a very time efficient method for this, but it needs some extra memory.
Assume the upper limit of numbers inside array is 'MAX_NUM_IN_ARRAY',
so you should create array (say counter) of size 'MAX_NUM_IN_ARRAY+1' and initialize it to 0.
int counter[MAX_NUM_IN_ARRAY+1]={0};
now scan the input array from first to last element,
for each number:
//say number is num
counter[num]++;
and at the end you have to just scan that counter array from index 1 to MAX_NUM_IN_ARRAY.
Sample code:
Suppose input array is a[],
number of elements in array is n,
maximum limit of number inside array is MAX_LIMIT
int counter[MAX_LIMIT]={0};
int i;
for(i=0; i<n; i++)
{
counter[a[i]]++;
}
for(i=0; i<MAX_LIMIT; i++)
{
printf("Number %d is appeared for %d times\n", i, counter[i]);
}
============EDIT
You could write a series of functions that handle your collection. the collection could be a 2 dimentional array like so numbers[][] where numbers[n][0] is your number, and numbers[n][1] is the number of times it occurred... and the gold would be in your add() function
add() does a few things, a user passes a value to add(),
first checks if number exists in numbers[n][0]
if the value exists at numbers[n][0]
numbers[n][1]++;
if it doesn't already exist,
check if the array is full
if it is full, copy all the data to a new, larger array
add it to the end of the array.. this is how to do it.
==OR
just design a 1 dimentional array numbers[] that holds all of your numbers.. and the add() function only:
if(it is full){copies to larger array}
adds number to the end;
and modify the code I wrote earlier (Below).. to print the most common number and it's occurrence count
============EDIT
I'm a Java guy so you'll need to translate (shouldn't be too hard..)
This is going to be just like a sorting algorithm with a little bit of extra logic (later search for Selection Sort)
int[] temp = {4,3,2,4,4,5};
////// find the most commonly occuring value
int times;
int moreTimes = 1;
int value = temp[0];
for(int i = 0; i < temp.length; i++) {
times = 1;
for(int j = i+1; j < temp.length; j++) {
if(temp[i] == temp[j])
times++;
}
if(times > moreTimes) {
moreTimes = times;
value = temp[i];
}
}
/////// count the most common value
int count = 0;
for(int i = 0; i < temp.length; i++) {
if(temp[i] == value)
count++;
}
System.out.println("number: " + value + ", count: " + count);

Resources