How to use various calculations for various inputs - c

I am writing a program that will let the user enter various types of information to calculate the expenses for a vacation trip.
I am given the costs of three different forms of transportation, as well as four source cities and four destination cities.
The three forms of travel are air, train and bus, while the source cities are Baltimore, Chattanooga, Nashville, and Pasadena. The destination cities are Denver, Madison, Clarksville, and Knoxville.
I need to be able to calculate the cost to travel between each source and each destination city depending on what the user enters (form of travel, and each city).
Now, my first guess was to write a very very long if/else if statement for each condition. I tried it and it doesn't seem to work either because it is so long or maybe I messed up somewhere.
if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'D', 'd')
transportation_price = 5000;
else if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'M', 'm')
transportation_price = 4000;
else if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'K', 'k')
transportation_price = 5000;
else if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'C', 'c')
transportation_price = 2500;
else if(transportation_type == 'T', 't' && src_city == 'B', 'b' && dest_city == 'D', 'd')
transportation_price = 2500;
else if(transportation_type == 'T', 't' && src_city == 'B', 'b' && dest_city == 'M', 'm')
transportation_price = 2000;
else if(transportation_type == 'T', 't' && src_city == 'B', 'b' && dest_city == 'K', 'k')
transportation_price = 2500;
else if(transportation_type == 'T', 't' && src_city == 'B', 'b' && dest_city == 'C', 'c')
transportation_price = 800;
else if(transportation_type == 'B', 'b' && src_city == 'B', 'b' && dest_city == 'D', 'd')
transportation_price = 2000;
else if(transportation_type == 'B', 'b' && src_city == 'B', 'b' && dest_city == 'M', 'm')
transportation_price = 1000;
else if(transportation_type == 'B', 'b' && src_city == 'B', 'b' && dest_city == 'K', 'k')
transportation_price = 2000;
else if(transportation_type == 'B', 'b' && src_city == 'B', 'b' && dest_city == 'C', 'c')
transportation_price = 2000;
else if(transportation_type == 'A', 'a' && src_city == 'C', 'c' && dest_city == 'D', 'd')
transportation_price = 2500;
else if(transportation_type == 'A', 'a' && src_city == 'C', 'c' && dest_city == 'M', 'm')
transportation_price = 4000;
else if(transportation_type == 'A', 'a' && src_city == 'C', 'c' && dest_city == 'K', 'k')
transportation_price = 4000;
else if(transportation_type == 'A', 'a' && src_city == 'C', 'c' && dest_city == 'C', 'c')
transportation_price = 6000;
else if(transportation_type == 'T', 't' && src_city == 'C', 'c' && dest_city == 'D', 'd')
transportation_price = 500;
else if(transportation_type == 'T', 't' && src_city == 'C', 'c' && dest_city == 'M', 'm')
transportation_price = 2300;
else if(transportation_type == 'T', 't' && src_city == 'C', 'c' && dest_city == 'K', 'k')
transportation_price = 1600;
else if(transportation_type == 'T', 't' && src_city == 'C', 'c' && dest_city == 'C', 'c')
transportation_price = 2000;
else if(transportation_type == 'B', 'b' && src_city == 'C', 'c' && dest_city == 'D', 'd')
transportation_price = 600;
else if(transportation_type == 'B', 'b' && src_city == 'C', 'c' && dest_city == 'M', 'm')
transportation_price = 1300;
else if(transportation_type == 'B', 'b' && src_city == 'C', 'c' && dest_city == 'K', 'k')
transportation_price = 1400;
else if(transportation_type == 'B', 'b' && src_city == 'C', 'c' && dest_city == 'C', 'c')
transportation_price = 1700;
else if(transportation_type == 'A', 'a' && src_city == 'N', 'n' && dest_city == 'D', 'd')
transportation_price = 5000;
else if(transportation_type == 'A', 'a' && src_city == 'N', 'n' && dest_city == 'M', 'm')
transportation_price = 2500;
else if(transportation_type == 'A', 'a' && src_city == 'N', 'n' && dest_city == 'K', 'k')
transportation_price = 4000;
else if(transportation_type == 'A', 'a' && src_city == 'N', 'n' && dest_city == 'C', 'c')
transportation_price = 4500;
else if(transportation_type == 'T', 't' && src_city == 'N', 'n' && dest_city == 'D', 'd')
transportation_price = 1500;
else if(transportation_type == 'T', 't' && src_city == 'N', 'n' && dest_city == 'M', 'm')
transportation_price = 900;
else if(transportation_type == 'T', 't' && src_city == 'N', 'n' && dest_city == 'K', 'k')
transportation_price = 1500;
else if(transportation_type == 'T', 't' && src_city == 'N', 'n' && dest_city == 'C', 'c')
transportation_price = 1700;
else if(transportation_type == 'B', 'b' && src_city == 'N', 'n' && dest_city == 'D', 'd')
transportation_price = 1400;
else if(transportation_type == 'B', 'b' && src_city == 'N', 'n' && dest_city == 'M', 'm')
transportation_price = 700;
else if(transportation_type == 'B', 'b' && src_city == 'N', 'n' && dest_city == 'K', 'k')
transportation_price = 1000;
else if(transportation_type == 'B', 'b' && src_city == 'N', 'n' && dest_city == 'C', 'c')
transportation_price = 1300;
else if(transportation_type == 'A', 'a' && src_city == 'P', 'p' && dest_city == 'D', 'd')
transportation_price = 5000;
else if(transportation_type == 'A', 'a' && src_city == 'P', 'p' && dest_city == 'M', 'm')
transportation_price = 4500;
else if(transportation_type == 'A', 'a' && src_city == 'P', 'p' && dest_city == 'K', 'k')
transportation_price = 3000;
else if(transportation_type == 'A', 'a' && src_city == 'P', 'p' && dest_city == 'C', 'c')
transportation_price = 4500;
else if(transportation_type == 'T', 't' && src_city == 'P', 'p' && dest_city == 'D', 'd')
transportation_price = 2000;
else if(transportation_type == 'T', 't' && src_city == 'P', 'p' && dest_city == 'M', 'm')
transportation_price = 1900;
else if(transportation_type == 'T', 't' && src_city == 'P', 'p' && dest_city == 'K', 'k')
transportation_price = 1200;
else if(transportation_type == 'T', 't' && src_city == 'P', 'p' && dest_city == 'C', 'c')
transportation_price = 1700;
else if(transportation_type == 'B', 'b' && src_city == 'P', 'p' && dest_city == 'D', 'd')
transportation_price = 1400;
else if(transportation_type == 'B', 'b' && src_city == 'P', 'p' && dest_city == 'M', 'm')
transportation_price = 1300;
else if(transportation_type == 'B', 'b' && src_city == 'P', 'p' && dest_city == 'K', 'k')
transportation_price = 800;
else if(transportation_type == 'B', 'b' && src_city == 'P', 'p' && dest_city == 'C', 'c');
transportation_price = 1300;
I use chars to symbolize each city and form of transportation. This if/else if statement does not work, as in my output all it gives me is a value of $1300 despite what the user enters.
Is there any way I can shorten this down? Or if I messed up somewhere can someone point it out for me?
Any help is appreciated!

At least this problem: Follow code does not compare transportation_type to 'A' and
transportation_type to 'a'. 1
transportation_type == 'A', 'a' // bad
Instead fold the case.
// transportation_type == 'A', 'a'
toupper((unsigned char)transportation_type) == 'A'
Same for others.
Suggest a one time change before the if().
#include <ctype.h>
transportation_type = toupper((unsigned char) transportation_type);
src_city = toupper((unsigned char) src_city);
dest_city = toupper((unsigned char) dest_city);
// if(transportation_type == 'A', 'a' && src_city == 'B', 'b' && dest_city == 'D', 'd')
if(transportation_type == 'A' && src_city == 'B' && dest_city == 'D')
1 transportation_type == 'A', 'a' uses the comma operator. The result is 'a'. The result of the compare is lost.
Comma operator with && further complicates things. IAC, , is not needed here.

As mentioned previously, use only uppercase selections or convert the selections to the same case. Additionally, you can store the trip combinations in an array to make the code the cleaner.
#include <stdio.h>
#include <math.h>
int main(){
char transportation_type = 'A';
char src_city = 'B';
char dest_city = 'K';
int transportation_price = 0;
if(transportation_type == 'A' && src_city == 'B' && dest_city == 'D')
transportation_price = 5000;
else if(transportation_type == 'A' && src_city == 'B' && dest_city == 'M')
transportation_price = 4000;
else if(transportation_type == 'A' && src_city == 'B' && dest_city == 'K')
transportation_price = 5000;
printf("%i\n",transportation_price);
// better way, store trip combinations in array
char trips[4][3] = {
{'A','B','D'},
{'A','B','M'},
{'A','B','K'},
{'A','B','C'}
};
int cost[4] = {
5000,4000,5000,2500
};
for (int t=0; t<3; t++) {
if(transportation_type == trips[t][0] && src_city == trips[t][1] && dest_city == trips[t][2]) {
transportation_price = cost[t];
break;
}
}
printf("%i\n",transportation_price);
return transportation_price;
}
Output
5000
5000

Related

Problems reading a file and then writing it in another file

So basically this is the code i have to read one file and then encrypt it to another one. The problem i have is that doesn't write anything in the file. Im posting just part of the code because all the code is a big block of code. I thinks its a buffer problem because it doesn't enter in the second while.
char new_array[ROWS+1][COLUMNS+1];
char frase_encriptada[160];
char frase_desencriptada[80];
void xifrar_frase(char frase[80],char matriu_x[7][7], char frase_encriptada[160]){
int i=0;
int j,k,q=0;
while(frase[i] != '\n' && frase[i] !='\0'){
for(j =1;j<=ROWS;j++){
for(k=1;k<=COLUMNS;k++){
if(frase[i] == matriu_x[j][k]){
frase_encriptada[q] = matriu_x[j][0];
q++;
frase_encriptada[q] = matriu_x[0][k];
q++;
}
}
}
i++;
}
printf("\n");
}
void xifrarArxiu(char matriu_x[7][7],char frase[80],char frase_encriptada[160])
{
FILE*fit1;
FILE*fit2;
int i;
fit1 =fopen("txtXifrat.txt","w");
fit2 = fopen("txtDesxifrat.txt","r");
if(fit1 == NULL || fit2 == NULL)
{
printf("Error al obrir un fitxer");
}
else
{
while(fgets(frase,80,fit2)!=NULL)
{
fflush(stdin);
xifrar_frase(frase,new_array,frase_encriptada);
i=0;
while(frase_encriptada[i] !='\0')
{
fprintf(fit1,"%c", frase_encriptada[i]);
i++;
}
}
feof(fit1);
fclose(fit1);
fclose(fit2);
}
}
int main(void) {
int option;
char frase[80];
char array[ROWS][COLUMNS] = {
{'A', 'B', 'C', 'D', 'E', 'F'},
{'G', 'H', 'I', 'J', 'K', 'L'},
{'M', 'N', 'O', 'P', 'Q', 'R'},
{'S', 'T', 'U', 'V', 'W', 'X'},
{'Y', 'Z', ' ', '1', '2', '3'},
{'4', '5', '6', '7', '8', '9'},
};
do
{
MenuOpcions(option);
scanf("%d",&option);
fflush(stdin);
switch (option)
{
case 3:
xifrarArxiu(new_array,frase,frase_encriptada);
break;
case 0:
printf("Sortint del programa \n");
printf("\n");
break;
default:
printf("No hi ha aquesta opcio \n");
printf("\n");
}
}while(option !=0);
return 0;
}

How to simplify large conditional statement

This conditional statement compares letters with numbers according to the keyboard of old button-phones.
In this statement, every if-else condition is the same. How can I shorten this piece of code?
//compares every name and pattern character
//every number represents some letters from latin alphabet
if(lowch >= 97 && lowch <= 99 && pattern[ptrch] == '2'){
ptrch++;
mir++;
}
else if(lowch >= 100 && lowch <= 102 && pattern[ptrch] == '3'){
ptrch++;
mir++;
}
else if(lowch >= 103 && lowch <= 105 && pattern[ptrch] == '4'){
ptrch++;
mir++;
}
else if(lowch >= 106 && lowch <= 108 && pattern[ptrch] == '5'){
ptrch++;
mir++;
}
else if(lowch >= 109 && lowch <= 111 && pattern[ptrch] == '6'){
ptrch++;
mir++;
}
else if(lowch >= 112 && lowch <= 115 && pattern[ptrch] == '7'){
ptrch++;
mir++;
}
else if(lowch >= 116 && lowch <= 118 && pattern[ptrch] == '8'){
ptrch++;
mir++;
}
else if(lowch >= 119 && lowch <= 122 && pattern[ptrch] == '9'){
ptrch++;
mir++;
}
else if(lowch == '+' && pattern[ptrch] == '0'){
ptrch++;
mir++;
}
else{
ptrch = 0;
mir = 0;
}
}
**ptrch- pattern char
*mir - matches in a row
Define a macro that encapsulates the comparisons, and then use a single condition with ||.
#define MATCH(start, end, ch) (lowch >= start && lowch <= end && pattern[ptrch] == ch)
if (MATCH('a', 'c', '2') ||
MATCH('d', 'f', '3') ||
MATCH('g', 'i', '4') ||
MATCH('j', 'l', '5') ||
MATCH('m', 'o', '6') ||
MATCH('p', 's', '7') ||
MATCH('t', 'v', '8') ||
MATCH('w', 'z', '9') ||
MATCH('+', '+', '0')) {
ptrch++;
mir++;
} else {
ptrch = 0;
mir = 0;
}
Another option would be to use an array of structures.
struct key {
char start,
char end,
char ch
} keys[] = {
{'a', 'c', '2'},
{'d', 'e', '2'},
...
{'+', '+', '0'}
};
bool found = false;
for (int i = 0; i < sizeof keys/sizeof keys[0]; i++) {
if (lowch >= keys[i].start && lowch <= keys[i].end && pattern[ptrch] == keys[i].ch) {
ptrch++;
mir++;
found = true;
break;
}
if (!found) {
ptrch = 0;
mir = 0;
}
A solution you might consider is to map the letters in an array.
// . . . . . . . . . . abcdefghijklmnopqrstuvwxyz
const char* numbers = "22233344455566677778889999";
char digit = (lowch >= 'a' && lowch <= 'z') ? numbers[lowch - 'a'] : 0;
if (digit == pattern[ptrch]) {
ptrch++;
mir++;
}
else if(lowch == '+' && pattern[ptrch] == '0') {
ptrch++;
mir++;
}
else {
ptrch = mir = 0;
}
Or (slightly overkill) you could build a full table to handle any character...
// Build the table once
char dialpad[1 << CHAR_BIT] = { 0 };
const unsigned char *map_from = "abcdefghijklmnopqrstuvwxyz+";
const char *map_to = "222333444555666777788899990";
for (int i = 0; map_from[i]; i++) dialpad[map_from[i]] = map_to[i];
// Later on...
if (dialpad[(unsigned char)lowch] == pattern[ptrch]) {
ptrch++;
mir++;
}
else {
ptrch = mir = 0;
}
All your characters (except the plus sign) are lower-case letters. In ASCII, these letters are in a contiguous range. You can therefore use an array to map lower-case letters to a number code:
// abcdefghijklmnopqrstuvwxyz
const char code[26] = "22233344455566677778889999";
if (lowch >= 'a' && lowch <= 'z' && code[lowch - 'a'] == pattern[ptrch]) {
ptrch++;
mir++;
} else if (lowch == '+' && pattern[ptrch] == '0') {
ptrch++;
mir++;
} else{
ptrch = 0;
mir = 0;
}
Before accessing the array, you must check whether lowch is a valid lower-case letter. The plus sign must be treated as special case here. (But you could make the array cover the whole 7-bit ASCII range, where the characters that don't have a umber code have a special value, perhaps '\0'.)

Trying to poll for a MSP430's Keypad Input

I'm working on a really simplified version of space invaders. I generate some aliens then as time goes on I lower them closer to the bottom of a screen which I'm just using arrays for. I've got it generating and lowering the invaders but when I tried to hit the keypad button to delete an alien it was ignored. I believe its because I'm not constantly looking for the Keypad's input so my checkInput() function isn't doing what it should do. I wanted to poll for it but I am not sure how or where I should do it. Any help would be appreciated.
#include <msp430.h>
#include "peripherals.h"
#include <stdlib.h>
// Function Prototypes
void swDelay(char numLoops);
void countDown();
//void speedCheck();
void generateAliens();
void inputCheck();
void displayAliens();
void initLeds(void);
// Declare globals here
int game;
//int win;
//int turn;
//int levelSpeed;
char arrAliens0[5] = {' ', ' ', ' ', ' ', ' '};
char arrAliens1[5] = {' ', ' ', ' ', ' ', ' '};
char arrAliens2[5] = {' ', ' ', ' ', ' ', ' '};
char arrAliens3[5] = {' ', ' ', ' ', ' ', ' '};
char arrAliens4[5] = {' ', ' ', ' ', ' ', ' '};
char arrAliens5[5] = {' ', ' ', ' ', ' ', ' '};
char arrTempAliens1[5];
char arrTempAliens2[5];
char arrTempAliens3[5];
char arrTempAliens4[5];
char arrTempAliens5[5];
void main(void)
{
//unsigned char ret_val = 0x0F;
unsigned char currKey=0;
// Define some local variables
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
// Useful code starts here
initLeds();
configDisplay();
configKeypad();
while (1) // Forever loop
{
GrClearDisplay(&g_sContext); // Clear the display
while (getKey() != '*')
{
// *** Intro Screen ***
GrStringDrawCentered(&g_sContext, "Space Invaders!", AUTO_STRING_LENGTH, 48, 30, TRANSPARENT_TEXT);
GrStringDrawCentered(&g_sContext, "Press '*' to", AUTO_STRING_LENGTH, 48, 50, TRANSPARENT_TEXT);
GrStringDrawCentered(&g_sContext, "Start the Game", AUTO_STRING_LENGTH, 48, 65, TRANSPARENT_TEXT);
GrFlush(&g_sContext);
}
currKey = getKey();
if (currKey == '*')
{
game = 1;
//turn = 0;
countDown();
while (game == 1)
{
//speedCheck();
generateAliens();
inputCheck();
//displayAliens();
//turn++;
}
GrClearDisplay(&g_sContext);
GrStringDrawCentered(&g_sContext, "You Lose!", AUTO_STRING_LENGTH, 48, 45, TRANSPARENT_TEXT);
GrFlush(&g_sContext);
swDelay(3);
}
} // end while (1)
} //end main
void countDown()
{
//3 Count
GrClearDisplay(&g_sContext);
GrStringDrawCentered(&g_sContext, "3", AUTO_STRING_LENGTH, 48, 45, TRANSPARENT_TEXT);
GrFlush(&g_sContext);
swDelay(3);
GrClearDisplay(&g_sContext);
//2 Count
GrStringDrawCentered(&g_sContext, "2", AUTO_STRING_LENGTH, 48, 45, TRANSPARENT_TEXT);
GrFlush(&g_sContext);
swDelay(3);
GrClearDisplay(&g_sContext);
//1 Count
GrStringDrawCentered(&g_sContext, "1", AUTO_STRING_LENGTH, 48, 45, TRANSPARENT_TEXT);
GrFlush(&g_sContext);
swDelay(3);
GrClearDisplay(&g_sContext);
}
/*void speedCheck()
{
if (turn <= 3)
{
levelSpeed = 10;
}
else if ((turn > 3) && (turn <= 6))
{
levelSpeed = 8;
}
else if ((turn > 6) && (turn <= 9))
{
levelSpeed = 4;
}
else if ((turn > 9) && (turn <= 12))
{
levelSpeed = 2;
}
else
{
levelSpeed = 1;
}
}*/
void generateAliens()
{
memcpy(arrTempAliens1, arrAliens1, 5);
memcpy(arrTempAliens2, arrAliens2, 5);
memcpy(arrTempAliens3, arrAliens3, 5);
memcpy(arrTempAliens4, arrAliens4, 5);
memcpy(arrTempAliens5, arrAliens5, 5);
memcpy(arrAliens1, arrAliens0, 5);
memcpy(arrAliens2, arrTempAliens1, 5);
memcpy(arrAliens3, arrTempAliens2, 5);
memcpy(arrAliens4, arrTempAliens3, 5);
memcpy(arrAliens5, arrTempAliens4, 5);
/*arrTempAliens1 = arrAliens1;
arrTempAliens2 = arrAliens2;
arrTempAliens3 = arrAliens3;
arrTempAliens4 = arrAliens4;
arrTempAliens5 = arrAliens5;
arrAliens1 = arrAliens0;
arrAliens2 = arrTempAliens1;
arrAliens3 = arrTempAliens2;
arrAliens4 = arrTempAliens3;
arrAliens5 = arrTempAliens4;*/
int a = rand() % 4;
if (a == 0)
{
arrAliens0[0] = '0';
arrAliens0[1] = ' ';
arrAliens0[2] = ' ';
arrAliens0[3] = ' ';
arrAliens0[4] = ' ';
}
else if (a == 1)
{
arrAliens0[0] = '0';
arrAliens0[1] = '1';
arrAliens0[2] = ' ';
arrAliens0[3] = ' ';
arrAliens0[4] = ' ';
}
else if (a == 2)
{
arrAliens0[0] = '0';
arrAliens0[1] = '1';
arrAliens0[2] = '2';
arrAliens0[3] = ' ';
arrAliens0[4] = ' ';
}
else if (a == 3)
{
arrAliens0[0] = '0';
arrAliens0[1] = '1';
arrAliens0[2] = '2';
arrAliens0[3] = '3';
arrAliens0[4] = ' ';
}
else if (a == 4)
{
arrAliens0[0] = '0';
arrAliens0[1] = '1';
arrAliens0[2] = '2';
arrAliens0[3] = '3';
arrAliens0[4] = '4';
}
displayAliens();
}
void inputCheck()
{
unsigned char currKey = getKey();
if ((arrAliens5[0] && arrAliens5[1] && arrAliens5[2] && arrAliens5[3] && arrAliens5[4]) == ' ')
{
if (currKey == '0')
{
if ((currKey == '0') && (arrAliens4[0] == '0'))
{
arrAliens4[0] = ' ';
setLeds(0x30);
}
else if ((currKey == '0') && (arrAliens4[0] != '0') && (arrAliens3[0] == '0'))
{
arrAliens3[0]= ' ';
}
else if ((currKey == '0') && (arrAliens4[0] != '0') && (arrAliens3[0] != '0') && (arrAliens2[0] == '0'))
{
arrAliens2[0] = ' ';
}
else if ((currKey == '0') && (arrAliens4[0] != '0') && (arrAliens3[0] != '0') && (arrAliens2[0] != '0') && (arrAliens1[0] == '0'))
{
arrAliens1[0] = ' ';
}
else if ((currKey == '0') && (arrAliens4[0] != '0') && (arrAliens3[0] != '0') && (arrAliens2[0] != '0') && (arrAliens1[0] != '0') && (arrAliens0[0] == '0'))
{
arrAliens0[0] = ' ';
}
}
if (currKey == '1')
{
if ((currKey == '1') && (arrAliens4[1] == '1'))
{
arrAliens4[1] = ' ';
}
else if ((currKey == '1') && (arrAliens4[1] != '1') && (arrAliens3[1] == '1'))
{
arrAliens3[1]= ' ';
}
else if ((currKey == '1') && (arrAliens4[1] != '1') && (arrAliens3[1] != '1') && (arrAliens2[1] == '1'))
{
arrAliens2[1] = ' ';
}
else if ((currKey == '1') && (arrAliens4[1] != '1') && (arrAliens3[1] != '1') && (arrAliens2[1] != '1') && (arrAliens1[1] == '1'))
{
arrAliens1[1] = ' ';
}
else if ((currKey == '1') && (arrAliens4[1] != '1') && (arrAliens3[1] != '1') && (arrAliens2[1] != '1') && (arrAliens1[1] != '1') && (arrAliens0[1] == '1'))
{
arrAliens0[1] = ' ';
}
}
if (currKey == '2')
{
if ((currKey == '2') && (arrAliens4[2] == '2'))
{
arrAliens4[2] = ' ';
}
else if ((currKey == '2') && (arrAliens4[2] != '2') && (arrAliens3[2] == '2'))
{
arrAliens3[2]= ' ';
}
else if ((currKey == '2') && (arrAliens4[2] != '2') && (arrAliens3[2] != '2') && (arrAliens2[2] == '2'))
{
arrAliens2[2] = ' ';
}
else if ((currKey == '2') && (arrAliens4[2] != '2') && (arrAliens3[2] != '2') && (arrAliens2[2] != '2') && (arrAliens1[2] == '2'))
{
arrAliens1[2] = ' ';
}
else if ((currKey == '2') && (arrAliens4[2] != '2') && (arrAliens3[2] != '2') && (arrAliens2[2] != '2') && (arrAliens1[2] != '2') && (arrAliens0[2] == '2'))
{
arrAliens0[2] = ' ';
}
}
if (currKey == '3')
{
if ((currKey == '3') && (arrAliens4[3] == '3'))
{
arrAliens4[3] = ' ';
}
else if ((currKey == '3') && (arrAliens4[3] != '3') && (arrAliens3[3] == '3'))
{
arrAliens3[3]= ' ';
}
else if ((currKey == '3') && (arrAliens4[3] != '3') && (arrAliens3[3] != '3') && (arrAliens2[3] == '3'))
{
arrAliens2[3] = ' ';
}
else if ((currKey == '3') && (arrAliens4[3] != '3') && (arrAliens3[3] != '3') && (arrAliens2[3] != '3') && (arrAliens1[3] == '3'))
{
arrAliens1[3] = ' ';
}
else if ((currKey == '3') && (arrAliens4[3] != '3') && (arrAliens3[3] != '3') && (arrAliens2[3] != '3') && (arrAliens1[3] != '3') && (arrAliens0[3] == '3'))
{
arrAliens0[3] = ' ';
}
}
if (currKey == '4')
{
if ((currKey == '4') && (arrAliens4[4] == '4'))
{
arrAliens4[4] = ' ';
}
else if ((currKey == '4') && (arrAliens4[4] != '4') && (arrAliens3[4] == '4'))
{
arrAliens3[4]= ' ';
}
else if ((currKey == '4') && (arrAliens4[4] != '4') && (arrAliens3[4] != '4') && (arrAliens2[4] == '4'))
{
arrAliens2[4] = ' ';
}
else if ((currKey == '4') && (arrAliens4[4] != '4') && (arrAliens3[4] != '4') && (arrAliens2[4] != '4') && (arrAliens1[4] == '4'))
{
arrAliens1[4] = ' ';
}
else if ((currKey == '4') && (arrAliens4[4] != '4') && (arrAliens3[4] != '4') && (arrAliens2[4] != '4') && (arrAliens1[4] != '4') && (arrAliens0[4] == '4'))
{
arrAliens0[4] = ' ';
}
}
}
else if ((arrAliens5[0] | arrAliens5[1] | arrAliens5[2] | arrAliens5[3] | arrAliens5[4]) != ' ')
{
game = 0;
}
}
void displayAliens()
{
GrClearDisplay(&g_sContext);
GrStringDrawCentered(&g_sContext, arrAliens0, 5, 48, 5, TRANSPARENT_TEXT);
GrStringDrawCentered(&g_sContext, arrAliens1, 5, 48, 25, TRANSPARENT_TEXT);
GrStringDrawCentered(&g_sContext, arrAliens2, 5, 48, 45, TRANSPARENT_TEXT);
GrStringDrawCentered(&g_sContext, arrAliens3, 5, 48, 65, TRANSPARENT_TEXT);
GrStringDrawCentered(&g_sContext, arrAliens4, 5, 48, 85, TRANSPARENT_TEXT);
GrFlush(&g_sContext);
swDelay(3);
}
void swDelay(char numLoops)
{
volatile unsigned int i,j; // volatile to prevent optimization
// by compiler
for (j=0; j<numLoops; j++)
{
i = 50000 ; // SW Delay
while (i > 0) // could also have used while (i)
i--;
}
}
if ((arrAliens5[0] && arrAliens5[1] && arrAliens5[2] && arrAliens5[3] && arrAliens5[4]) == ' ')
This condition is never true because && is a boolean operator and results in either 0 or 1, which can never be equal to the value of the space character.

Struggling with TicTacToe in C

I tried to program a simple TicTacToe in C. The program itselfs compiles and show no errors.
So the program draws the field, reads the names and let a player put his symbol in a specific field. All this happens in a while loop, the should be run until its a draw or someone wins.
But the program just run the loop one time so there is only one turn then the program stops.
So here is my code:
main.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "game.h"
#define NAMELENGTH 20
int main(void) {
char names[2][NAMELENGTH];
// field positions
char field[9];
int winner = -1;
getnames(names);
printf("\n\n");
initField(field);
// set field positions to 'empty'
char actualPlayer = (char)(get_random_number()*10.0) % 2;
while (1) {
drawField(field);
turn(actualPlayer, names, field);
winner = isWinner(actualPlayer, field);
drawField(field);
if (winner >= 1) {
printwinner(winner, names);
return 0;
}
else if (winner == 0) {
printDrawGame(names);
return 0;
}
actualPlayer = (actualPlayer + 1) % 2;
}
return 0;
}
game.h Headerfile:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define NAMELENGTH 20
#pragma warning(disable:4996)
extern void drawField(char *field);
extern void getnames(char nameField[][NAMELENGTH]);
extern void initField(char *field);
extern void turn(char actualPlayer, char names[][NAMELENGTH], char *field);
extern char isWinner(char actualPlayer, char *field);
extern void printwinner(char winnerNumber, char names[][NAMELENGTH]);
extern void printDrawGame(char names[][NAMELENGTH]);
extern double get_random_number();
and then my game.c where I defined my functions:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "game.h"
#define NAMELENGTH 20
#pragma warning(disable:4996)
void drawField(char *field) {
printf("________________________\n");
printf("| | | |\n");
printf("| %c | %c | %c |\n", field[0], field[1], field[2]);
printf("|_______|_______|______|\n");
printf("| | | |\n");
printf("| %c | %c | %c |\n", field[3], field[4], field[5]);
printf("|_______|_______|______|\n");
printf("| | | |\n");
printf("| %c | %c | %c |\n", field[6], field[7], field[8]);
printf("|_______|_______|______|\n");
}
void getnames(char nameField[][NAMELENGTH]) {
printf("Name of the first player: ");
scanf("%s", nameField[0]);
printf("Name of the second player: ");
scanf("%s", nameField[1]);
}
void initField(char *field) {
for (int i = 0; i <= 8; i++)
{
field[i] = i + '1';
}
}
void turn(char actualPlayer, char names[][NAMELENGTH], char *field) {
char symbol = ' ';
int p1fieldnumber;
int p2fieldnumber;
if (actualPlayer == 0)
{
do {
printf("\nIts Player %s's turn.", names[0]);
char symbol = 'X';
printf("\nNumber of the field which you want to put your symbol in: ");
scanf("%d", &p1fieldnumber);
if (field[p1fieldnumber] == 'X' || field[p1fieldnumber] == 'O')
{
printf("\nField is already occupied!");
p1fieldnumber = 10;
}
} while (p1fieldnumber < 1 || p1fieldnumber > 9);
field[p1fieldnumber-1] = 'X';
}
else {
do {
printf("\nIts Player %s's turn.", names[1]);
char symbol = 'O';
printf("\nNumber of the field which you want to put your symbol in: ");
scanf("%d", &p2fieldnumber);
if (field[p2fieldnumber] == 'X' || field[p2fieldnumber] == 'O')
{
printf("\nField is already occupied!");
p2fieldnumber = 10;
}
} while (p2fieldnumber < 1 || p2fieldnumber > 9);
field[p2fieldnumber-1] = 'O';
}
}
char isWinner(char actualPlayer, char *field) {
char pwinner = '3';
if (((field[0] == 'O') && (field[1] == 'O') && (field[2] == 'O')) ||
(field[3] == 'O') && (field[4] == 'O') && (field[5] == 'O') ||
(field[6] == 'O') && (field[7] == 'O') && (field[8] == 'O') ||
(field[0] == 'O') && (field[4] == 'O') && (field[8] == 'O') ||
(field[2] == 'O') && (field[4] == 'O') && (field[6] == 'O') ||
(field[0] == 'O') && (field[3] == 'O') && (field[6] == 'O') ||
(field[1] == 'O') && (field[4] == 'O') && (field[7] == 'O') ||
(field[2] == 'O') && (field[5] == 'O') && (field[8] == 'O'))
{
pwinner = '2';
}
else if (((field[0] == 'X') && (field[1] == 'X') && (field[2] == 'X')) ||
(field[3] == 'X') && (field[4] == 'X') && (field[5] == 'X') ||
(field[6] == 'X') && (field[7] == 'X') && (field[8] == 'X') ||
(field[0] == 'X') && (field[4] == 'X') && (field[8] == 'X') ||
(field[2] == 'X') && (field[4] == 'X') && (field[6] == 'X') ||
(field[0] == 'X') && (field[3] == 'X') && (field[6] == 'X') ||
(field[1] == 'X') && (field[4] == 'X') && (field[7] == 'X') ||
(field[2] == 'X') && (field[5] == 'X') && (field[8] == 'X'))
{
pwinner = '1';
}
else if (((field[0] == 'X') || (field[0] == 'O')) && ((field[1] == 'X') || (field[1] == 'O')) && ((field[2] == 'X') || (field[2] == 'O')) ||
((field[3] == 'X') || (field[3] == 'O')) && ((field[4] == 'X') || (field[4] == 'O')) && ((field[5] == 'X') || (field[5] == 'O')) ||
((field[6] == 'X') || (field[6] == 'O')) && ((field[7] == 'X') || (field[7] == 'O')) && ((field[8] == 'X') || (field[8] == 'O')) ||
((field[0] == 'X') || (field[0] == 'O')) && ((field[4] == 'X') || (field[4] == 'O')) && ((field[8] == 'X') || (field[8] == 'O')) ||
((field[2] == 'X') || (field[2] == 'O')) && ((field[4] == 'X') || (field[4] == 'O')) && ((field[6] == 'X') || (field[6] == 'O')) ||
((field[0] == 'X') || (field[0] == 'O')) && ((field[3] == 'X') || (field[3] == 'O')) && ((field[6] == 'X') || (field[6] == 'O')) ||
((field[1] == 'X') || (field[1] == 'O')) && ((field[4] == 'X') || (field[4] == 'O')) && ((field[7] == 'X') || (field[7] == 'O')) ||
((field[2] == 'X') || (field[2] == 'O')) && ((field[5] == 'X') || (field[5] == 'O')) && ((field[8] == 'X') || (field[8] == 'O')))
{
pwinner = '0';
}
return pwinner;
}
void printwinner(char winnerNumber, char names[][NAMELENGTH]) {
if (winnerNumber == '1') {
printf("Player %s won!", names[0]);
}
else if (winnerNumber == '2') {
printf("Player %s won!", names[1]);
}
}
void printDrawGame(char names[][NAMELENGTH]) {
printf("Draw!");
}
static int _initialized;
double get_random_number() {
if (!_initialized) {
srand(time(NULL));
_initialized = 1;
}
return (double)rand() / ((double)(RAND_MAX)+1);
}
There are multiple issues
isWinner returns characters '0', '1', '2' and '3'. Replace them with numbers 0, 1, 2, 3, because your are comparing with numbers in main.
In main instead of checking if (winner >= 1) {, which is true even if 3 is returned by isWinner, check for if (winner == 1 || winner == 2) {.
Suggest to use parentheses in isWinner around each condition separated by ||.
Parentheses as shown below for the first condition
if (((field[0] == 'O') && (field[1] == 'O') && (field[2] == 'O')) ||
((field[3] == 'O') && (field[4] == 'O') && (field[5] == 'O')) ||
((field[6] == 'O') && (field[7] == 'O') && (field[8] == 'O')) ||
((field[0] == 'O') && (field[4] == 'O') && (field[8] == 'O')) ||
((field[2] == 'O') && (field[4] == 'O') && (field[6] == 'O')) ||
((field[0] == 'O') && (field[3] == 'O') && (field[6] == 'O')) ||
((field[1] == 'O') && (field[4] == 'O') && (field[7] == 'O')) ||
((field[2] == 'O') && (field[5] == 'O') && (field[8] == 'O')))

Function and loop trouble in C

This program is expecting the user to input a 7-digit number (except 1 and 0), and any digit has a corresponding set of letters
(2=ABC, 3=DEF, 4=GHI, 5=JKL, 6=MNO, 7=PRS, 8=TUV, 9=XYZ, as found on phones in the USA). Finally, it should output all 2187 possible sequences of letters.
ex: input 2345678
output should be ADGJMPT ADGJMPU ADGJMPV ADGJMRT ADGJMRU ADGJMRV ADGJMST..........CFILOSV
but my output always is AAAAAAA AAAAAAB AAAAAAC..........CCCCCCC
(I also have trouble in checking number. I first set a loop and array, if (che[1] != 1 && che[0] != 1) break; but sometimes it doesn't break.)
Can you explain what's wrong?
#include<stdio.h>
int main(){
int che[50] = { 0 };
int a, b, c, d, e, f, g, i, r, q, number, check;
char word2[7];
char word1[8][3] = {
{ 'A', 'B', 'C' },
{ 'D', 'E', 'F' },
{ 'G', 'H', 'I' },
{ 'J', 'K', 'L' },
{ 'M', 'N', 'O' },
{ 'P', 'R', 'S' },
{ 'T', 'U', 'V' },
{ 'W', 'X', 'Y' } };
while (1)
{
printf("Enter seven digit(except 0 and 1):");
scanf("%d", &number);
check = number;
for (; number != 0; number /= 10)
{
q = number % 10;
che[q] = 1;
}
if (che[1] != 1 && che[0] != 1) break;
}
number = check;
for (i = 6; number == 0; i--)
{
r = number % 10;
if (r == 2){ word2[i] = 0; }
if (r == 3){ word2[i] = 1; }
if (r == 4){ word2[i] = 2; }
if (r == 5){ word2[i] = 3; }
if (r == 6){ word2[i] = 4; }
if (r == 7){ word2[i] = 5; }
if (r == 8){ word2[i] = 6; }
if (r == 9){ word2[i] = 7; }
number /= 10;
}
for (a = 0; a < 3; a++){
for (b = 0; b < 3; b++){
for (c = 0; c < 3; c++){
for (d = 0; d < 3; d++){
for (e = 0; e < 3; e++){
for (f = 0; f < 3; f++){
for (g = 0; g < 3; g++){
printf("%c%c%c%c%c%c%c ",word1[word2[0]][a], word1[word2[1]][b], word1[word2[2]][c], word1[word2[3]][d], word1[word2[4]][e], word1[word2[5]][f], word1[word2[6]][g]);
}
}
}
}
}
}
}
return 0;
}
Main problem is here:
for (i = 6; number == 0; i--)
The loop condition is the opposite of the one it should be. You want to keep iterating on the number until you reach 0 (by successively dividing it by 10).
It should be
for (i = 6; number != 0; i--)
or
for (i = 6; i >= 0; i--)
In addition mind that
if (r == 2){ word2[i] = 0; }
if (r == 3){ word2[i] = 1; }
if (r == 4){ word2[i] = 2; }
if (r == 5){ word2[i] = 3; }
if (r == 6){ word2[i] = 4; }
if (r == 7){ word2[i] = 5; }
if (r == 8){ word2[i] = 6; }
if (r == 9){ word2[i] = 7; }
is equivalent to
if (r >= 2 && r <= 9)
word2[i] = r - 2;
I think this works as you expected:
For some convenience in debugging, I changed some IO format:
Input separated number 2-9 divided by space and end with -1.
The input sequence can be of any length, just end with -1.
For example, input:2 3 4 2 -1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char word1[8][3] = {
{ 'A', 'B', 'C' },
{ 'D', 'E', 'F' },
{ 'G', 'H', 'I' },
{ 'J', 'K', 'L' },
{ 'M', 'N', 'O' },
{ 'P', 'R', 'S' },
{ 'T', 'U', 'V' },
{ 'W', 'X', 'Y' } };
void translate(char * headStr,int * pattern,int pos_to_do)
{
if(pattern[pos_to_do]<0)
{
printf("%s\n",headStr);
return;
}
char str[3][20];
int i;
for(i=0;i<3;i++)
{
strcpy(str[i],headStr);
char str_this[2];
str_this[0]=word1[ pattern[pos_to_do] ][i];
str_this[1]='\0';
strcat(str[i],str_this);
translate(str[i],pattern,pos_to_do+1);
}
return;
}
int main(){
int che[20];
int number, check,len;
while (1)
{
printf("Enter digits(except 0 and 1):");
len=0;
scanf(" %d", &number);
while(number>=2)
{
che[len]=number-2;
len++;
scanf("%d", &number);
}
che[len]=-1;
char str_start[]="";
translate(str_start,che,0);
}
return 0;
}
Test output:
Enter digits(except 0 and 1):2 3 4 -1
ADG
ADH
ADI
AEG
AEH
AEI
AFG
AFH
AFI
BDG
BDH
BDI
BEG
BEH
BEI
BFG
BFH
BFI
CDG
CDH
CDI
CEG
CEH
CEI
CFG
CFH
CFI
Enter digits(except 0 and 1):

Resources