Remove unnecessary value entries from multidimensional array in c? - arrays

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;
}

Related

How Do I Make This Print?

I understand how to print the stuff now: I forgot to allocate memory for the array. However, now I can't seem to get the math right in the final result.
Prompt:
A boy goes to buy video games from a shop. The shop contains N unique
video games. The prices of the games are given in the form of an array
A. The price of ith games is A[i]. Now the boy has q queries, in each
query he wants to know the number of unique games that have a price
less than the given amount M. Input:
The first line contains an integer N total number of unique video
games available in the shop.
The second line contains N space-separated integers (the price of the
games).
The third line contains Q number of queries.
Each of the next Q lines contains integer M. Output:
For each query output number of games having price less than M for
that query. Sample Input:
5
1 4 10 5 6
4
2
3
5
11
Output for the sample input:
1
1
2
5
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *Prices, UniqueGames, j, h, i, numPrice, numQueries, *PriceQueries, *TestResults;
//Making Arrays
printf("Enter number of unique games.");
scanf("%d", &UniqueGames); // Array Size
Prices = (int*)malloc(sizeof(int)*UniqueGames); // Memory Allocation
for(j = 0; j < UniqueGames; j++){ // Filling Array
scanf("%d", &h);
*(Prices+j) = h;
}
printf("Enter number of queries.");
scanf("%d", &numQueries); // Array Size
PriceQueries = (int*)malloc(sizeof(int)*numQueries); // Memory Allocation
for(j = 0; j < numQueries; j++){ // Filling Array
scanf("%d", &h);
*(PriceQueries+j) = h;
}
//Calculations
TestResults = (int*)malloc(sizeof(int)*numQueries);
h = 0;
for(j = 0; j < numQueries; j++){ // Filling array TestResults with test results
for (i = 0; i < UniqueGames; i++) {
if (Prices[i] < PriceQueries[i]) {
h = h + 1;
TestResults[j] = h;
}
else {
h = 0;
}
}
printf("%d\n", TestResults[j]);
}
free(Prices);
free(PriceQueries);
free(TestResults);
return 0;
}
I'm filling an array of prices for each game and an array of prices for the number of queries the user inputs. I fill an array of test results based on the prices within the query set and I'm trying to print that final array.
Your 'calculations' are needless complex making it difficult to understand. (And the wonky indentation does not help.)
//Calculations
TestResults = (int*)malloc(sizeof(int)*numQueries); // <== uninitialised array
h = 0;
for(j = 0; j < numQueries; j++){ // Filling array TestResults with test results
for (i = 0; i < UniqueGames; i++) {
if (Prices[i] < PriceQueries[i]) { // <= one index should be 'j'
h = h + 1;
TestResults[j] = h; // <== assignment should be accumulation
}
else {
h = 0; // <== why reset???
}
}
printf("%d\n", TestResults[j]); // <== why use an array???
}
Rewriting (with comments) may help clarify what you seem to want to achieve
//Calculations
for( j = 0; j < numQueries; j++ ) { // for each query amount...
int cnt = 0; // count the games...
for( i = 0; i < UniqueGames; i++ ) // for each game
if( Prices[ i ] < PriceQueries[ j ] ) // priced less than this query amount
cnt++;
printf( "Query %d: %d games cost less than %d\n", j, cnt, PriceQueries[ j ] );
}

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

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.

Trying to find smallest array elements from 2 arrays returns 0 (doesn't work) and the other works. (C lang)

I'm trying to accomplish a simple task in C which is to print out the smallest number from array 1 and smallest number from array 2. Both array elements are imputed by the user.
First one just returns 0 (which in my testing case its supposed to be 1) and the other one returns the correct one (11). I seriously can't understand why and I also tried to google this with no result so that's when I once again decided to seek help here!
int main () {
int masyvas1[10] = {0};
int masyvas2[10] = {0};
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk pirmo masyvo 10 sk: ");
scanf("%d", &x);
masyvas1[i] = x;
}
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk antro masyvo 10 sk: ");
scanf("%d", &x);
masyvas2[i] = x;
}
int mas1maz[2] = {0, 0};
for(int i = 0; i < 10; i++){
if(masyvas1[i] < mas1maz[1]){
mas1maz[1] = masyvas1[i];
}
if(masyvas2[i] < mas1maz[2]){
mas1maz[2] = masyvas2[i];
}
}
printf("testas: %d %d", mas1maz[1], mas1maz[2]);
}
If I enter numbers say from 1 to 10 for the first array and 11 to 20 for the second the program output is: testas: 0 11 which I was expecting it to be testas: 1 11
Thank you in advance!
I would like you to go over your program by trying what is below
int mas1maz[2] = {0, 0};
The Array has 2 elements, try to print each element.
Note: there are only 2 elements but I am printing 3 as you have used mas1maz[2] ( this is grabage= 11)
printf("%d,%d,%d",mas1maz[0],mas1maz[1],mas1maz[2]);
Then you are trying to compare with mas1maz[1]=0, this will result in a minimum always equal to zero.
for(int i = 0; i < 10; i++) {
/*
*/
if(masyvas1[i] < mas1maz[1]) {
mas1maz[1] = masyvas1[i];
}
Here you are tyring to compare mas1maz[2] with garbage=11, this is the reason why you see 11.
if(masyvas2[i] < mas1maz[2]) {
mas1maz[2] = masyvas2[i];
}
What you should try is the following :
for(int i = 0; i<9; i++) {
if(masyvas1[i]>masyvas1[i+1])
{
/*copy to your array*/
mas1maz[0]=masyvas1[i]
}
/* similarly for masyvas2*/
}
see that for an array of length len, indices of the array ranges from 0 to len-1
if(masyvas2[i] < masyvas2[i]){
mas1maz[2] = masyvas2[i];
}
Change your second if as follow. You was checking for smaller number in masmaz1 array and was passing 2 in array parameters which is not compatible. As you have initialized an array for 2 locations 0 and 1 as array locations are started from 0. So change that Second if to compare it with itself for smallest number.
int min;
int max;
int i;
min=max=mas1maz[0];
for(i=1; i<10; i++)
{
if(min>mas1maz[i])
min=mas1maz[i];
}
You should use this after you fill your tables with scanf to find the minimum value
then compare the two different minimums

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);

Reading an array of integers and printing them out

I'm learning C on my own and doing a few exercises. The following code reads in an
array of integers from the user. The integers are printed out when the user types in a "0" or when the array is filled. Now the problem is the output. When I type in "0" after I have typed in 3 digits e.g. 1 2 3 the output is the following: 1 2 3 -858993460 -858993460. I am not sure why I get the value "-858993460" but I have already found a solution to avoid it. Now my question is what the values mean and if there is a smarter solution than mine which is presented below as comments.
#include <stdio.h>
#include <string.h>
#define arraylength 5
int main ()
{
//const int arraylength = 21; //alternative possibility to declare a constant
int input [arraylength] ;
int temp = 0;
//int imax = 0;
printf("Please type in a your digits: ");
for (int i = 0; i < arraylength; i++)
{
scanf("%d", &temp);
if ( temp !=0)
{
input[i]= temp;
//imax= i;
}
else
{
//imax= i;
break;
}
if (i < arraylength-1)
printf("Next: ");
}
for (int i =0; i < arraylength; i++ ) // switch arraylength with imax
{
printf("%d", input[i]);
}
getchar();
getchar();
getchar();
}
This happens because irrespective of when the 0 input is given you print all 5 numbers:
for (int i =0; i < arraylength; i++ )
To fix this you can print only the number(s) user entered before entering a 0 by running a loop from 0 to i:
for (int j =0; j < i; j++ )
Those 2 numbers are the garbage that was left in the memory locations for the last 2 parts of your array. You never initialise those when you only input 3 numbers, so when you go through and print all 5 elements in the array, it prints whatever garbage was in the memory.
You print all integers in array which is size of arraylength = 5. So you get 5 integers in output. As you didn't initialize array, you get uninitilized values as 4th and 5th elements of array. You can use memset(&input, 0, arraylength*sizeof(int)); to set initials values in array to 0.

Resources