C : Array, Loop, Min Element Values - c

I'm looking for help with this question:
"Create an array of 10 ints called myArray. Give the array contents an initial value of 0 in the variable declaration. Create a loop to prompt the user and get revised values for all of the array elements, pressing ENTER after each of the 10 items. Within the loop, keep track of which element has the lowest value. After the loop is done, display the minimum element's index and value."
I am a new student. The code I made doesn't work but hoping someone can see the problem or what I'm missing. The getNum variable was made by our teacher for us to use.
I need help being able to output the smallest element with the variable associated with that element.
int main()
{
int getNum(void);
int sizeArray = 10;
int myArray[11] = {0,0,0,0,0,0,0,0,0,0};
int counter = 0;
int smallestNumber =0;
print("Enter 10 Integers:\n");
for (counter = 0; counter < sizeArray; counter++)
{
myArray[sizeArray] = getNum();
}
for (counter = 0; counter < sizeArray; counter++)
{
if(myArray[counter] < smallestNumber) {
smallestNumber = myArray[counter];
}
}
printf("Smallest number is %d, in Element %d. \n", smallestNumber, counter);
return 0;
}
#pragma warning(disable: 4996)
int getNum(void) {
char record[121] = {0};
int number = 0;
fgets(record, 121, stdin);
if( sscanf(record, "%d", &number) != 1){
number = -1;
}
return number;
}

You edited your code so I will provide the main problem with your original code for context.
You initially declared and defined your myArray as follows:
int myArray[] = {0};
As mentioned in the comments, the proper way to accomplish this is with:
int myArray[10] = {0};
Alternatively, you could have done it using a for loop as you attempted to initially with:
for(int i = 0; i < 10; i++)
{
myArray[i] = 0;
}
But, for such a simple task, the first way is much easier.
We shouldn't stop there, however. There are some simple ways to improve your code. Instead of hardcoding the size of the array AND having the sizeArray variable, why not do something like a define statement before your main function:
#define SIZE_ARRAY 10
This will allow you to do some useful things in your code that can be changed MUCH easier in the future:
int myArray[SIZE_ARRAY] = {0};
...
for (int i = 0; i < SIZE_ARRAY; i++) {} //Note also the change to 'int i'
Another thing is the counter variable. It is an additional variable that you don't need. You can just utilize the 'int i' as above in your loop. What if instead of having a counter variable AND a smallestNumber variable, you combine them into a single variable called something like this:
int smallestIdx = 0;
Then, in your for loop you could do something like this:
for(int i = 0; i < SIZE_ARRAY; i++)
{
myArray[i] = getNum();
if (myArray[i] < myArray[smallestIdx]){
smallestIdx = i;
}
}
And because you are only keeping track of the index of the smallest integer in your array, you could print like this:
printf("Smallest number is %d, in Element %d. \n", myArray[smallestIdx], smallestIdx);

Related

How to print the sum of a passing a int array as a parameter

#include <stdio.h>
int sumofArrayNum(int numList[]);
int main(){
int result,numList[]={23,32,54,23,54,32,3,35};
result = sumofArrayNum(numList);
printf("sum= %d", result);
return 0;
}
int sumofArrayNum(int numList[]){
int sum = 0;
for(int i = 0; i < 10; ++i){
sum += numList[i];
}
return sum;
}
Output is different each time I build and run it.
E.g. output is sum = 1032918821
Expected output I would like is sum = 256
Parameters like int numList[] is the same as int* numList, compiler will not know elements count of it if it was not explicitly defined. By the way, int numList[8] is also the same as int* numList. C language does not check the range of array.
There are some ways to get and check the array size.
size/count parameter
int sumofArrayNum(int numList[], int listSize){
int sum = 0;
for(int i = 0; i < listSize; ++i){
sum += numList[i];
}
return sum;
}
Here listSize should be the count of elements.
And you can use macro to hide the count parameter:
#define sumofArray(array) sumofArrayNum((array), sizeof(array)/sizeof(*array))
point to the whole array
int sumofArrayNum(int (*numList)[8]){
int sum = 0;
for(int i = 0; i < sizeof(*numList)/sizeof(**numList); ++i){
sum += (*numList)[i];
}
return sum;
}
Call it by sending pointer of array:
result = sumofArrayNum(&numList);
Compiler(such as gcc) can do a weak check for this: give a warning if you send an array which are not int (*)[8].
Note that you have to ensure validity of array, and array size must be constant.
Besides,
Output is different each time I build and run it.
It is because only 8 elements has been defined, index range is 0〜7. numList[8] and numList[9] is undefined, mean any value is possible. Maybe used, changed by other process, random and dangerous.
In numlist there are 8 element that means for loop must execute code 8 times.
Your code must be:
for(int i = 0; i < 8; ++i)
{
sum += numList[i];
}
This code iterate until i=7, when i=8 it will end the loop.
Information on for loop

Binary search not returning the position

this code is used to create an array filled with 10 random integers. It sorts the array and then inputs the array into a binary search function. I do not get the position of where my search key is positioned.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int binary_search(int array[], int search, int strt, int ending)
{
int middle;
middle = (strt + ending)/2;//splitting the array in half to compare the search key
if (search > array[middle]){binary_search(array, search, middle + 1, ending);}
else if(search == array[middle])
{
printf("Your search key is indicated in %d position the array Ferrari\n", middle + 1);
return middle;
}
else{binary_search(array, search, strt, middle -1);}
return -1;
}
int main()
{
srand(time(NULL));//random number seed generator
int Ferrari[10];
int size = 10;
int selection;
int temporary = 0;//I'm using this variable to store
//the value returned from linear_search()
int start = 0;
int end;
int i;
//this is to generate a random number between 0 and 101
for(int i=0; i<10; i++) {Ferrari[i] = rand() % 100 + 1;}
//printing the initial array
printf("\nThe array Ferrari consists of -> ");
for(int i=0; i<10; i++){printf("%d, ", Ferrari[i]);}
//--------------------------SORTING--------------------------------------------
for(int f = 0; f < (size - 1); f++)
{
for(int kk = 0; kk < (size - 1 - f); kk++)
{
if(Ferrari[kk] > Ferrari[kk +1])
{
int Te_mP;
Te_mP = Ferrari[kk + 1];
Ferrari[kk+1] = Ferrari[kk];
Ferrari[kk] = Te_mP;
}
}
}
//----------------------------------------------------------------------------
//printing the array after it has been sorted
printf("\n");
printf("\nThe sorted array Ferrari consists of -> ");
for(int i=0; i<10; i++){printf("%d, ", Ferrari[i]);}
start = 0;
end = i -1;
//this will be used to implement the searching algorithm
printf("\n\n");
printf("Please enter a number to test if it is included in the array or not\n");
scanf("%d", &selection);
temporary = binary_search(Ferrari, selection, start, end);
return 0;
}
I keep getting the answer that the search key is positioned in ``0 of array Ferrari. How do I resolve this?
Please let me know what I'm doing wrong over here. Much appreciated.
Look at this line
end = i - 1;
Where is i initialized?
In your loop you have
for(int i=0........
Note by giving int i=0 it means you are creating a new variable i within the for block. So this doesn't alter your original i variable declared at the top. Try using end = size - 1 or it's a best practice to define a constant for this purpose.
#define ARR_SIZE 10
in loop
for(i=0; i<ARR_SIZE;i++)
Then initialize end = ARR_SIZE -1;
And one more thing in your binary_search function is that you don't handle the case when the key is not present in the array.
Something like
if(end==start && array[end] != search)
return -1;
This checks when the search space has only one element and that is not your search element, it means it doesn't exist so we return -1.
Hope this helps
The problem is occurring because you are using uninitialised variable i here:
end = i -1;
Note that the scope of variable i declared in loop init clause is different from the scope of variable i declared in function block.
for(int i=0; i<10; i++){
^^^^^^^
// The scope of i declared in loop init clause is limited to the loop.
To fix the problem, you can use the i declared at function block scope as the loop variable, like this
for(i=0; i<10; i++){
Now, after the loop finishes, the variable i will hold its last value until it's value explicitly modify. But using i to identify the size of array down the code may cause several problems as it is not tightly coupled with the size of array and i may be get modified by other part of code. So, it is not the right idea to use i to identify the size of array.
Since, you are having a variable size which hold the size of array Ferrari, you can do:
end = size - 1;
No need to have another variable to keep the track of size of array. The problem with this is that you have to keep updating the size whenever you change the array size. An alternative of this would be to use a macro to define the array size.
The most appropriate way to set the end of array would be:
end = (sizeof(Ferrari) / sizeof(Ferrari[0])) - 1;

Changing and updating values with arrays in C

I am having issues with my c program. I am new to C programming and I have to write a program for class involving arrays. I have to use two sets of arrays and allow the user to remove a location and add a new value into that spot. I created a max array of 20 but we have to use 1 thru 5 and allow the user to remove the value in either data set. Here is what I have currently and I am getting a lot of errors saying I have ; and { in the wrong spots but it doesn't seem wrong when I go back to my text book and slides about arrays. I created constant values under myarr1 and myarr2 and SIZE is set to 20. Any and all help is appreciated I don't understand why i am getting all these errors.
int display_arr(int * count);
int remove_arr();
int myarr1[SIZE];
int main() {
printf("Data confirmation and update program written in C.\n");
int display_arr[6];
// display_arr[0]=NULLL;
int counter = 6;
my_identity();
for (i = 0, i < SIZE; i++) {
myarr1[i] = counter;
}
for (i = 0, i < SIZE; i++)
printf("Array[%d] is %d.\n", i, myarr1[i];
return EXIT_SUCCESS;
}
// deleting entry from data
int remove_arr() {
int position;
printf("Enter the location where you wish to delete element\n");
scanf("%d", & position);
}
int display_arr(int * count) {
int i;
for (i = 0; i < * count; i++)
printf("%d", myarr1[i]);
return 0;
}
//add an entry to data set
// int myarr()
}
// int input;
// printf("Enter the value you would like to add to the end of the arry:");
// scanf("%d", &input);
// if (array_select == 1){ // adds value to data set 1
// myarr1[*counter] == input;
// else
// myarr2[counter] == input; // adds value to data set 2
//return 0;
}
}
Computer programming is about being precise. This means also following the rules exactly to the point, not more, not less.
In this case, I see two things
Parenthesis/braces/brackets must be balanced:
printf("Array[%d] is %d.\n", i, myarr1[i];
Do you see the missing parenthesis at the end?
Comma and semicolon are not the same:
for (i = 0, i < SIZE; i++) {
Do you see the first comma?
For the other problems, look at the compiler error messages.

Assigning a random value to an array

I'm trying to
Get rid of the info in an array with 10 "spots".
Fill the array with (10) random numbers
My code till time
int main()
{
int numbers[10] = { 0 };
int randNumber = 0;
int i = 0;
for (int i = 0; i <= 10; i++)
{
srand(time(NULL));
randNumber = rand() % 10 + 1;
printf("Random number saved in the array: %d\n", randNumber);
i++;
}
getchar();
getchar();
return 0;
}
First of all, you need to move the srand(time(NULL)); out of the loop.
Otherwise, because, time() has a time granularity of 1 second, in a second, if called multiple times in the loop (within a second, probably), it will re-initialize the PNRG with the same seed and all the next call to rand() will give you the same random number.
Now, once you have the random numbers, you need to assign it to the each array member like numbers[i] = randNumber; inside the loop, but there's more to it. Your loop, at present is off by one. You need to change
for (int i = 0; i <= 10; i++)
to
for (int i = 0; i < 10; i++)
to stay within bounds.
Your array's size is 10, and this loop runs 11 times, causing an overflow. This will solve it:
for (int i = 0; i < 10; i++)
Also remove the increasing of the loop's iterator, i, from inside the loop body. Remove the line:
i++;

C Max Numbers In An Array Algorithm

So, I'm just working on C code, particularly a function which accepts 3 arguments: an array, the size of the array, and the number of max elements you want returned.
Here's my code:
int* findMaxElements(int base_array[],int size_of_base_array, int number_of_elements_to_find);
int main( void )
{
printf("Find Max Values in an Array\n\n");
// Set up array
int kinch[6] = {1,2,3,4,5,6};
// Pass to function and get a pointer to new array filled with only the max elements
int *given = findMaxElements(kinch,6,3);
for(int i = 0; i < 3; i++)
{
printf("\nMax Value = %d\n", *(given + i));
}
return 0;
}
int* findMaxElements(int base_array[],int size_of_base_array, int number_of_elements_to_find)
{
// Set up all initial variables
int i,k,c,position;
int maximum = 0;
int returnArray[100];
/*Actual Algorythm */
for(i = 0; i < number_of_elements_to_find; i++)
{
// Get the max value in the base array
for(k = 0; k < size_of_base_array; k++)
{
if(base_array[k] > maximum)
{
maximum = base_array[k];
}
}
// Find the position of the max value
for(position = 0; position < size_of_base_array; position++)
{
if(base_array[position] == maximum)
{
break;
}
}
// Delete the maximum value from the array and shift everything
for(c = position - 1; c < size_of_base_array - 1; c++)
{
base_array[c] = base_array[c+1];
}
// Reduce the size of the array
size_of_base_array -= 1;
// Push max value into return array
returnArray[i] = maximum;
// Reset max value
maximum = 0;
}
return returnArray;
}
I have a feeling somewhere in the function something goes wrong.
// Set up array
int kinch[6] = {1,2,3,4,5,6};
// Pass to function and get a pointer to new array filled with only the max elements
int *given = findMaxElements(kinch,6,3);
for(int i = 0; i < 3; i++)
{
printf("\nMax Value = %d\n", *(given + i));
}
This should output the numbers 6, 5, and 4, because they are the three largest in the array, however the output I get is always 6, 6, and 6. What's wrong with it?
This may not be your only problem, but in the lines
for(c = position - 1; c < size_of_base_array - 1; c++)
{
base_array[c] = base_array[c+1];
}
You copy the element at [c+1] (which is the maximum) to [c] - so you keep finding the max...
You should start the loop with c = position, not c = position - 1.
And add keyword static in front of the array you use to store the return values, so they remain valid (this is one way to address the issue that Jonathan Leffler identified).
One problem is that you are returning a pointer to a local variable, returnArray, in the function. You can't do that reliably — it leads to undefined behaviour.
There may well be other problems too, but that's enough to be a show-stopper on its own.
The whole approach to find the Kth largest element is not efficient and elegant. I will suggest you to modify your algorithm, although with above suggestions it will work fine, but it's not good way to solve this problem.
I will suggest you to look into below link to modify your algorithm
http://www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/

Resources