Random function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Random function

Is it possible in C to use the random function to generate different questions to ask the user, from the different questions functions I’ve made? (I’m trying to do this for the quiz game I’m developing, so when they choose all it will display random questions I’ve already written in the other functions)😅

29th Dec 2018, 9:38 PM
farhan bhatti
farhan bhatti - avatar
3 Answers
+ 1
I don't know that much about c, but there is a function int rand(), which will choose a random intreger between 0 and 32767. With this information, you could write something like this (it's not an actual c program) /*create arrays with the questions and the answers at the same index*/ array questions = ['q1','q2']; array answers = ['a1','a2']; /*the function*/ int random_question(){ /*random intreger between 0 and (in this case) 3 - 1, so that if rand() chooses 30270, it would output 20, ask me if you don't get it*/ int index = int rand() % (amount of questions - 1); /*print the question*/ printf(questions[index]); /*empty variable, not sure if this is possible, otherewise do string ans = "";*/ string ans; /*ask for the user input*/ fgets("%s",&ans); /*I actually had to search this one*/ /*then check if the user has it correct, otherwise show the ans*/ if(ans === answers[index]){ printf("Amazing, that's correct"); } else { printf("Sorry, the answer is: "+answers[index]); } }
29th Dec 2018, 10:37 PM
Roel
Roel - avatar
+ 1
No problem, you're welcome. I found a lot of the stuff on internet, so maybe that might be a tip for the next time
30th Dec 2018, 8:48 PM
Roel
Roel - avatar
0
thanks Roel, i wasnt sure about the rand function, as i havent come acorss it yet, but wanted to use it instead of a loop, ill try and see if your idea works for my quiz game
30th Dec 2018, 8:38 AM
farhan bhatti
farhan bhatti - avatar