Am having many problems with coding C. Apologies for any bad mistakes. Im trying to do simple horizontal histogram for frequency of integers in array. No matter what it prints out incorrect and makes infinite loop. I believe the problem lies in printHistogram function. Any tips?
Here is code:
#include <stdio.h>
//Prints histogram to screen using horizontal bar chart
void printHistogram ( int *hist, int n );
int main ( void )
{
int i, n;
printf ("How many values for array? ");
scanf ("%d", &n);
int list[n];
for (i=0; i < n; i++) {
printf ("Enter value: ");
scanf ("%d", &list[i]);
}
// Process data to compute histogram
int hist[10];
// Print histogram
printHistogram ( hist, 10);
return 0;
}
void printHistogram ( int *list, int n )
{
int i, j;
for (i=0; i < n; i++) {
printf ("[%d] ", i);
for (j = 0; j < list[i]; j++)
printf ("*");
printf ("\n");
}
}
The problem is in
for (j = 0; j < list[i]; j++)
when, you're trying to use list[i], but based on the argument passed, the value is indeterminate. So, in this case, this invokes undefined behavior and the loop goes haywire.
To elaborate, you have defined int hist[10]; as a local variable and did not initialize it, so all the members contain indeterminate value. You then, go ahead and pass the array to printHistogram(), inside which, you receive it via list and then, dereference that and expect to get some valid value magically, which is not possible.
OTOH, you are scanning values in list inside the main() and not using it. You need to make some corrections so as to make use of the scanned value later, which seems to be the actual target.
Related
Beginner here, I've been trying this for hours and can't get it to work, searched online too and couldn't find an answer.
I'm trying to write a program where you input people by putting their age and height then calculate the average of each, and the average ratio of age to height. Whenever I pass the struct to my getAverage function, it returns the address (I think) instead of the averages.
#include <stdio.h>
#include <stdlib.h>
typedef struct person
{
int age;
double height;
} Person;
double getAv (Person people[50], int max)
{
int i;
double total, retval;
total = 0;
for (i=0; i<=max; i++)
{
total = total + people[i].age;
}
retval = total / max;
return retval;
}
int main (void)
{
Person people[50];
int i;
while (i++, people[i].age>=0)
{
printf ("Person #%d\n", i);
printf ("enter an age: ");
scanf ("%d", &people[i].age);
if (people[i].age<0)
break;
printf ("enter a height: ");
scanf ("%lf", &people[i].height);
printf ("\n");
}
double averageAge;
averageAge = getAv (&people[50], i);
printf ("%.1lf\n", averageAge);
}
Haven't implemented average height or ratio yet, just trying to get average of ages to work for now. When I try taking the & out of averageAge = getAv(&people[50], I); I get a compile error that tells me it needs the &. Any help would be appreciated.
There are serveral issues in you code, the first one:
Person people[50];
int i;
while (i++, people[i].age>=0)
You are using i uninitialized, thus, incrementing a variable containing garbage (or 0 as intended, but it is impossible to guarantee)
To avoid such problems in the future enable warnings on your compiler, the compiler would have told you something like:
āiā is used uninitialized in this function [-Wuninitialized]
So switch to
Person people[50] = {0};
int i = 0;
It seems (based on the pre-increment operator ++i) that you want to use arrays with base 1, there is nothing wrong with that, but in your average function you are starting from 0, so use a for:
for (i = 0; ; i++)
{
...
if (people[i].age <= 0) break;
...
}
Another issue:
double averageAge;
averageAge = getAv (&people[50], i);
In this way you are passing only element 50 which is not part of your array (remember arrays are base 0 in C), to pass the entire array:
averageAge = getAv (people, i);
or
averageAge = getAv (&people[0], i);
The last one:
for (i=0; i<=max; i++)
You are including the element discarded when you was checking for age > 0, switch to:
for (i=0; i<max; i++)
A minor issue:
Iif the user enters 0 for the first element of people you end up dividing by 0
double averageAge;
averageAge = getAv (&people[50], i);
printf ("%.1lf\n", averageAge);
should be
if (i > 0)
{
double averageAge;
averageAge = getAv (people, i);
printf ("%.1f\n", averageAge); // No need to use lf (long double)
}
If you do it this way, you need to receive in your function (Person& people[], int n)
Where n is the length of the array.
We use the '&' to not do copies of the array and also you are passing only the element with index 50 in the function, simply do only (people, n)
there are mistakes in this code ,first you should initialize int i to int i=0 in mian function.
how are using this condition while (i++, people[i].age>=0) when you haven't scanned any input it's like using an uninitialized variable. you need a do-while like this
do
{
printf("Person #%d\n", i);
printf("enter an age: ");
scanf("%d", &people[i].age);
if (people[i].age < 0)
break;
printf("enter a height: ");
scanf("%lf", &people[i].height);
printf("\n");
i++;
} while (people[i-1].age >= 0);
also you are sending wrong arguments to your getAv function you should use averageAge = getAv (people, i);.
and in your function you have to remove = in this loop for (i=0; i<=max; i++) .this should be for (i=0; i<max; i++) ,otherwise the negative entered age will also be add to total and will affect the average.
So there is this project in Data Structures that i have to deal with this semester and it requires that i have to code in C . The problem is that i am a little bit rusty in C and i am dealing with basic problems. One of the problems is that i have to write a simple program in C that implements BubbleSort . The BubbleSort algorithm has to be a seperate function and call it in the main program . Here is my effort . The problem is that it doesnt type the sorted array . I hope you can help me .
THE CODE :
int calculateRand()
{
int num;
num = (rand())%(UPPER-LOWER+1)+LOWER;
return num;
}
void swap(int *xp, int *yp)
{
int temp=*xp;
*xp=*yp;
*yp=temp;
}
void BubbleSort(int S[], int n)
{
int up=n;
int i,j;
while(up>1)
{
j=0;
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
}
for(i=0; i<n; i++)
{
printf("%d\n", S[i]);
}
}
int main()
{
int n,i;
printf("Parakalw dwste mia timh sto n: \n");
scanf("%d", &n);
int S[sizeof(n)];
printf("O mi taxinomimenos pinakas einai o exis \n");
for(i=0; i<n-1; i++)
{
S[i]=calculateRand();
printf("%d\n", S[i]);
}
printf("O pinakas meta thn taxinomisi einai \n");
BubbleSort(S[sizeof(n)], n);
return 0;
}
So if we start from the top there is a problem in the calculateRand() function as you do not declare the UPPER and LOWER variables or pass them as parameters to function.
Swap function is ok.
In the BubbleSort() function you need to decrease the up variable value after the for loop.
while(up>1)
{
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
up--;
}
Also at this point you should start iterating from 0 instead of 1 since arrays start from index 0. So for(i=0; i<up-1; i++) is the correct way to go.
Lastly in the main() function when you're declaring the array variable S you shouldn't pass the sizeof(n) since n is an integer and size of an integer is 4. Instead you want to use n as it is int S[n];
For loop to populate the array should go up to n not n-1 if you want to fill all elements of the array. However if you change this you'll need to make the similar change in the BubbleSort() function.
And finally in the BubbleSort() function call you are passing the last element of the array which is an integer whereas function expects you to pass an array. It should look like this BubbleSort(S, n); instead.
sizeof(n) has nothing to do with the value of the variable n. It's the the size of the variable n, i.e. mostly 4 bytes for the modern architectures.
Modern variants of C permit variable size arrays thus
int S[n];
would have been legit. Otherwise
int *S = (int *)malloc(n*sizeof(int));
will help.
When you call BubbleSort , your argument should be S not S[sizeof(n)];
I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");
Got an incomplete histogram that needs to be completed for a project.
#include <stdio.h>
/**
* Prints a histogram to the screen using horizontal bar chart.
* Parameters:
* list - a list of integers
* n - the number of values in the list
*/
void printHistogram ( int *hist, int n );
/**
* This program requests data from the user and then
* computes and prints a histogram. You may assume that
* the data values entered are in the range of 0 to 9.
*/
int main ( void )
{
int i, n;
// Data entry
//
printf ("How many values in your data set? ");
scanf ("%d", &n);
int list[n];
for (i=0; i < n; i++) {
printf ("Enter a value: ");
scanf ("%d", &list[i]);
}
// Processing data to compute histogram
int hist[10];
// Printing histogram
printHistogram ( hist, 10);
return 0;
}
void printHistogram ( int *list, int n )
{
int i, j;
for (i=0; i < n; i++) {
printf ("[%d] ", i);
for (j = 0; j < list[i]; j++)
printf ("*");
printf ("\n");
}
}
You provide too little info for an actual solution but anyway.
So, I assume that you want to print a histogram with the number of occurrences of an integer from 1-9(At least, this is what I understood).
A possible way to do that is to create an ingeter array that will keep the number of occurrences of every integer. It will obviously have 10 items. When you get to the input, for every integer that you come across, you will incrememt the according item in the array. Note that you do not need to search in the array for every integer.
If you want to count the occurrences of words-strings, this is something a little more complicated because it requires the use of a struct, but it is based in the same idea.
My program is supposed to order a list of numbers inputed by the user, but it crashes even before reaching the first printf. My compiler makes 2 warnings, but I don't see the issue. I haven't studied pointers yet, so I didn't want to use them. Here are the messages:
In function `selection_sort':
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
In function `main':
[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast
.
#include<stdio.h>
int selection_sort(int n, int v[n])
{
int high = v[0];
int i;
for(i = 0; i < n; i++)
high = high < v[i]? v[i] : high;
if(n - 1 == 0)
return;
v[n - 1] = high;
n -= 1;
selection_sort(n, v[n]);
}
int main(void)
{
int n, i;
int v[n];
printf("Enter how many numbers are to be sorted: ");
scanf("%d", &n);
printf("Enter numbers to be sorted: ");
for(i = 0; i < n; i++)
scanf("%d", &v[i]);
selection_sort(n, v[n]);
printf("In crescent order: ");
for(i = 0; i < n; i++)
printf("%d ", v[i]);
getch();
return 0;
}
Your program is using a variable length array, a feature that was added in C99.
However, you declare its size based on an uninitialized variable. What did you believe would happen there?
In C, variables declared inside functions are NOT set to 0. They are not set to anything. They pick up whatever value was left on the stack or in the register that they are assigned.
I believe that your program is crashing because n in int v[n] is a ridiculously big number and v is trying to use too much memory.
You can probably fix this by moving your array declaration below the scanf that reads in n.
You need to pass v, not v[n] to the function selection_sort. v is the array, v[n] is actually an out of bounds element of v.
the line should be selection_sort(n, v);