C - Getting the min and max of the randomly generated numbers - c

My code is below, this is my first programming course so expect a possibly stupid mistake.
Basically I am trying to get the min/max and the position number of them. However, my max works correctly up until 6 numbers are generated and I can't seem to understand why.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int num[0];
printf("Enter an integer");
scanf("%d", &n);
x = n;
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
return 0;
}

There are actually several places that needs improvement in your code.
Firstly, it is invalid to declare an array of size 0 in your code int num[0];, so I'm not sure why your code work with a n up to 6.
Secondly, as you may learn very soon, indentation is very important while programming so that the code is better to understand and maintain in the future. Furthermore, while C is not a language that requires indentation (and that is considered one of its strengths) many common languages such as Python that rely on whitespace to differentiate functions do need careful management of indentation.
Third, RAND_MAX is not a multiple of 1000 so you would not obtain equal probability in your program. A srand function call is also recommended.
A possible implementation of your intended program (still ugly):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXN 1000
int main(void) {
int n, r, i;
int pos = 0;
int max;
int num[MAXN];
printf("Enter an integer");
scanf("%d", &n);
srand(time(0));
printf("\n Pos | Val");
for (i = 0; i<n; i++)
{
r = (int)(((double)rand() / (RAND_MAX + 1)) * 1000) + 1;
printf("\n %3d | %3d", i + 1, r);
num[i] = r;
}
max = num[0];
i = 0;
for (i = 1; i < n; i++)
{
if (num[i] > max)
{
max = num[i];
pos = i;
}
}
printf("\nMax : %d | Pos : %d", max, pos); // biggest number
//while (1);
return 0;
}
As far as my tests, this piece works well

As already identified by numerous answers and comments, your primary problem is your array. Standard C doesn't allow array sizes of zero. GCC does unless you tell it to complain.
However, all the other answers continue to blithely use the array. For the problem stated, there's no need for an array at all. Also, the question text mentions 'minimum' as well as 'maximum', and 'position' as well as 'value' — though the code shown reports neither minimum nor position. Clearly, if this is just a preliminary phase before using the data for some other work, then you probably do need to save the data in an array. You can then decide whether to use a C99 (or later) VLA — variable length array — or whether to use dynamic memory allocation with malloc() et al, remembering to free the allocated space with free().
Here's a simple revised program that doesn't use an array and does manage minimum and maximum as well as reporting positions. It deliberately changes the range of values to 0..999 so that there are never 4-digit numbers to throw the presentation off. You can decide what to do if you absolutely must used 1-based counting and values in the range 1..1000. (Using + 1 in selected locations is one part of the answer; deciding to replace %3d with either %d or %4d is probably the rest of the answer).
This code uses the time as a seed value for the random numbers, and it reports that seed value. If the program was going to be used seriously, I'd make it accept optional arguments, one of which would be the seed, so that previous runs can be recreated. I'd probably make it accept an argument for the number of random values to be generated too.
The code validates that a number was entered and validates that the number falls in the range 1..999, bailing out with an error message written to standard error if the value is not acceptable. Note that the error message diagnoses what is valid — there is nothing more frustrating than to be told that something is invalid but not why and what you need to do to fix it (and often, it helps to show what the program read — it might not be what the user thought the program would read).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int n;
printf("Enter number of random values to test: ");
if (scanf("%d", &n) != 1 || n <= 0 || n >= 1000)
{
fprintf(stderr, "Didn't read a valid number in the range 1..999\n");
return 1;
}
unsigned seed = time(0);
srand(seed);
printf("Seed: %u\n", seed);
int minval = 0;
int maxval = 0;
int minidx = 0;
int maxidx = 0;
printf("\n Pos | Val\n");
for (int i = 0; i < n; i++)
{
int r = (rand() % 1000);
printf(" %3d | %3d\n", i, r);
if (i == 0)
{
minval = r;
maxval = r;
minidx = i;
maxidx = i;
}
else if (r > maxval)
{
maxval = r;
maxidx = i;
}
else if (r < minval)
{
minval = r;
minidx = i;
}
}
printf("Minimum value was %3d at index %3d\n", minval, minidx);
printf("Maximum value was %3d at index %3d\n", maxval, maxidx);
return 0;
}
Example run (program mnmx67 compiled from mnmx67.c):
$ mnmx67
Enter number of random values to test: 10
Seed: 1503763592
Pos | Val
0 | 201
1 | 216
2 | 85
3 | 793
4 | 382
5 | 780
6 | 341
7 | 661
8 | 75
9 | 266
Minimum value was 75 at index 8
Maximum value was 793 at index 3
$

You did not store your random numbers in num, also You need to have some space to store these numbers. Try this for size, i commented my changes
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int * num; // ++++++++ pointer to array
printf("Enter an integer");
scanf("%d", &n);
x = n;
num = malloc(x * sizeof(int)); // ++++++++++ allocate memory
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
num[n] = r; // +++++++++ store your number
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
free(num); // +++++++++ free memory
return 0;
}

Your first mistake is that the array's dimension is zero. You need to set a size for the array.
I would do this by splitting the code into three additional functions: one to generate the numbers, and two others to find the min and max.
int *gennums(size_t n)
{
int *nums;
size_t i;
if ((nums = malloc(n * sizeof (int))) != NULL) {
for (i = 0; i < n; ++i)
nums[i] = rand() % 1000;
return nums; // caller must free
}
return NULL;
}
int min(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] < m)
m = arr[i];
return m;
}
int max(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] > m)
m = arr[i];
return m;
}

Here int num[0];
You are not storing your random numbers in this array.Searching in that is meaning less.
Also size of your array should be at-least equal to n

Related

change an integer to base 2 with arrays as output in C

#include <stdio.h>
#include<math.h>
int main(void){
int Num;
int i;
int N;
int x = 0;
int a[x];
scanf("%d", &Num);
N = Num;
for(i = 0; i < Num; i++)
{if (Num%2 == 0)
{a[i] = 0;}
else
{a[i] = 1;}
Num = Num/2;
}printf("%d in base 2 is %d", N, a[x]);
return 0;
}
program should convert an integer Num to base 2 eg 17 to 10001.
ideally using an array as the output
the remainder of the division of Num by 2 should be the last number in the output
then number is divided by 2 and the process repeats with the second output becoming the 2nd last output of the array
Sorry if this question is worded badly
Any help is appreciated
Thanks
#include <stdio.h>
#include <math.h>
int main(void){
int Num;
int N;
scanf("%d", &Num);
int x = floor(log2(Num)) +1;
int a[x];
N = Num;
for(size_t i=0;i<x;i++){
if(Num%2 == 0){
a[i]=0;
}else{
a[i]=1;
}
Num /= 2;
}
printf("%d in base 2 is ",N);
for(int i=x-1; i>=0;i--){
printf("%d",a[i]);
}
return 0;
}
I think the above code works fine for what you need (although it's not the best way to code this program).
In line 7 of your code, you defined x as 0; so, in line 8, the length of your array is 0 – and that's not what we need.
At the end, when you want to output the result, you only output the xth element of your array. Instead, we want to output every element that we stored. (I used i-- because, if I did not, the binary of Num would be reversed.)

I need help creating a program in c that prints average and count of user inputed values

This program must fill a constant array of doubles with user inputs. It must keep count of all digits excluding chars when they are input. 0s count. After compilation it will accept inputs but the program immediately terminates. Right now it will only output the average but the count should be tracked as of now. I'm unfamiliar with c so any help would be appreciated.
#include <stdio.h>
#define SIZE 1000
double avgNoZero(double array[], int size);
int main (int argc, char **argv) {
double array[SIZE];
double number;
double average;
int count = 0;
while (scanf("%lf", & number == 1) && (count < SIZE)) { //I'm receving warnings about number being an int
array[count++] = number;
}
average = avgNoZero(array, count);
printf("%f\n", average);
return 0;
}
double avgNoZero(double array[], int size) {
int i;
//int count = 0;
double sum = 0;
for(i = 0; i < size; i++) {
sum += array[i];
/*if (array[count] != 0 ) { //I'm unsure where the part that checks for non zero should be.
sum += array[i];
} */
}
return sum / size;
}
At least this one problem
// while (scanf("%lf", & number == 1) && (count < SIZE))
while (scanf("%lf", & number) == 1 && (count < SIZE))
Good that OP has some warnings enabled and reported them.
I'm receving warnings about number being an int

Rand() not generating random variables in C

I've been trying to apply all advices found in this site but none seems to be working.
For the first part of the code I need to fill an array with random numbers (0 or 1) to simulate an epidemic spreading, but the array obtained is not the desired one at all... this is the code I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
int N, BC, t, T, i, v[N];
float b, g, p, r;
/*Variable values initialization*/
printf("Enter infection probability:\n");
scanf("%f", &b);
printf("Enter the number of individuals:\n");
scanf("%d", &N);
printf("Enter the number of time steps:\n");
scanf("%d", &T);
printf("Periodic boundary contitions? (Y:1 / N:0)\n");
scanf("%d", &BC);
/*First set of individuals*/
srand(time(NULL));
for(i = 0; i < N; i++){
v[i] = (rand()/RAND_MAX);
}
/*Check if array properly initialized*/
printf("Initial array:\n" );
for(i = 0; i < N; i++){
printf("%d-", v[i]);
}
The outcome I expected for the array was something like: 1-0-1-1-0-0-0-..., but I always get the following one:
Initial array:
0-0-2-15-0-0-0-0-0-0-
What am I doing wrong?
Thanks a million!
You should declare v[N] after
printf("Enter the number of individuals:\n");
scanf("%d", &N);
otherwise its size will be random since N isn't initialized when the memory allocated for v[] based on N is set.
If you want just 0 or 1 you should use a modulo:
srand(time(NULL));
for(i = 0; i < N; i++){
v[i] = (rand() % 2);
}
all the even values generated by rand will become 0 and all the odd values will become 1

Why is the program returning the wrong answer?

I'm just starting out learning C so I have no idea what i'm doing. I was writing a program to add the multiples of a number together (i.e. x + 10x + 100x ...) according to a variable k. n is the number to add/multiply. Can someone tell me what I am doing wrong in this? with input n being 12 and input k being 3, it should output 13332 but instead outputs 13200. Thanks!
#include <stdio.h>
int main() {
int n;
int k;
scanf("%d", &n);
scanf("%d", &k);
int i = 0;
int t;
while (i < k) {
t = n + (n * 10);
n = n * 10;
i++;
}
printf("%d", t);
}
You set the variable t instead of adding to it.
Use += to add the calculated amount.
You can also add only n, as n * 10 would be added next iteration (if it needs to).
You should also set t to 0, because currently it isn't initialized and will hold an unpredictable garbage value.
#include <stdio.h>
int main() {
int n;
int k;
scanf("%d", &n);
scanf("%d", &k);
int i = 0;
int t = 0;
while (i < k) {
t += n; // See here?
n = n * 10;
i++;
}
printf("%d", t);
}
Besides, for clarity, I'd suggest you to:
make variable names more descriptive - total instead of t, etc.
print input messages ("Please insert...") - they're better for the user and also make the use of n and k more bright, even if you don't change them to things like amount or initialNumber
With t = n + (n * 10);, you consider n twice with each run.
Just write:
int main() {
int n;
int k;
scanf("%d", &n);
scanf("%d", &k);
int i = 0;
int t = 0;
while (i < k) {
t = n + (t * 10);
i++;
}
printf("%d", t);
}
Note that t needs to be initialized, i.e. int t = 0, because otherwise expression t = n + (t * 10) would lead to undefined behaviour.

C - why is arr[0] showing as 32767

Following is just one section on one code.
t is test case number and then i have integer n for each t.
i want to break integer to digits and store in array and then print each element of array.
input
1
45
expected output
5
4
actual output
32767
0
code
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,n1,tmp,in,len,j;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int arr[]={};
n1=n;
in=0;
len=0;
while(n1>0)
{
tmp=n1%10;
arr[in]=tmp;
len++;
n1=n1/10;
in++;
}
for(j=0;j<len;j++)
{
printf("%d\n",arr[j]);
}
}
}
The problem is with your definition of int arr[]={}; which creates an empty array without space for storage. You are better off always defining a maximum array size, unless dynamically allocating. Fixing that issue (along with initializing all values) takes care of the issue.
The following is just one approach to correcting the issue. It defines a maximum number of array elements MAXVALUES of 128. It also adds prompts to orient the user to the data requested, and prevents the trailing newline from your first use of scanf from being read as the input for 'n':
#include <stdio.h>
#include <stdlib.h>
#define MAXVALUES 128
int main () {
int t = 0;
int n = 0;
int n1 = 0;
int tmp = 0;
int in = 0;
int len = 0;
int j = 0;
printf ("\n Enter the number of numbers to convert: ");
scanf ("%d%*c", &t);
while (t--) {
printf ("\n Enter the number 'n' : ");
scanf ("%d%*c", &n);
int arr[MAXVALUES] = {0};
in = 0;
len = 0;
n1 = n;
while (n1 > 0) {
tmp = n1 % 10;
arr[in] = tmp;
len++;
n1 = n1 / 10;
in++;
}
for (j = 0; j < len; j++) {
printf ("%d\n", arr[j]);
}
}
return 0;
}
output:
$ ./bin/arrayval
Enter the number of numbers to convert: 2
Enter the number 'n' : 12345
5
4
3
2
1
Enter the number 'n' : 56789
9
8
7
6
5
Dynamically Allocate arr based on digits in n
You can dynamically allocate arr to prevent having #define allocate more space than needed (this is kinda like using a sledge-hammer to swat a fly here). It just takes a little more work. Specifically, it takes knowing how many digits are in n before you allocate arr so you can allocate no more memory than needed. Here, the number of digits in n is calculated by the function szitoa and then arr is allocated. This is one approach to that type solution:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* determine number of chars required for string of int i,
does NOT include space for null char (like strlen) */
size_t
szitoa (int val)
{
int it = 0;
int sz = (val > 0) ? 0 : 1; /* provide space of '-' */
val = (val > 0) ? val : -val; /* absolute value */
for (it = 1; it < INT_MAX; it*=10) {
sz++;
if (val >= it && val < (it*10))
break;
}
return sz;
}
int main () {
int t = 0;
int n = 0;
int n1 = 0;
int tmp = 0;
int in = 0;
int len = 0;
int j = 0;
printf ("\n Enter the number of numbers to covert: ");
scanf ("%d%*c", &t);
while (t--) {
printf ("\n Enter the number 'n' : ");
scanf ("%d%*c", &n);
/* dynamically allocate arr and validate */
int *arr = calloc (szitoa (n), sizeof (int));
if (!arr) {
fprintf (stderr, "error: arr allocation failed\n");
exit (EXIT_FAILURE);
}
in = 0;
len = 0;
n1 = n;
while (n1 > 0) {
tmp = n1 % 10;
arr[in] = tmp;
len++;
n1 = n1 / 10;
in++;
}
for (j = 0; j < len; j++) {
printf ("%d\n", arr[j]);
}
if (arr) free (arr); /* free memory allocated to arr */
}
return 0;
}
This should work for you:
#include <stdio.h>
int main() {
int number, numberCount, tmp, count;
printf("Please enter a number:\n>");
scanf("%d", &number);
tmp = number;
for(numberCount = 0; tmp > 0; numberCount++)
tmp /= 10;
int numbers[numberCount];
for(count = (numberCount-1); number > 0; count--) {
numbers[count] = number % 10;
number /= 10;
}
for(count = 0; count < numberCount; count++)
printf("%d digit is: %d\n", count+1, numbers[count]);
return 0;
}
Input:
45
Output:
1 digit is: 4
2 digit is: 5
You are trying to write more integers to your array than you have allocated space for. This code here:
while(n1>0)
{
tmp=n1%10;
arr[in]=tmp; // You initialize the array space to in, which is ambiguous.
len++;
n1=n1/10;
in++; // You increment the array after already initializing space which you can't do in this manner.
}
If you wish to accomplish in expanding your array based on the number of inputs from the user which is also ambiguous - you might think about using dynamic memory.

Resources