I am creating an array that contains the locations of sites in space. So for array[2], I also want to say array[2].num = 2 I want each site to have a unique site number num from 0 to N-1. Output different values of i for array[i].num gives 0, 1, 32767. Whereas, for increasing i, I want to see incrementing values from 0 to N-1.
I am very new to structures so if you could explain where I am making my mistakes I would much appreciate your help as a noice programmer.
typedef struct site_t
{
int num; // want to add more varaibels later hence type struct //
} site;
site fillStruct( site[], int);
int main()
{ int i;
const int N = 20;
site array[N];
fillStruct(array, N);
for (i = 0; i < N; i++) {
printf("location of site %d\n", array[i].num);
}
}
site fillStruct(site array[], int size) {
for (int k = 0; k < size; k++) {;
array[k].num = k;
return array[k];
}
}
If I'm understanding your question correctly, I think your problem comes from your fillStruct() function. The loop in this function will only execute once, instead of N times. You never exceed k=0, so you set the num member for array[0] and then return array[0].
When you return to your main function, you print the location for array[0] accurately, but subsequent site numbers in the array are just random uninitialized values.
Instead, you want the return statement to be outside of the loop block, so the function should like like...
site fillStruct(site array[], int size) {
int k;
for (k = 0; k < size; k++) {;
array[k].num = k;
}
return array[k-1]; // Returns the last site in the array
}
Now, when you return to your main function you will have 20 sites numbered 0 to 19 (for N=20).
Also note that in the code you gave, you are not using the return value of fillStruct().
Hope that helps, let me know if I missed something.
Related
#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
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);
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.
I'm trying to find the sum of all positive numbers in an array. So far, I have come up with this;
int largest_sum_sequence(int list, int size)
{
int sum = 0, *index = 0;
for (index < size; index = size; index++)
{
if (list[index] > 0)
{
sum = sum + list[index];
}
}
printf("%d", sum);
return sum;
}
My program keeps crashing. I'm pretty sure it has something to do with index. Whenever I use list[index] it says that I need to use a pointer for index, but I don't know how to do that properly. Help is appreciated!
You do not want index to be a pointer, and your for loop is incorrect. Try:
int sum = 0, index = 0;
for (; index < size; index++)
The compiler tells you actually exactly what to do.
First of all you need an array or a pointer as a parameter, like
int largest_sum_sequence(int *list, int size)
{
....
}
or
int largest_sum_sequence(int list[], int size)
{
....
}
where the latter might be easier to read.
The second thing is, you don't want to iterate with a pointer through the list, but more with a simple integer.
so you declare
int sum = 0, index = 0;
The for() loop isn't quite correct either. Instead of initializing something, you test if index < size and discard the result. This is syntactically correct, but doesn't make sense.
The first part in the for-statement is executed before the loop starts, but doesn't influence the starting itself. It is meant for initializing the loop variable (index in this case). The second part is the termination condition. The loop terminates if the condition evaluates to false. The last part of the loop is for incrementing (or decrementing, more abstract, changing) the loop variable.
Having said this, it is halfway obvious it should look like:
for (index = 0; index < size; ++index) {
....
}
Assuming your list isn't very long (such that the sum could exceed 2^{31} - 1), the rest is correct. Although I'd add an \n to the printf() pattern.
Where is the list coming from? Can't answer that from your code, but you've room for mistakes here too :-)
Function argument doesn't except an array.
Quick function I wrote.
int getSums(int myArray[], int size)
{
int total = 0;
int index = size;
for ( int i = 0; i < index; i++)
{
if (myArray[i] > 0)
total += myArray[i];
}
return ( total );
};
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/