How to print random imported strings from user in C? - c

The assignment is as follows: Write a program that takes in courses from a user, saves them in an array, and then prints out a random course for user to complete first.
For example:
How many courses do you have homework in? 3
Course: Math
Course: English
Course: Computer Science
Math, I choose you!
// Helps a user decide which homework to do first
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
// Prompt the user for the number of courses that they have homework in
int n = get_int("How many courses do you have homework in? ");
// TODO: Declare an array of courses with the correct number of elements
// TODO: Prompt the user for their course names and store it in the array
string courses[n];
for (int i = 0; i < n; i++)
{
courses[i] = get_string("Course: ");
}
return(0);
// Initialize random number generator
// (found info on https://www.tutorialspoint.com/c_standard_library/c_function_rand.htm)
time_t t;
srand((unsigned) time(&t));
// Find a random number
int r = rand() % n;
// TODO: Print out a random course number with index r
printf("%s/n", courses[r]);
}
This is my code above. How do I fix the print statement to print a random string that the user imported?

You're having a problem in your code, you've put return (0); before finishing your work, so your main always exits before printing anything.
it's a \n not /n.

Related

Inputing a value and instead of keeping that information in a array, it changes another var

I made a program and then it didn't worked. As in the other post someone advised me to trying to debug my programs, I learned it and debugged this one. Probably it has some basic errors of writting but that's because I've changed a lot of thing recently to understand what's happening. In third time when I input a value on screen on that loop, it changes my var "i" to that value instead of keeping that number in my array "grade".
First I tried to make it all in one loop, the first one, but as always it didn't help much, and then i wrote the code by this manner as you'll see
#include <stdio.h>
#include <stdlib.h>
int main()
{
int j=0,sum=0,i=0;
int grade[]={0};
for(;j<100;j++){
printf("Type a grade:\t");
scanf("%d",&grade[j]);
if(grade[j]<10||grade[j]>20){
break;
}
}
for(;i<j;i++){
sum=sum+grade[i];
}
float average=sum/j;
printf("The average is: %.2f\n",average);
system("pause");
return 0;
}
The exercicise says that you need to read "x" grades from a student and it needs to be between 10 and 20, if the number is out of this range it stops the loop.After I just need to calculate the average os these grades.I don't really know if my var average is being calculated correctly, cause I didn't could reach over there because of my problem. If you input 11, 12 and 13 it should give to a sum of 36, but gaves me 26, i don't know how.
Erik, you should define your array in a coherent way. To allow the necessary number of elements, try defining a numeric constant. You could use it for both define the number of iterations of your cycle and the size of your grade array. You can also avoid a new cycle to calculate the sum of the array, you can do this operation while reading the grades, using only one for loop. Try this way:
#include <stdio.h>
#include <stdlib.h>
#define MAX_GRADES 100
int main()
{
int j,sum=0,i;
float average;
int grade[MAX_GRADES];
for(j = 0 ; j < MAX_GRADES; j++)
{
printf("Type a grade:\t");
scanf("%d",&i);
if ( (i<10) || (i>20) )
break;
grade[j] = i;
sum += i;
}
if (j > 0)
average = (float)sum/j;
else
average = 0;
printf("The average is: %d, %d, %.2f\n",sum, j, average);
system("pause");
return 0;
}

Printing non duplicate in C array

I was working on a program for my intro to C class (xtra credit assignment) and can't figure out how to discard duplicates numbers on an array. The problem asks to only print non duplicates; so I able to print the first number, compare the following and print if different, I discard the next if a duplicate, but the thing is I've only figured out how to compare the one number it following one, I figured I could do another for loop inside the for loop, but I'm getting super confused and just can't figure it out. I've already submitted my code last week, I've just been working on this trying to figure it out for myself so any help/guidance would be greatly appreciated.
"EDIT: Here's the problem: Use a single-subscripted array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, print it only if it's not a duplicate of a number already read. Provide for the worst case in which all 20 numbers are different. Use the smallest possible array to solve this problem"
Thanks in advance, and any advice on how I'm writing my program would also be appreciated as I'm a total noob, and trying to be a good programmer with as little bad habits as possible.
#include <stdio.h>
#include <stdlib.h>
#define AS 20
void findDuplicate (int af[], int fAS);
int main(){
int a[AS], i , j, k;
int last = 0;
printf("Enter %d numbers between 10 and 100:\n", AS);
for (i = 0; i < AS; i++){
scanf("%d",&a[i] );
if (a[i] >= 10 && a[i] <= 100 ){
continue;
} else {
printf("You must enter values between 10 - 100\n");
i = i -1;
}
}
findDuplicate(a, AS);
system ("pause");
return 0;
}
void findDuplicate (int af[], int fAS){
int c;
printf("You entered ");
for (c=0; c < fAS; c++){
if (af[c] != af[c+1]){
printf("%d ", af[c]);
}
continue;
}
printf("\n");
}
You should first define an Array which can save as many variables as you want ..
Lets say you are comparing for 10-100 which means 91 possible different digits.
so , define array with the size of 91. and then do the scanning in for loop for 91 times to find out if you have that variable entered previously. If not then save it and display it ,else discard it.

Adding Numbers Generated By Random Number Generator in C

before I ask my question I would like to point out that I did look for the answers already, and I didn't find what I was looking for.
Please bear in mind that I am a beginner in terms of programming, so please don't assume that I know everything there is to know.
Right, to the question.
My question is : How do I add together numbers that are created by random number generator ? The difficulty that I have is the fact that the number of randomly generated numbers could be different every time the program is ran. To make it clearer, the amount of randomly generated numbers is dependent on the input from user, eg if the input is 9, the program will generate 9 random numbers. This makes it difficult for me to come up with the idea of how to add the random numbers together and display them.
Here is the source code from my program. I think it is important to mention that the random numbers change every time I run the program, which is how I want them to be ( I used srand() with time, and rand() ). Also, the problem that I have currently is that the program doubles the last randomly generated number instead of adding them all together.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int input;
scanf("%d", &input);
int i;
int roll;
int turn_total;
time_t t;
int sum;
srand((unsigned) time(&t)); // the seed for the random number generator based on the current time
for( i = 0; i < input; i++)
{
roll = (rand() % 6 + 1); // random number generator
sum = roll+roll; // only dubbling the last roll for some reason = /
printf("You Rolled : %d\n", roll);
}
printf("The Total Turn Score is : %d", sum);
}
Any help, ideas or clues would be greatly appreciated.
Yo need to initialize sum first also you are not adding properly.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int input;
scanf("%d", &input);
int i;
int roll;
time_t t;
int sum = 0;
srand((unsigned) time(&t)); // the seed for the random number generator based on the current time
for( i = 0; i < input; i++)
{
roll = (rand() % 6 + 1); // random number generator
sum += roll; // only dubbling the last roll for some reason = /
printf("You Rolled : %d\n", roll);
}
printf("The Total Turn Score is : %d", sum);
}
Use
srand( ( unsigned int )time( NULL ) );
and initialize variable sum. For example
long long int sum = 0;
//...
sum += roll;
//...
printf( "The Total Turn Score is : %lld", sum );
Your program is doubling the number that was generated because that's what you tell it to do in this line:
sum = roll+roll;
Instead, you need to add the current roll to the current value of sum:
sum = sum + roll;
And you need to initialize sum to 0 so that you start by adding just the first roll.
Think about it like rolling a dice multiple times and writing down what it was each time. You roll it once and get a 3, so you write down 3. You roll it again and get a 6, so you add 6 to the previous roll to get 9. You roll again and get 2, so you add 2 to 9 and get 11, and so on. The variable sum is where you write down the new number after every roll, but you're adding to what you wrote down before.
The way you had it before, you were completely disregarding the previous rolls. rolls in the loop only refers to the latest roll that you performed, and since the loop ends at some point, sum will be left as the sum of the last value of roll. This is why you were getting double the last number.
replace
sum = roll+roll
with
sum = roll+sum;

Random password generator same string

This is my first C program and I wanted to make a random password, but every time I run the program, it generates the same string. (always generates "pkDHTxmMR1...") This is not going to actually be used so the security of rand() doesn't really matter to me. Why would it output the same string every time that I run it?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//this is a program to generate a random password
int main()
{
int counter = 0;
srand(time(NULL));
char randChar;
int passwordLength;
printf("Type in a password Length \n");
scanf("%d", &passwordLength);
while(counter < passwordLength)
{
//seed random based on time
srand(time(NULL));
randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
printf("%c", randChar);
counter++;
}
return 0;
}
Oh dear. Everybody has got the answer wrong, including me before I tried the questioner's code for myself.
In fact, yes there should be no call to srand() in the loop because it will reseed the random number generator on each iteration. However, there should also be no call to srand() outside the loop either because the function used to generate actual random numbers is random() not rand(). The correct code is
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int counter = 0;
srandom(time(NULL)); // Correct seeding function for random()
char randChar;
int passwordLength;
printf("Type in a password Length \n");
scanf("%d", &passwordLength);
while(counter < passwordLength)
{
randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
printf("%c", randChar);
counter++;
}
printf("\n"); // Stops the output from being on the same line as the prompt
return 0;
}
Your loop takes less than a second to run.
Therefore, time(NULL) always returns the same value, so your random numbers all have the same seed.
Don't do that.
The standard:
The srand function uses the argument as a seed for a new sequence of
pseudo-random numbers to be returned by subsequent calls to rand. If
srand is then called with the same seed value, the sequence of
pseudo-random numbers shall be repeated.
It is very likely that the time_t on your system is based on seconds or something like that. But the execution time between srand() calls is far far less than one second, so you keep feeding it the same seed value.
Always just call srand() once in your whole program.

power int number while in loop

OK, so my task is to get a single digit from a natural number and sum the square numbers (Using function while, which means no arrays yet :S). For instance I type 123 so sum=1*100+2*10+3*1; However the problem is that the digit could be whatever. My problem is that the power rises with int but its like so - 1, 10, 99, 1000. The problem for me is 99. Also answer is looping but I'll fix it later. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int N,
number=0,
answer=0,
a=1,
i=0;
printf("Type natural number: ");
scanf("%d",&N);
while(N>i)
{
number=N%10;
N/=10;
a=10;
a=pow(a,i);
answer+=number*number*a;
printf("%d\n", answer);
i++;
}
return 0;
}
Try it the other way around. Don't make the input an integer. Start at the beginning of the stream, get the character, convert it to an int 'number'. Then do
answer = 10 * answer;
answer += (number * number);
This will build up your answer little by little. Note that I am not sure that this is what you are asking for due to your example not seeming to match the code.
Let me know if this is off-base and I will update it.

Resources