C Array of Counters - c

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i; //Counting Variable for loop
int sales[30]; //Array for sales people
//Creates Gross for 30 Indiviudals
for (i = 0; i < 30; i++)
{
sales[i] = ( rand() % 15000) + 1;
}
printf("Original List\n");
for (i = 0; i < 30; i++)
{
printf("%d\n", sales[i]);
}
return 0;
}
Im tying to make a program that takes 30 random numbers between 0 and 15000, then applies the equation (100+a*0.09), then sorts the answers from highest to lowest. Im getting stuck on how to apply the equation to the values founded in the array since they are program generated.

you can just loop through the array again and assign them again just like you looped through the two previous times
for (i=0; i < 30; i++){
sales[i] = 100 + sales[i] * .09;
}

You mean:
for (i = 0; i < 30; i++)
{
printf("%f\n", 100 + (float)sales[i] * 0.09);
}
?
You can also store it in an other array (of float/double). Not sure to understand correctly as it seems very simple!
Edit: if you need to sort it you would have to store it in an array (float vals[30]; let say) and then have a look to 'qsort(…)' function in order to order the values.

Related

Confusion in arrays

Recently I was learning about arrays passing to functions (by passing their base address to a pointer defined as parameter in function and then using pointer arithmetic for extracting the whole array subsequently)
For practice I was asked to calculate the average marks of a class of 70 students with their marks listed in an array named "marks" and was asked to define a variable with parameter as a pointer
and calculate average from there.
The data given to me was that student 1 scored 40 , student 2 scored 41, student 3 scored 42....and so on.
Here is my attempt at it:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
float average(int *b)
{
int sum = 0;
for (int i = 1; i <= 70; i++)
{
sum = sum + *b;
b = b + 1;
}
printf("the value of sum is %d\n", sum); // this value is changing every time I run the program
return (((float)sum) / 70);
}
int main()
{
int marks[70];
marks[0] = 40;
for (int i = 0; i < 68; i++)
{
marks[i + 1] = marks[i] + 1;
}
printf("the value of marks of 10th child is %d\n", marks[9]); // Just for checking if I am correct!(yes! the ans does come out to be 49!)
printf("the value of average marks of the class is %f\n", average(&marks[0]));
return 0;
}
to my surprise the value kept changing every time I ran it. Can anyone give a hint where am I wrong?
I was asked to calculate the average marks of a class of 70 students with their marks listed in an array named "marks"
In the posted code, we can find the following declaration
int marks[70];
The size is correct, but note that it's uninitialized, so that the values of its elements are undeterminated. The code, though, tries to assign the correct values immediately after.
marks[0] = 40; // "student 1 scored 40, student 2 scored 41, student 3 scored 42...
// and so on."
for (int i = 0; i < 68; i++)
{ // ^^^^^^
marks[i + 1] = marks[i] + 1;
} // ^^^^^
The last mark assigned is marks[67 + 1], which leaves marks[69] (the actual last element of the array) undeterminated.
There are many ways to achive the correct result, some may find the following appropriate.
int marks[70] = { 40 };
for (int i = 0; i + 1 < 70; ++i)
{ // ^ ^^^^^^^^^^
marks[i + 1] = marks[i] + 1;
}
I was learning about arrays passing to functions (by passing their base address to a pointer defined as parameter in function and then using pointer arithmetic for extracting the whole array subsequently)
Using indices often yields more readable code, so I won't use "pointer arithmetic" in the following snippet.
I'd suggest to always pass the size of the array, not only the pointer.
Note how many "magic" numbers, like 70 and the wrong 68, are spread (and repeated) throughout the posted code, limiting its generality and rising the chances of errors.
I'd also extract the logic of the previous snippet into a separate function, easily modifiable and testable.
#include <stdio.h>
double average(size_t n, int *marks)
{
long sum = 0;
for (size_t i = 0; i < n; ++i)
{
sum += marks[i];
}
return (double)sum / n;
}
void fill_linear(size_t n, int *arr, int first_value)
{
for (size_t i = 0; i < n; ++i)
{
arr[i] = first_value++;
}
}
int main(void)
{
enum { n_students = 70 };
int marks[n_students];
fill_linear(n_students, marks, 40);
printf("Average: %.1f\n", average(n_students, marks)); // Average: 74.5
return 0;
}
You're problem is related to the fact (as mentioned in my comment) that your array is uninitialized.
The memory for it has been allocated but its still random jumble data.
Luckily you overwrite that data for all entries in the array, except for the last one. The last entrance is basically a random value at this point.
So thats the reason the output keeps changing, your actuall bug is a bit simpler.
In the for loop where you calculate the sum, you iterate from i = 0 to i = 67. So with the +1 offset you change all the entries from 1 to 68, so the last entrance (marks[69]) doesn't get touched.
Fixed code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float average(int *b) {
int sum = 0;
for (int i = 1; i <= 70; i++) {
sum = sum + *b;
b = b + 1;
}
printf("the value of sum is %d\n",
sum); // this value is changing every time I run the program
return (((float)sum) / 70);
}
int main() {
int marks[70];
marks[0] = 40;
for (int i = 0; i < 68; i++) {
marks[i + 1] = marks[i] + 1;
}
printf("the value of marks of 10th child is %d\n",
marks[9]); // Just for checking if I am correct!(yes! the ans does come
// out to be 49!)
printf("the value of average marks of the class is %f\n", average(&marks[0]));
return 0;
}
PS:
In the average function ,you use pointer arithmetic to loop over the input array, which is considered bad practice by a lot of people. Also, youre basiaclly not using the for-loop incrementor variable you create (int i). A easier and safer way to do this is :
float average(int *b) {
int sum = 0;
for (int i = 0; i < 69; i++) {
sum += b[i];
}
printf("the value of sum is %d\n",
sum); // this value is changing every time I run the program
return (((float)sum) / 70);
}

C: Create randomly-generated integers, store them in array elements, and print number of integers stored in each element

I'm incredibly new to C (and programming in general) and finding how to manipulate arrays is almost impossible to understand (I know what an array is).
I'm attempting to write a program that generates 100 random integers in a range (1-50), stores them in array elements (1-10, 11-20, 21-30, 31-40, and 41-50), and print the number of randomly generated integers stored in each element, i.e.
1-10 = 20
11-20 = 30
21-30 = 21
31-40 = 19
41-50 = 20
The best I can come up with so far is:
void randomNumbers
{
int count[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = rand() % 50 + 1;
}
for (int i = 0; i <= ARRAY_LENGTH - 1; i++)
{
printf("Index %d -> %d\n", i, count[i]);
}
}
That just says "element 1 = random number, element 2 = random number" etc.
I don't understand how to:
Store the randomly-generated integers in the array's elements
Partition the randomly-generated integers into the corresponding
element
Tell the program to print the number of integers generated in each
element range
The following is the code that generates 100 random integers and groups them into categories based on their value :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i, temp;
int a[5]; // array to store the frequency
for(i=0;i<5;i++)
a[i]=0;
srand(time(0)); // for generating new random integers on every run
for(i=0;i<100;i++)
{
temp = (rand()%50) + 1; // generates random integers b/w 1 to 50
a[(temp-1)/10]++;
}
for(i=0;i<5;i++)
printf("%d->%d = %d\n",i*10+1,(i+1)*10,a[i]); //printing in the desired format
return 0;
}

How can I use the rand() function to generate a different number that hasn't been generated before?

// What I mean by this is shown by my example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int i;
int a;
for (a = 0;a <10;a ++) {
i = (rand()%10)+1; // generates a number from 1-10
printf("%d\n", i);
}
// I would like for the loop to generate a number that gives a number that was not generated before. For example, an output such as:
1,3,6,2,8,9,4,10,5,7
instead of:
3,9,10,3,7,9,2,7,10,1
In other words, I would like no copies.
You obviously don't just want no copies, but you want every number in a given set exactly once. This is, as commented by Robert, similar to shuffling a deck of cards. You don't have "decks" in C, but you can model one as an array:
int deck[] = {1,1,1,1,1,1,1,1,1,1};
This should represent 10 different "cards" (identified by their index in the array), each available one time. Now, just write code that "draws" cards:
int i = 0; // starting point for searching for the next card to draw
for (int n = 10; n > 0; --n) // how many cards are left
{
int skip = rand() % n; // randomly skip 0 .. n cards
while (1)
{
if (deck[i]) // card still available?
{
if (!skip) break; // none more to skip -> done
--skip; // else one less to skip
}
if (++i > 9) i = 0; // advance index, wrapping around to 0
}
deck[i] = 0; // draw the card
printf("%d\n", i+1); // and print it out
}
of course, seed the PRNG (e.g. srand(time(0))) first, so you don't get the same sequence every time.
The idea shown in the question is to print numbers within a range, without repetition. Here is one way to do that, by putting each value into an array and swapping its elements around.
A variation could be that you don't want to use all the possible numbers, in that case just change PICKED.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRLEN 10
#define PICKED 10
int main(void) {
int array[ARRLEN];
srand((unsigned)time(NULL)); // seed the PRNG
for(int i = 0; i < ARRLEN; i++) { // generate the numbers
array[i] = i + 1;
}
for(int i = 0; i < ARRLEN; i++) { // shuffle the array
int index = rand() % ARRLEN;
int temp = array[i];
array[i] = array[index]; // by randomly swapping
array[index] = temp;
}
for(int i = 0; i < PICKED; i++) { // output the numbers
printf("%d ", array[i]);
}
printf("\n");
}
Program output:
9 8 4 5 1 10 7 3 6 2
The library's PRNG is not very random, but for many cases that is not important. If it is, better algorithms are available.

How do I print out 100 numbers in an array then add them using C

I'm trying to print out 100 numbers from an array using a loop and then add them all together. So far I have:
#include <stdio.h>
#include <stdlib.h>
int main(){
int* number = malloc(101 * sizeof(int));
int num = 0;
number[num] = 1;
while (number[num] <= 100){
printf(" %d\n ", number[num]);
num = num +1;
number[num] = number[num]+1;
}
return 0;
}
but this just prints 1 once.
number[num] = number[num]+1;
You only properly set number[0]. Now you are trying to take whats in number[1] and add to it, in the first iteration. You didn't set it to anything though, leaving it uninitialised. This is undefined behaviour. What you most likely wanted to do is
number[num] = number[num-1]+1;
To add one to the previous number before after printing it. Now it will print fine.
To add them up, simply do
for (int a = 0; a < 100; a++) {
number[100] += number[a]; // add number[a] to result
}
printf("%d\n",number[100]);
Also, don't forget to free your dynamically allocated array at the end.
Try this:
#include <stdio.h>
int main () {
int n[ 100 ]; /* n is an array of 100 integers */
int i,j;
int sum = 0;
/* initialization */
for ( i = 0; i < 100; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 100; j++ ) {
printf("Element[%d] = %d\n", j, n[j]);
sum += n[j];
}
printf("Sum of Elements = %d\n", sum);
return 0;
}
Remember that you should declare an array, then initialize it, print it out and after all print out the sum
You can just print out 1 to 100, then you could quickly use some maths to get the count of all numbers added together, for example, one of Gauss' algorithms, specifically http://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/
There’s a popular story that Gauss, mathematician extraordinaire, had a lazy teacher. The so-called educator wanted to keep the kids busy so he could take a nap; he asked the class to add the numbers 1 to 100.
Here's what I would do: -
int i = 0;
for (i = 1; i <= 100; i++) {
printf("%d", i);
}
// gauss technique 100(100 + 1) / 2
int count = (100 * 100 + 100 * 1) / 2;
printf("all numbers added: %d", count);

issues randomly populating a 2d array of structure type in C

I'm trying to populate a 20x20 matrix where each entry is of structure type. My goal is to randomly assign 100 ants and 5 doodlebugs on this 2D array. Even though I got it to work, I don't always get the amount of ants or doodlebugs I need in the matrix. I added a counting function to always verify how many of them I have each time I run the program, but I'm always slightly short. I'm trying to force those number to work (100 ants and 5 doodlebugs) by using a do/while loop in my populating function, although it's not working. Can someone spot where is my logic is failing me?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define N 20
struct cellState {
int emptyInt;
int antInt;
int dBInt;
char emptyChar;
char antChar;
char dBChar;
};
struct cellState gridState[N][N];
// function to populate world
void pop_mtx(struct cellState gridState[N][N], int antsNeeded, int dBNeeded) {
int i, j;
do {
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if ((gridState[i][j].emptyInt = rand() % 3) == 0) {
gridState[i][j].emptyChar = '.';
} else
if (((gridState[i][j].antInt = rand() % 3 == 1) && antsNeeded != 0)) {
gridState[i][j].antChar = 'a';
antsNeeded--;
} else
if (((gridState[i][j].dBInt = rand() % 3 == 2) && dBNeeded != 0)) {
gridState[i][j].dBChar = 'D';
dBNeeded--;
}
}
}
} while (dBNeeded != 0 && antsNeeded != 0);
}
//function to display current state of the world
void display_mtx(struct cellState gridState[N][N]) {
int i, j;
char charToDisplay;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (gridState[i][j].antChar == 'a')
charToDisplay = 'a';
else
if (gridState[i][j].dBChar == 'D')
charToDisplay = 'D';
else
charToDisplay = '.';
printf("%c ", charToDisplay);
}
printf("\n");
}
printf("\n\n");
}
//function to count ants and doodlebugs
void count_mtx(struct cellState gridState[N][N]) {
int i, j, antCount = 0, dBcount = 0;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (gridState[i][j].antChar == 'a')
antCount++;
else
if (gridState[i][j].dBChar == 'D')
dBcount++;
}
}
printf("ant count: %i, doodlebug count: %i\n", antCount, dBcount);
}
int main(void) {
srand((unsigned int)time(NULL));
//populate grid state with 5 doodlebugs and 100 ants
int antsNeeded = 100, dBNeeded = 5;
pop_mtx(gridState, antsNeeded, dBNeeded);
count_mtx(gridState);
display_mtx(gridState);
}
There are several problems. First, each time you call rand() you obtain a different value, so it is possible that none of the three tests pass. You should call rand () once and save the value.
Second, there is nothing that guarantees that over NxN calls of rand() you will get as many ones and twos as you need. The outer loop is therefore necessary. You should also preserve already populated squares from one iteration to the next because it might take a long time before you reach an iteration that produces enough ones and twos.
Third, this method is biased toward the squares at the beginning of the grid. It will not give you one out of all possible distributions of 100 ants and 5 doodlebugs over 400 squares with equal probability.
Here is the proper way to do it:
Consider the grid as a uni-dimensional array. First fill it, in order, with 100 ants, 5 doodlebugs, and empty spaces. Then perform a random shuffle of the array.
This procedure will return each possible distribution of the ants and doodlebugs on the grid with equal probability.

Resources