Random Number Generating Giving Same Number - c

When writing a program for class, i had to create a random number generator for part of it, and whenever i run it, the random number generator will only generate the same number, that being "293".
I have removed the code that generates the number and placed it in a new program by itself, and it properly generates different numbers. Is here something else in the code that is causing the output to be the same every time?
int main(){
/*generates random number*/
int min = 100;
int max = 999;
int num = rand()%((max+1)-min)+min;
printf("number is: %d\n",num);
int input;
/*takes apart the generated number*/
int digitThree = num % 10 /1;
int digitTwo = num % 100 / 10;
int digitOne = num % 1000 / 100;
printf("Today we will play a game, you take ten guesses of a 3 digit number, and I will tell you which one is a match or a hit\n");
for(int i = 1; i<11; i++){
printf("\nGuess #%d.\n", i);
printf("What is your guess?\n");
scanf("%d", &input);
int inputThree = input % 10 /1;
int inputTwo = input % 100 / 10;
int inputOne = input % 1000 / 100;
/*checks if number is a hit or a match*/
if (inputThree == digitThree )
printf("Numer %d is a match\n", inputThree);
if(inputThree == digitTwo)
printf("Number %d is a hit\n", inputThree);
if(inputThree == digitOne)
printf("Number %d is a hit\n", inputOne);
if(inputTwo == digitThree)
printf("Number %d is a hit\n", inputTwo);
if(inputTwo == digitTwo)
printf("Number %d is a match\n", inputTwo);
if(inputTwo == digitOne)
printf("Number %d is a hit\n", inputTwo);
if(inputOne == digitThree)
printf("Number %d is a hit\n", inputOne);
if(inputOne == digitTwo)
printf("Number %d is a hit\n", inputOne);
if(inputOne == digitOne)
printf("Number %d is a match\n", inputOne);
if(inputOne == digitOne && inputTwo == digitTwo && inputThree == digitThree){
printf("Congrats! You guessed the number %d correctly!\n", num);
return 0;
}
if(i == 10)
printf("Last Guess!!\n");
printf("\n");
}

You have to use srand() function:
#include <time.h>
int main(){
time_t t;
/* Initialization to get random differents numbers each time */
srand((unsigned) time(&t));
/*generates random number*/
int min = 100;
int max = 999;
int num = rand()%((max+1)-min)+min;
printf("number is: %d\n",num);
Link -> https://www.tutorialspoint.com/c_standard_library/c_function_srand.htm

Related

Find two largest numbers in input

I need to make a program that will perform the following task:
Enter N natural numbers. Complete the input with 0. Output the number
of the maximal number.
I have already done this, and you can see the code below:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int i = 0, num, max_place = -1;
int max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num >= max) {
max = num;
max_place = i;
}
i++;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else printf("\nMax number was on %d place, bruh", max_place + 1);
return 0;
}
The teacher then made the task more difficult – the program needs to print the maximum number and the next maximum after it of the entered numbers.
How can I do it?
If you can use arrays and sort use that way. if not, this is in your code
int main(void) {
int i = 0, num, max_place = -1, second_max_place = -1;
int max = -2147483647;
int second_max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num == 0) break;
if (num >= max) {
second_max = max;
second_max_place = max_place;
max = num;
max_place = i;
}
if(num < max && num >= second_max){
second_max = num;
second_max_place = i;
}
i++;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else{
printf("\nMax number was on %d place, bruh", max_place + 1);
printf("\nSecond Max number was on %d place, bruh", second_max_place + 1);
}
return 0;
}

How to get min/max value from 10 numbers with a loop? (C language)

Hi im fairly new in programming and started with C language and now im stuck with loops.
The problem is that I try to write a program that has to get an input value of 10 INT numbers that are greater than 20, and after that the program has to determine which of the numbers is the maximum and which is minimum. at the end it has to calculate the average of all numbers.
So now I managed to get only the average calculation to work correctly, and the main problem is the max/min values.
#include<stdio.h>
void main()
{
//Variables
int num, i = 1, cnt = 0, sum = 0, max = 0, min = 0;
float average;
printf("Enter 10 int numbers greater than 20:\n");
//Input check
while (i <= 10)
{
printf("\n%d) ", i);
scanf("%d", &num);
max = num;
min = num;
if (num <= 20)
{
printf("Wrong number! enter an integer greater than 20:\n");
continue;
}
i++;
sum += num;
cnt++;
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
//Average calculation and output
average = sum / (float)cnt;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average of all numbers is: %.2f\n", average);
}
Here is a quick check game in c that asks for few numbers and then when you enter 0 it shows you the lowest and highest number in the array (number collected)
int main(){
int a, max = 0, min;
char answer;
while(answer != 'n')
{
for(int i = 0; i < 100; i++){
printf("Enter Number:");
if (scanf("%d", &a) == 1)
{
if(a == 0) //check if the input value is 0 then break the loop
break;
else
{
if(a > max)
max = a;
if(a < min)
min = a;
}
}
}
printf("lowest: %d, highest: %d", min, max);
printf("\nWould you like to start over? (j/n): ");
scanf("%s", &answer);
max = 0;
//min=0;
if(answer == 'n')
break;
}
return 0;
}

C loop until 0 is given

I'm trying to make a loop that lets the user enter numbers one by each other and calculate the sum of all those numbers until the user enters 0 as an input. However, my code is running only once and then stops.
#include <stdio.h>
int main(void) {
int i = 0;
int num;
int total = 0;
printf("Give me a number \n");
scanf("%d", num);
if(num < 0 && num > 0){
printf("Give me a number \n");
scanf("%d", num);
total = total + num;
i = i + 1;
}
printf("The total is %d", total);
}
There are no loops in your code
The condition (num < 0 && num > 0) is alway false. A number can't be: less than zero AND greater than zero
Wrong call of scanf
You probably want:
printf("Give me a number \n");
if (scanf("%d", &num) != 1) exit(1);
while(num != 0){
total = total + num;
i = i + 1;
printf("Give me a number \n");
if (scanf("%d", &num) != 1) exit(1);
}
The above solution will exit the program if the user inputs a non-integer, e.g. a letter.
An alternative solution that will end the loop on non-integer input is:
printf("Give me a number \n");
while(scanf("%d", &num) == 1 && num != 0){
total = total + num;
i = i + 1;
printf("Give me a number \n");
}
This last solution can even be written a little more compact - like:
while(printf("Give me a number \n"), scanf("%d", &num) == 1 && num != 0){
total = total + num;
i = i + 1;
}
It's a bit harder to read but avoids duplicated lines.
This is the idiomatic way IMO. There is only one scanf call to scanf and we use break to end the loop prematurely if the user has entered 0.
#include <stdio.h>
int main() {
int i = 0;
int num;
int total = 0;
while (1) // loop forever
{
printf("Give me a number \n");
scanf("%d", &num);
if (num == 0) // if the number is 0
break; // we terminate the loop
total = total + num;
i = i + 1;
}
printf("You entered %d numbers, the total is %d", i, total);
}
Disclaimer:
for brevity there is no error check for scanf which IMO is OK for toy programs.
Otherways the remarks provided by 4386427 in his answer are correct.
Make sure to take the address of the variable (&num) in the scanf() call and add a do{ } while() statement.
int main(){
int i = 0;
int num;
int total =0;
do {
printf("Give me a number \n");
scanf("%d", &num);
total = total + num;
i = i + 1;
} while(num != 0);
printf("The total is %d", total);
}
the problem is in the if statement you are trying to check if the given number (num) is at once greater than 0 and less than 0 which is why the if scope won't be accessed u can use the following if statement
if(num!=0)
this will check if the num is different than zero!
and since you are trying to repeat this bloc until 0 is inserted you have to use a while/dowhile instead.
you have also to pay attention to the scanf because you forgot to specify the pointer of the num variable (scanf("%d", &num);)
In your case, use of while (num != 0) would be more suitable.
int main(){
int i = 0;
int num = 1;
int total = -1;
while (num != 0){
printf("Give me a number \n");
scanf("%d", &num);
total = total + num;
i = i + 1;
}
printf("The total is %d", total);
}

how to find the min/max of values within a file

#include <stdio.h>
int main(void)
{
int num, i, total, average, min, max;
min = num;
max = num;
FILE *ifile;
ifile = fopen("scores.txt", "r");
i = total = 0;
while (fscanf(ifile, "%d", &num) != EOF) {
i++;
total += num;
}
printf("The total of the integers is %d.\n", total);
printf("The number of integers in the file is %d.\n", i);
average = total/i;
printf("The average of the integers is %d.\n", average);
while (fscanf(ifile, "%d", &num) != EOF) {
if (num < min) {
printf ("The minimum is %d\n", min);
} else if (num > max) {
printf ("The maximum is %d\n", max);
}
}
fclose(ifile);
return (0);
}
The part of the code that's wrong is the very end about mins/maxes.
I'm not sure whether to put in a loop for this or to even make min and max variables themselves.
There are at least three issues in your min/max-detection loop:
First, as indicated by chux, min and max are not initialized; hence, when iterating through the numbers, statement if (num < min)... is far from guaranteed to work properly (same for max, of course).
So initialize min with INT_MAX, and initialize max with INT_MIN (both defined in <limits.h>), such that already in the first iteration min and max will be set to values from your file.
Second, the check for if (num < min)... gives you a "local" minimum, i.e. the minimum for all the numbers read so far, but not the "absolute" minimum, as there may come smaller numbers at a later point. So min/max will be valid at the end of the loop, not during the iteration.
Third, if (num < min) ... else if (num > max) is wrong at least if the file contains just one number.
Your code could look like the following:
int min = INT_MAX;
int max = INT_MIN;
while (fscanf(ifile, "%d", &num) != EOF) {
if (num < min)
min = num;
if (num > max)
max = num;
}
// min/max are valid earliest at this point:
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);
// Note that min/max will not be correct if the file does not contain any number;
// Note further, that fscanf(ifile, "%d", &num) != EOF may result in an endless loop if the file contains characters that "%d" will not read as a valid integral value.
// But this is left to the OP for further improvement :-)
Consider the following modification to your code:
#include <stdio.h>
int main(void) {
int num, i, total, average, min, max;
// open file
FILE *ifile = fopen( "scores.txt", "r" );
// if opening file fails, print error message and exit 1
if (ifile == NULL) {
perror("Error: Failed to open file.");
return 1;
}
// initialize i and total to zero.
i = total = 0;
// read values from file until EOF is returned by fscanf,
// or until an error (hence the comparison "== 1")
while(fscanf(ifile, "%d", &num) == 1) {
// In first round of loop, initialize min and max
// to the number being read (num)
// After min/max have been initialized, they can then
// be compared and modified in the second if statement
// in the remaining loop rounds
if (i == 0) {
min = num;
max = num;
total += num;
++i;
continue;
}
if (num < min) {
min = num;
} else if (num > max) {
max = num;
}
total += num;
++i;
}
// initialize average
average = total/i;
// summary
printf("The sum of all integers in file is %d.\n", total);
printf("The number of integers in file is %d.\n", i);
printf("The average of all integers in file is %d.\n", average);
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);
fclose(ifile);
return 0;
}

C FOR Condition

I need to create a simple program which asks for 10 numbers from user and then shows the sum of those numbers or, if the user gives 0 as input, stops and immediately displays the sum of those numbers, and I need to create it only by using a "for" condition. Here is the code:
#include <stdio.h>
int main(){
int num = 0;
for(num = 0; num < 10; num++){
printf("Input a number: \n");
scanf("%d", &num);
if(num == 0){
printf("Sum: %d\n", num);
}
}
printf("Sum: %d\n", num);
getchar();
getchar();
}
It stops only when the number is greater than "10".Whats wrong?
I think you want to do this kind of work with your code.
#include <stdio.h>
int main(){
int num = 0;
int sum=0;
for(num = 0; num < 10; num++){
int i;
printf("Input a number: \n");
scanf("%d", &i);
sum = sum+i;
if(i == 0){
printf("Sum: %d\n", sum);
getchar();
return 0;
}
}
printf("Sum: %d\n", sum);
getchar();
return 0;
}
You are changing the value of the counter inside the for loop. That's why, when you read a value greater than or equal to 10, it will abandon the for loop, since you have the condition num < 10.
Let me tweak the code for you:
#include <stdio.h>
int main(){
int sum = 0;
int i;
int num;
for(i = 0; i < 10; i++){
printf("Input a number: \n");
scanf("%d", &num);
sum += num;
if(num == 0){
break; //means leave the loop
}
}
printf("Sum: %d\n", sum);
getchar();
return 0;
}
I'm using 3 variables:
sum, which is used to store the overall sum.
i, which is used as the for loop counter.
num, which is used to store the current number given by the user.
First of all, I'm waiting for an input:
printf("Input a number: \n");
scanf("%d", &num);
Now, the input is stored in num, so I'm upgrading the sum, to add the new value:
sum += num;
The I check if the current number is zero; in that case I'll just leave the loop:
if(num == 0){
break;
}
The problem in your code is, you're using the same variable num both as counter and for taking user input which is breaking the logic in for loop.
Use another variable for taking user input.
Also, you've to have a break statement to discontinue the for loop once you've got the breaking criteria.
Note: as I mentioned in my comments, there is no logic for Sum.
Check the below code.
#include <stdio.h>
int main(){
int num = 0;
int sum = 0; //to hold the sum
int input = 0;
for(num = 0; num < 10; num++){
printf("Input a number: \n");
scanf("%d", &input);
sum += input; // yoo-hoo, time to add-up
if(input == 0){
printf("Sum: %d\n", sum);
break; // time to say bye-bye to for loop
}
}
if (num == 10) //only print if not printed previously
printf("Sum: %d\n", sum);
return 0;
}

Resources