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.
Related
I have to creat a program thats that asks from the user to enter a number of rows and then creats a floyd's triangle. The problem is i don't seem to manage to make this particular pattern:
1
2 3
4 5 6
7 8 9 10
I have only managed to creat the basic program
#include <stdio.h>
#include <stdlib.h>
int rows, r, c, a;
int number=1;
int main()
{
printf("Floyd Triangle\n");
printf("--------------");
printf("\nPlease enter an integer number of rows: ");
scanf("%d",&rows);
while(rows<=0)
{
printf("\nYou must enter an integer value: ");
scanf("%d",&rows);
}
for(r=1;r<=rows;r++)
{
for(c=1;c<=r;+c++)
{
printf("%d ", number++);
}
printf("\n");
}
there are no erros in my code so far
Just print some spaces before the first number in each row
// ...
for (r = 0; r < rows; r++) {
printsomespaces(r, rows); // prints some spaces depending on current row and total rows
for (c = 0; c < r; +c++) {
printf("%d ", number++);
}
printf("\n");
}
// ...
If you can't write your own function (no printsomespaces) use a loop instead:
//...
//printsomespaces(r, rows);
for (int space = 0; space < XXXXXXXX; space++) putchar(' ');
//...
where XXXXXXXX is some calculation using r and rows.
Try (untested) 2 * (rows - r) (2 is the width of each number: 1 for the number + 1 for the space).
i haven't learnt how to make my own functions yet. isnt there a way to accomplish this only by using loops?
There is. A main problem of this exercise is to compute the needed width of each column, which of course depends on the number in the bottom row. The count of digits of a number can be determined in various ways; perhaps the easiest is via the snprintf(char *s, size_t n, const char *format, ...) function, which
… returns the number of characters that would have been written
had n been sufficiently large…
If n is zero, nothing is written,
and s may be a null pointer.
// we need to compute the width the of widest number of each column
int width[rows];
const int max = rows*(rows+1)/2; // the greatest number
for (c=1; c<=rows; ++c) // see how many characters will be written
width[c-1] = snprintf(NULL, 0, "%d ", max-rows+c);
for (r=1; r<=rows; ++r, puts(""))
for (c=1; c<=rows; ++c)
if (c <= rows-r) // here comes an empty cell in this row
printf("%-*c", width[c-1], ' ');
else
printf("%-*d", width[c-1], number++);
I'm trying to write C code where the user inputs 10 values and the index, and the output should display the index's value from the 10 values set by the user.
The problem statement:
Your grandparents gave you a fantastic cooking recipe but you can never remember how much of each ingredient you have to use! There are 10 ingredients in the recipe and the quantities needed for each of them are given as input (in grams). Your program must read 10 integers (the quantities needed for each of the ingredients, in order) and store them in an array. It should then read an integer which represents an ingredient's ID number (between 0 and 9), and output the corresponding quantity
Example Input:
500 180 650 25 666 42 421 1 370 211
3
My code:
#include <stdio.h>
int main(){
int ingred[9];
int readValue = 0;
int ID;
for(int i = 0; i < 9;i++){
scanf("%d %d", &readValue,&ID);
ingred[i] = readValue;
}
printf("%d",ingred[ID]);
return 0;
}
My output is always 0. Doesn't the scanf() function read the next line of code after the user presses "enter"? Please help.
Is it a requirement to read all of the quantities from a single line? Because that can be a little tricky to perform with scanf.
You could iterate trough a loop and get all of the quantities one by one, like this:
#include <stdio.h>
int main ()
{
int ingredients [10];
int newQuantity = 0;
int ingredientId;
int index;
for (index = 0; index < 10; index++)
{
printf ("Enter quantity #%d: ", index);
scanf ("%d", &newQuantity);
ingredients [index] = newQuantity;
}
printf ("Enter the ID: ");
scanf ("%d", &ingredientId);
printf ("Quantity: %d\n", ingredients [ingredientId]);
return 0;
}
On your code you tried to read a pair of integer values nine times in your loop. That's also something to note: despite array indexes beginning at 0, when you declare an array, the value between brackets is the number of elements of the array, not the index of the last element.
#include <stdio.h>
int main(void){
int i = 0;
int entry;
int index = 0;
int array[10];
for(i = 0; i <10; i++){
scanf("%d", &entry);
array[index] = entry;
index = index + 1;
}
scanf("%d", &index);
printf("%d", array[index]);
return 0;
}
Try this.
I'm trying to create a program which randomly decides how many cards you have, then randomly allocates a value to each of those cards.
I have managed to randomise the amount of cards, and I know how to randomise their values using an array and a for loop, but the problem is that this method only works when I manually choose a value for the number of elements in the array, but I want the number of elements to be the random amount of cards.
How do I go about this?
Here's my code so far to show what I mean. And yes, I'm aware the code probably could be done better but this is my first C assignment and I'm a complete beginner.
Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(void)
{
system("cls"); /* Clears output to start */
srand(time(NULL)); /* Sets seed for random number generator */
int player1_amount = rand() %9 + 2; /*Generates random number for player 1's amount of cards */
int player2_amount = rand() %9 + 2; /*Generates random number for player 2's amount of cards */
int a = 1; /* For loop purposes */
while(a <= 1) /* While loop to print out each player's amount of cards once */
{
printf("Player 1 you have %d cards! \n", player1_amount);
Sleep(500);
printf("Player 2 you have %d cards! \n", player2_amount);
a++;
}
Sleep(1000); /* Delays for 1 second before printing card values */
int values[3]; /* Creates an array with 3 elements, but I want the number of elements to be player1_amount from above */
int b; /* Random variable for the loop */
int size = sizeof(values) / sizeof(values[0]); /* Gets length of array */
for (b = 0; b < size; b++) /* For loop randomises 3 values and then stops */
{
values[b] = rand() % 10 +1;
}
printf("Player 1 your cards are"); /* For loop to print out the values one after the other */
for(b = 0; b < size; b++)
{
printf(" %d, ", values[b]);
}
getch();
return 0;
}
I believe you will want to use malloc or calloc for that with a pointer.
int *values = (int *)calloc(player1_amount, sizeof(int));
Just make sure you free your allocation when done:
free(values);
C allows you to declare variable sized array. If you are not interested in using functions like malloc or calloc you can simply use variable to declare array as I've done here :
#include <stdio.h>
void main()
{
int x;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
int array[x];
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
This program runs correctly without any error. So your problem is solved here itself without using malloc or calloc. But just make sure you declare your array after scanning or giving value to your variable which will represent the size of your array(here : x is the variable) and in your case I guess : player1_amount.
But still if you want to use malloc then here it goes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int x , i;
int * array;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
array = (int *) malloc(x * sizeof(int));
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
Both the codes will give you same output.
A little explanation ...
Malloc will take input parameter as the amount of memory you wish to allocate to given variable(like 'array' in our case) in bytes and will output the pointer to that block of memory.
Since here we are working with integer array the return type is cast as : (int *), had it been a character array we would type cast it as : (char *).
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.
I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.