How do I get switch() to loop multiple times in C? - c

I have created this fruit machine game. However I would like to loop the output several times before printing a final output that is then scored. To simulate the moving nature of a real slot machine. When I try and loop my switch() statements no output is produced. How would I go about doing this?
#include <stdio.h>
#include <unistd.h>
int main ()
{
int firstReel, secondReel, thirdReel, loop;
// Generating three random numbers
srand(time(NULL));
int rndOne = rand () %4;
int rndTwo = rand () %4;
int rndThree = rand () %4;
// Assigning random numbers to clearer var names
firstReel = rndOne;
secondReel = rndTwo;
thirdReel = rndThree;
// Switch statements for each reel
switch(firstReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
switch(secondReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
switch(thirdReel){
case 0:
printf("Bell\n");
break;
case 1:
printf("Cherry\n");
break;
case 2:
printf("Orange\n");
break;
case 3:
printf("Horseshoe\n");
break;
}
// Win/lose conditions
if (firstReel == secondReel || firstReel == thirdReel || secondReel == thirdReel)
printf("Congratulations! You win!\n");
else
{
printf("Sorry, you lose. Play again? (Y/N)\n");
}
}

use some sort of counter/ looping statement
int i=0;
while(i< 10){
//Your switch statements
i++;
}
As a better programming practice please do include default case/scenario too when the switch input doesn't satisfy any of the cases.. helps in keeping the code structured and avoids any confusion also showing that other values have been taken care of. For ex:
default:
printf("Invalid value entered");
break;

Try using a loop as shown below :
Here I am running the loop for some x number of times.You can run the loop for any number of times you wish to.
int main ()
{
int firstReel;
int i=0;
// Generating three random numbers
srand(time(NULL));
// Assigning random numbers to clearer var names
while(i<7)
{
firstReel = rand () %4;
// Switch statements for each reel
switch(firstReel){
case 0:
printf("Bell ");
break;
case 1:
printf("Cherry ");
break;
case 2:
printf("Orange ");
break;
case 3:
printf("Horseshoe ");
break;
}
i++;
}
}

This will show the reels spinning and slowing to the final pattern (in a console).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SYMBOLS 4
#define REELS 3
#define SPINS 20
char *symbol [SYMBOLS] = {" Bell ", " Cherry ", " Orange ", "Horseshoe "};
int reel [REELS];
int main(int argc, char **argv)
{
int s, r, elap, tix, counts;
srand ((unsigned)time(NULL));
for (s=SPINS; s>0; s--) {
printf ("\r");
for (r=0; r<REELS; r++) {
reel [r] = rand() % SYMBOLS;
printf ("%s", symbol [reel [r]]);
}
tix = clock();
counts = CLOCKS_PER_SEC / s;
do {
elap = clock() - tix;
}
while (elap < counts);
}
printf ("\n");
for (r=1; r<REELS; r++)
if (reel [r] != reel [r-1])
break;
if (r < REELS)
printf ("You lost!\n");
else
printf ("You won!\n");
return 0;
}

Related

Trying to find duplicates in a Struct Array in C

I've attempted to find if the user has inputted a product id value that's a duplicate and if so, it just tells them that it's a duplicate value and then returns to the menu in my switch statement.
The actual result i get, is that after "productsfilled == 0", it won't utilise the For Loops to check for the duplicates and productsfilled will remain at 1. I've looked online and this way of finding duplicates tends to work and i have used it previously in my code, so I don't think that could be the issue.
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <conio.h>
int productsfilled;
struct ProductData{
int product_id;
char product_name[120];
int price;
};
int quiz_5(){
char ch;
int size, input = 0;
struct ProductData products[20];
while(1){
printf("\nWelcome To The Super Mall's Product List. Please Select An Option:\n1. Add Product\n2. Display Product\n3. Delete Product\n");
fflush(stdin);
switch(getchar()){
case '1':
printf("\nPlease Enter Product ID:");
scanf("%d",&products[productsfilled].product_id);
printf("\nPlease Enter Product Name:");
scanf("%s",&products[productsfilled].product_name);
printf("\nPlease Enter Product Price:");
scanf("%d",&products[productsfilled].price);
printf("Productsfilled: %d",productsfilled);
if(productsfilled == 0){
productsfilled = 1;
break;
}
for(int i = 0; i < productsfilled;i++){
for (int j = i + 1; j < productsfilled;j++){
if(products[i].product_id == products[j].product_id){
printf("\nPlease Use Different Product ID");
break;
}else{
printf("test");
productsfilled += 1;
break;
}
}
}
break;
case '2':
while(1){
for(int i = 0;i < productsfilled;i++){
printf("Product ID: %d Product Name: %s Product Price: %d\n",products[i].product_id,products[i].product_name,products[i].price);
}
printf("Please Press Enter To Continue");
fflush(stdin);
if(getchar() == '\n'){
break;
}
}
case '3':
break;
case '\n':
break;
default:
printf("Please Select An Option:\n1. Add Product\n2. Display Product\n3. Delete Product: ");
}
}
}
int main() {
int input = 1;
printf("Welcome to my assignment. Which quiz do you want to run (please input the number of the quiz e.g. for quiz 1, type 1): \n-Quiz 1\n-Quiz 2\n-Quiz 3\n-Quiz 4\n-Quiz 5\n-Quiz 6\n-Quiz 7\n");
while(input == 1){
fflush(stdin);
switch(getchar()){
case '5':
quiz_5();
break;
case '\n':
printf("Welcome to my assignment. Which quiz do you want to run (please input the number of the quiz e.g. for quiz 1, type 1): \n-Quiz 1\n-Quiz 2\n-Quiz 3\n-Quiz 4\n-Quiz 5\n-Quiz 6\n-Quiz 7\n");
getchar();
default:
printf("Invalid Input\n");
} }
return 0;
}
The problem is that you don't increment productsfilled before you enter the loop...therefore, productsfilled is always 1 less than the actual length of your array which means that you don't compare all elements in the array.
Try your program on 2 inputs, both with the same ID. You'll see that you don't compare anything.
You are wrong when using scanf for string input:
scanf("%s",&products[productsfilled].product_name);
You should not use &, you should use as below:
scanf("%119s",products[productsfilled].product_name);
OT, in main function:
switch(getchar()){
case '5':
...
Because getchar() will return int value, so if you want to access to quiz_5, you have to type 35 (ANSCI code) instead of type 5 when you run your program.
char a = '5';
similar to:
int a = 35;

Make a dice rolling game

A normal six-sided dice is thrown six times; the user must guess a number each time the dice
is thrown. If the number matches the guess, the user wins a point. Score 4 points to win.
I'm working on a project to make a dice throwing game. The goal is to guess the number that the dice is going to land on, and to repeat this loop until the user chooses to exit the program. Currently I'm just working on getting the inital stage to work, but for some reason my dice is coming up with an extremely large number and due to my limited understanding of srand I don't know how to fix it, so any help would be greatly appreciated
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int runs, correct, correct_guesses, guess;
srand(time(NULL));
correct_guesses = 0;
int roll = ((rand() % 6) + 1);
printf("Please guess the number the dice will land on\n");
printf("%d", &roll);
scanf("%d", &guess);
{
switch (guess)
{
case '1': correct = 1 == roll; break;
case '2': correct = 2 == roll; break;
case '3': correct = 3 == roll; break;
case '4': correct = 4 == roll; break;
case '5': correct = 5 == roll; break;
case '6': correct = 6 == roll; break;
default: correct = 0; printf("Not a possible outcome\n");
}
if (correct)
{
printf("You guessed correctly!\n");
}
else
printf("You guessed incorrectly\n");
}
}

How to turn integers into string in c programming? (eg. 0 => zero)

How to turn integers into string in c programming? (eg. 0 => zero)
Code Example:
https://onlinegdb.com/BygYM1L9V
#include <stdio.h>
#include <stdbool.h>
int main(int argc, const char * argv[]) {
int input, number, right_digit;
bool isNegative = false;
printf("Insert a number:\n ");
scanf("%d", &input);
// if keyed-in number is negative, make it positive, but remember it was negative
if ( input < 0 ) {
input = input;
isNegative = true;
}
if (isNegative == true){
printf("negative ");
}
number = 0;
// reversing the digits of input and store in number
while ( input ) {
// adds the last digit of input to value from right
number = 10 * number + input % 10;
input /= 10;
}
do {
right_digit = number % 10;
switch (right_digit) {
case 0:
printf("zero ");
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
}
number = number / 10;
} while (number != 0 );
printf("\n");
return 0;
}
Expected result for entering 1230 is one two three zero.
However, this code provides 123 and omits the 0. How do I turn integers into strings?
However, is there a better way of doing it? Is there any other method? C coders, please help
I'd drop the switch for a look-up table. Regarding numbers having to be parsed with % operator "backwards" from ls digit and up, simply store them digit by digit in a separate temporary array to easily re-order them.
void stringify (unsigned int n)
{
const char* LOOKUP_TABLE [10] =
{
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
};
if(n == 0)
{
puts(LOOKUP_TABLE[0]);
return ;
}
int numbers[10]={0}; // assuming UINT_MAX = 4.29 billion = 10 digits
for(int i=0; i<10; i++)
{
numbers[10-i-1] = n%10;
n/=10;
}
bool remove_zeroes = true;
for(int i=0; i<10; i++)
{
if(!remove_zeroes || numbers[i]!=0)
{
remove_zeroes = false;
printf("%s ", LOOKUP_TABLE[numbers[i]]);
}
}
}
Out of your problem a typo in your code : input = input; must be input = -input;
It is easier to work on the number as a string, example :
#include <stdio.h>
int main() {
printf("Insert a number:\n ");
char s[32];
if (fscanf(stdin, "%31s", s) != 1) {
return -1;
}
char * p = s;
if (*p == '-') {
printf("negative ");
p += 1;
}
for (;;) {
switch (*p++) {
case 0:
case '\n':
if ((*s == '-') && (p == (s+2))) {
puts("missing number");
return -1;
}
putchar('\n');
return 0;
case '0':
printf("zero ");
break;
case '1':
printf("one ");
break;
case '2':
printf("two ");
break;
case '3':
printf("three ");
break;
case '4':
printf("four ");
break;
case '5':
printf("five ");
break;
case '6':
printf("six ");
break;
case '7':
printf("seven ");
break;
case '8':
printf("eight ");
break;
case '9':
printf("nine ");
break;
default:
puts(" invalid number");
return -1;
}
}
}
Compilation and executions :
/tmp % gcc -pedantic -Wall -Wextra n.c
vxl15036 /tmp % ./a.out
Insert a number:
0
zero
vxl15036 /tmp % ./a.out
Insert a number:
-1
negative one
vxl15036 /tmp % ./a.out
Insert a number:
12305
one two three zero five
vxl15036 /tmp % ./a.out
Insert a number:
007
zero zero seven
vxl15036 /tmp % ./a.out
Insert a number:
-
negative missing number
vxl15036 /tmp % ./a.out
Insert a number:
a
invalid number
As you see the number is rewritten as it was enter, 0 at left are not removed and -0 is negative zero
It can be fun to write one thousand two hundred thirty four for 1234 ;-)
I made a small change to your program so that it loops through once before to get the number of digits, and then loops through count times for the switch statement.
#include <stdio.h>
#include <stdbool.h>
int main(int argc, const char * argv[]) {
int input, number, right_digit;
bool isNegative = false;
printf("Insert a number:\n ");
scanf("%d", &input);
// if keyed-in number is negative, make it positive, but remember it was negative
if ( input < 0 ) {
input = -input;
isNegative = true;
}
if (isNegative == true){
printf("negative ");
}
int count = 0;
int n = input;
//count the digits
while(n != 0)
{
n /= 10;
++count;
}
number = 0;
// reversing the digits of input and store in number
while ( input ) {
// adds the last digit of input to value from right
number = 10 * number + input % 10;
input /= 10;
}
for(int i = 0; i < count; i++) {
right_digit = number % 10;
switch (right_digit) {
case 0:
printf("zero ");
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
}
number = number / 10;
}
printf("\n");
return 0;
}
I think you use similar logic as this example integrated into your loop, but when you reverse the number the 0's get treated like leading 0's and are ignored. I didn't make any changes to the inside of the loop so that may need to be cleaned up.
test input:
12345000
output:
one two three four five zero zero zero

Gradebook, array not saving

So I'm trying to make a grade book that does everything displayMenu() says. But i cant even get the student ID to save when i go to view the grades. Please Help.
Everything is initialized here
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define EXAMS 100
#define STUDENT 4
void displayArray(float grades[STUDENT][EXAMS]);
void newStudent(float grades[STUDENT][EXAMS]);
void displayStudentAverage(float grades[STUDENT][EXAMS]);
int main() {
float grades[STUDENT][EXAMS];
This is everything the program should do
displayMenu(grades, 0 );
} // end of main;
int displayMenu(float grades[STUDENT][EXAMS]) {
printf("\t \t MENU \t \t");
printf("Enter Corresponding Number\n");
printf("1.Enter New Student\n");
printf("2.Change Existing Grades\n");
printf("3.View All Grades\n");
printf("4.View Average Score Per Student\n");
printf("5.View Average Score Per Exam\n");
printf("6.View Average Score For The class\n");
printf("7.CLEAR GRADEBOOK\n");
printf("8. Save Gradebook\n");
printf("8.Exit\n");
int choice = 0;
scanf("%d", &choice);
switch (choice) {
case 1:
newStudent(grades, 0);
CLS;
displayMenu(grades,0);
break;
case 2:
break;
case 3: displayArray(grades, 0);
CLS;
displayMenu(grades,0);
break;
case 4:
displayStudentAverage(grades, 0);
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
exit(0);
break;
case 9:
exit(0);
break;
default: printf("You Have entered an incorrect number");
PAUSE;
}
}
This is what displays the grades
void displayArray(float grades[STUDENT][EXAMS]) {
printf("%.1f\t", grades[STUDENT][EXAMS]);
}
I'm trying to add the values to the array here
void newStudent(float grades[STUDENT][EXAMS]) {
float addgrade;
printf("Please Enter Student ID: ");
scanf("%f", &grades[STUDENT][EXAMS]);
printf("Enter four exam grades, use comma to split grades");
scanf("%f", addgrade);
grades[STUDENT][EXAMS] += addgrade;
PAUSE;
CLS;
}
void displayStudentAverage(float grades[STUDENT][EXAMS]) {
int sum, loop;
float avg;
sum = avg = 0;
for (loop = 0; loop < 10; loop++) {
sum = sum + grades[loop];
}
avg = (float)sum / loop;
printf("Average of array values is %.2f", avg);
}
First of all, it's always good check the compiler warnings to get some hints to possible bugs...
Here's a list of problems in the code:
no header files included
displayMenu prototype is missing
the grades array is used with inconsistent types (float/int)
with grades[STUDENT][EXAMS] the grades array is accessed out of bounds (for example if you define an array of size 5 you can only access position 0 to 4)
the return type of main needs to be int
the function newStudent has return type void but the code tries to return something with return &grades[STUDENT][EXAMS];
Apart from that, the code should work...

Calling a function in printf in C?

I am a beginner in C programming.
I was writing a simple program to calculate average.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int n, s = 0, num, i;
float avg;
printf("Enter value of total no\n");
scanf("%d", &n);
for (i=1; i<=n; i++)
{
void pri(int i){
switch(i){
case 1:
printf("st");
break;
case 2:
printf("nd");
break;
case 3:
printf("rd");
break;
default:
printf("th");
break;
}
}
printf("Enter %d pri(i) number\n", i);
scanf("%d", &num);
s += num;
}
avg = s / n;
printf("The average is %f",avg);
return 0;
}
But pri(i) is not working as I expected. But later I found another way to do this, so here is the second version of this code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int n, s = 0, num, i;
float avg;
printf("Enter value of total no\n");
scanf("%d",&n);
for (i=1; i<=n; i++)
{
void pri(int i){
switch(i){
case 1:
printf("enter 1st number\n");
break;
case 2:
printf("enter 2nd number\n");
break;
case 3:
printf("enter 3rd number\n");
break;
default:
printf("enter %dth number\n",i);
break;
}
}
pri(i);
scanf("%d", &num);
s += num;
}
avg = s / n;
printf("the average is %f",avg);
return 0;
}
I want to get the results of this second piece of code from the first version.
Can I call functions in printf which are defined somewhere in program?
You cannot tell printf() to call another function in the middle of its execution. printf() expects to receive a formatting string and arguments to replace parts of this string. What you're trying to do (embed a function call in the formatting string) is not possible for a number of reasons.
What you can do is return the string instead of printing it and use it as argument.
const char *pri(int i) {
switch(i) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
printf("enter %d%s number\n", i, pri(i));
C doesn't support nested functions (function defined inside another function). Your code works because your compiler adds support for such functions as an extension. In general, you should probably avoid nesting functions.

Resources