I designed a simple program in c but although it compiles fine, it doesn't work well and I would like to know why.
Perhaps the function getchar doesn't work. It's what I believe. I execute this program in my computer windows 11 in msys2-mingw_86. In the screen everything is fine until i try to modify the array. Then appears in the screen any number everytime i run the program. It's always a different number. Can somebody help me, please ?
I hope someone tell me the correct way in c in windows 11 of to use function "getchar" because I think this is what's wrong.
Thank you.
This is the program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define CLEAR() printf("\033[2J")
#define MOVEUP(x) printf("\033[%dA", (x))
#define MOVEDOWN(x) printf("\033[%dB", (x))
#define MOVELEFT(y) printf("\033[%dD", (y))
#define MOVERIGHT(y) printf("\033[%dC",(y))
#define MOVETO(x,y) printf("\033[%d;%dH", (x), (y))
#define RESET_CURSOR() printf("\033[H")
#define HIDE_CURSOR() printf("\033[?25l")
#define SHOW_CURSOR() printf("\033[?25h")
#define HIGHT_LIGHT() printf("\033[7m")
#define UN_HIGHT_LIGHT() printf("\033[27m")
#define NUM_MAX 6
static void modificacion(int matriz[10][10], int fil, int col)
{
char letras;
int B;
CLEAR();
int x=0;
int y=0;
for (int i=0;i<fil;i++){
x=4;
y=y+1;
for (int j=0;j<col;++j){
MOVETO(y,x-3);
printf("%d",matriz[y-1][(x/4)-1]);
x=x+4;
}
}
x=1;
y=1;
MOVETO(16,2);
printf("2-down,8-up,4-left,6-right,5-insert,1-end");
int letra;
do
{
letra=getchar();
switch (letra){
case 2:
if (y<fil)
{
MOVELEFT(1);
printf("%d",matriz[y-1][(x/4)]);
y=y+1;
}
break;
case 8:
if (y>1)
{
MOVELEFT(1);
printf("%d",matriz[y-1][(x/4)]);
y=y-1;
}
break;
case 4:
if (x>1)
{
MOVELEFT(1);
printf("%d",matriz[y-1][(x/4)]);
x=x-4;
}
break;
case 6:
if (x<((col-1)*4))
{
MOVELEFT(1);
printf("%d",matriz[y-1][(x/4)]);
x=x+4;
}
break;
case 5:
MOVELEFT(1);
printf(" ");
MOVELEFT(4);
scanf("%d",&B);
matriz[y-1][(x/4)]=B;
break;
case 1:
MOVETO(20,10);
printf("If you want to end the modification enter f-end\n");
scanf("%s",letras);
break;
}
MOVETO(15,2);
printf ("value of row %d and column %d is %d \n",y,(x/4)+1,matriz[y-1][(x/4)]);
MOVETO(y,x);
printf("%d",B);
}while(letras!='f');
MOVELEFT(1);
printf(" ");
MOVELEFT(3);
printf("%d",matriz[y-1][(x/4)]);
MOVETO(17,2);
printf("END OF THE MODIFICATION\n");
}
int main(int argc, char **argv)
{
static int matriz[10][10];
int B;
static int fil,col;
register int i,j;
char caracter;
printf (" Enter the number of columns.\n");
scanf("%d", &col);
CLEAR();
printf("Now, enter the square matrix...\n");
sleep(1);
CLEAR();
fil=col;
for (i=0;i<fil;++i) {
for (j=0;j<col;++j) {
MOVETO(2,5);
printf (" Enter the value for the row %d and the column %d.\n",i+1,j+1);
MOVETO(4,5);
printf(" ");
MOVELEFT(6);
HIGHT_LIGHT();
scanf("%d", &B);
matriz[i][j]=B;
MOVETO(i*2+6,j*6+6);
UN_HIGHT_LIGHT();
printf("%d",B);
}
}
printf("\n");
sleep (1);
MOVETO(16,2);
printf(" Do you want to modify the matrix, s-yes/n-no\n");
scanf("%s",&caracter);
if (caracter=='s')
{
modificacion(matriz,fil,col);
}
printf("End of the program");
printf("Press any key\n");
caracter=getchar();
CLEAR();
return 0;
}
Related
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.
I want to make switch case in the switch case and make back switch. if remember we can use if else to make switch case move to the first switch case. thk
this is my current code now thk
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main() {
int a,b;
system("cls");
printf("Cara Membuat daftar Pertanyaan!\n");
printf("1. Matematika\n");
printf("2. Bahasa indonesia\n");
printf("3. Bahasa Inggris\n");
printf("4. Kewarganegaraan\n");
printf("0. Exit \n");
printf("Masukan no dari 1-4 (0) : ");
scanf("%d", &a);
switch(a)
{
case 1 : system("cls");
printf("1. Perkalian\n");
printf("2. Pertambahan\n");
printf("3. Perkurangan\n");
printf("4. Pembagian\n");
printf("5. Kembali \n");
printf("Masukan no dari 1-5 : ");
scanf("%d",&b);
if( b == 5)
{
switch(a);
}
else {
break;
}
break;
default : printf("Error");
}
return 0;
}
Put everything in a while loop, and only allow the loop to run for the Kembali option. You could also implement this as a recursive function, but that can get complicated.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int
main (void)
{
int a;
int b;
int loop = 1;
while (loop) {
loop = 0;
system ("cls");
printf ("Cara Membuat daftar Pertanyaan!\n");
printf ("1. Matematika\n");
printf ("2. Bahasa indonesia\n");
printf ("3. Bahasa Inggris\n");
printf ("4. Kewarganegaraan\n");
printf ("0. Exit \n");
printf ("Masukan no dari 1-4 (0) : ");
scanf ("%d", &a);
switch (a) {
case 0: {
printf ("Exited\n");
break;
}
case 1: {
system ("cls");
printf ("1. Perkalian\n");
printf ("2. Pertambahan\n");
printf ("3. Perkurangan\n");
printf ("4. Pembagian\n");
printf ("5. Kembali \n");
printf ("Masukan no dari 1-5 : ");
scanf ("%d", &b);
if (b == 5) {
loop = 1;
}
break;
}
default: {
printf ("Error\n");
break;
}
}
}
return 0;
}
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;
}
I can't even figure how to make this work!
So I coded this thing right heere, and in the part where it asks for input, I can't type anything! please hhelp T_T
What I'm making is a Question & Answer time program where a user can only answer the question within the alotted time limit.
Here is my code
#include <stdio.h>
#include "engine.h"
void level2(){
system("cls");
printf("Level 2 \n\n\n");
timer();
if ( time_limit >=0 ) {
printf("BOO");
}
}
int level1() {
char answer;
printf("Hello? \n\n");
scanf("%c",&answer);
time_limit = 20;
timer();
}
int rules() {
time_limit = 15;
system("cls");
printf(" Game Rules \n\n");
printf(" 1. You only have 5 seconds to guess what the correct answer for the question! \n");
}
int credits() {
int menu;
printf(" Coded by : \n");
printf("Lady Dianne Vertucci");
}
int main() {
int menu;
printf("TR \n ");
printf("1. Play \n");
printf("2. Credits \n");
scanf("%d",&menu);
switch (menu) {
case 1:
level1();
break;
case 2:
credits();
break;
default:
printf("Please choose a valid option 'tard");
break;
}
getch();
return 0;
}
This is the engine.h
#ifndef _ENGINE_H_
#define _ENGINE_H_
static int time_limit = 0;
extern int time_limit;
static int score = 0;
extern int score;
int timer() {
while (time_limit !=0)
{
time_limit--;
printf("%02d\r",time_limit);
sleep(1000);
}
}
#endif
In function level1() you should change
scanf("%c",&answer);
to
scanf(" %c",&answer);
^
|
space
This will eat up the newline character \n after entering a char and pressing enter.
Wake up sleepy head
Your call sleep(1000) sleeps for 1000 seconds. Suspect you want sleep(1).
Also recommend #haccks suggestion to use " %c".
Use
flushall(); before scanf
Hi I'm trying to make an interactive menu with switch statement in C.
Though I'm unsure of how to trigger a function that has certain arguments.
I'm a total beginner and I'm stumped how to do this.
The function in the switch statement needs the arguments though I would like the function to ask for the numbers. I'm doing this as an assignment and cannot provide the actual code so I made this mock up. Thank you for your help.
Here is an example of code I might use.
#include <stdio.h>
void printMenu()
{
int choice;
do
{
printf("Main Menu:\n");
printf("1) do this\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
function(); /* though this needs the arguments */
break;
}
} while (choice != 7);
int main(void)
{
printMenu();
return 0;
}
void function(int number1, float number2)
{
/*calculation*/
printf("enter your numbers");
/* Not sure how to read the numbers in here */
printf("%d + %d = %d", number1, number2, number1 + number2);
return;
}
If you want the switch to be as minimal as possible then just call another function which takes in input and then calls the function...
case 1:
read_input_and_function()
break;
...
void read_input_and_function(void)
{
printf("Enter your numbers: ");
/* scanf number1, number2 */
function(number1, number2);
}
The function in the switch statement needs the arguments though I
would like the function to ask for the numbers.
How about asking the arguments first , and then calling the function. This way the two arguments can be declared once and be used in other functions of the same switch , but be defined according to the chosen case.
void function1(int, float);
void printMenu()
{
int choice = 0 , num1 = 0;
float num2 = 0;
do
{
printf("Main Menu:\n");
printf("1) do this\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter number 1\n");
scanf("%d",&num1);
printf("\nEnter number 2\n");
scanf("%f",&num2);
function1(num1,num2);
break;
}
} while (choice != 7);
}
#include <stdio.h>
#include <stdlib.h>
#define Pi 3.14159216
/*
*small program of how to create a menu
*/
main ()
{
float degree,radians;
int input;
/*degrees to radians */
float degreesToRadians (float deg)
{
return ((Pi * deg) / 180.0);
}
/*radians to degrees*/
float radiansToDegrees (float rad)
{
return rad * (180 / Pi);
}
void menu ()
{
printf ("\n");
printf ("1. degrees\n");
printf ("2. radians\n");
printf ("3. quit\n");
do
switch (input) {
case 1:
printf ("\n");
printf ("\n");
printf (" Enter value of degrees: ");
scanf ("%f", °ree);
printf ("RADIANS = %f \n\n", degreesToRadians (degree));
menu ();
break;
case 2:
printf ("\n");
printf ("\n");
printf (" Enter value of radians: ");
scanf ("%f", &radians);
printf ("DEGREES = %f \n\n", radiansToDegrees (radians));
menu ();
break;
case 3:
printf (" quiting app \n");
exit (0);
break;
default:
printf ("wrong option\n");
break;
}
while (input != 3);
getchar ();
}
}
menu ();
}