switch(start)
{case 0:printf("");
j=1;
break;
case 1:printf("\t");
j=2;
break;
case 2:printf("\t\t");
j=3;
break;
case 3:printf("\t\t\t");
j=4;
break;
case 4:printf("\t\t\t\t");
j=5;
break;
case 5:printf("\t\t\t\t\t");
j=6;
break;
case 6:printf("\t\t\t\t\t\t");
j=7;
break;
}
start takes input from user, any way to shorten this piece of code???????
Any help is appreciated!!!!!!!!
int foo(int start)
{
for(int x = 0; x < start; x++) printf("\t");
return start + 1; // it is your j
}
or without the function
for(int x = 0; x < start; x++) printf("\t");
j = start + 1;
You could use start to compute the place in a buffer full of tabs at which to start printing:
if ( 0 <= start && start <= 6)
{
char* tabs = "\t\t\t\t\t\t"; // 6 tabs
printf( "%s", tabs+6-start);
j = start + 1;
}
Related
I'm learning C at school, and as homework I have to write the tictactoe game. No problem with the "algorithm", but I do not understand why if I change the order of the variables declaration, the program output drastically changes or even the programme stops working. For example, if I swap line 12 with line 13, the element of the array coord change values at random points of the programme. Can someone explain me why this happen?
#include <stdio.h>
#define DIM 3
#define MAX 11
int main(void) {
char c;
int state = 0; //Variable for the switch case
int nC, nR; //Variables used to count how many X or O there are in the rows and columns of the grid
int i, j;
int coord[2] = {0, 0}; //Array for the coordinates
char grid[DIM][DIM]; //Grid 3x3
char player1[MAX] = "", player2[MAX] = ""; //Name of the players
printf("Player 1, insert your name (max 10 characters): ");
gets(player1);
fflush(stdin);
printf("Player 2, insert your name (max 10 characters): ");
gets(player2);
for (i = 0; i < DIM; i++) { //Inizialize the grid with '.'
for (j = 0; j < DIM; j++) {
grid[i][j] = '.';
printf("%3c", grid[i][j]);
if (j == 0 || j == 1) printf(" |");
}
if (i == 0 || i == 1) printf("\n- - - - - - - -\n");
}
do{
switch (state) {
case 0: //State 0: Player 1 is asked for the coordinates corresponding to the position where you want to insert the X symbol
printf("\n%s your turn: ", player1);
scanf("%d %d", &coord[1], &coord[2]);
if (grid[coord[1] - 1][coord[2] - 1] == '.' && grid[coord[1] - 1][coord[2] - 1] != 'O') { //Check that the selected coordinates are free. Otherwise it prints an error message
grid[coord[1] - 1][coord[2] - 1] = 'X';
c = 'X';
state = 2;
}
else{
state = 0;
printf("Invalid coordinates!\n");
}
break;
case 1: //State 1: Player 2 is asked for the coordinates corresponding to the position where you want to insert the O symbol
printf("\n%s your turn: ", player2);
scanf("%d %d", &coord[1], &coord[2]);
if (grid[coord[1] - 1][coord[2] - 1] == '.' && grid[coord[1] - 1][coord[2] - 1] != 'X') { //Check that the selected coordinates are free. Otherwise it prints an error message
grid[coord[1] - 1][coord[2] - 1] = 'O';
c = 'O';
state = 2;
}
else{
printf("Invalid coordinates!\n");
state = 1;
}
break;
case 2: //State 2: Check if there a right combination of X or O
printf("\n");
for (i = 0; i < DIM; i++) {
for (j = 0; j < DIM; j++) {
printf("%3c", grid[i][j]);
if(j == 0 || j == 1) printf(" |");
}
if (i == 0 || i == 1) printf("\n- - - - - - - -\n");
}
nC = 0;
nR = 0;
i = coord[1] - 1;
for (j = 0; j < DIM; j++) {
if(grid[i][j] != c){
break;
}
else{
nR++;
}
}
j = coord[2] - 1;
for (i = 0; i < DIM; i++) {
if (grid[i][j] != c) {
break;
}
else{
nC++;
}
}
if (nC == 3 || nR == 3) state = 3;
else if (c == 'X') state = 1;
else state = 0;
break;
case 3:
if (c == 'X') printf("\n%s IS THE WINNER!\n", player1);
else printf("\n%s IS THE WINNER!\n", player2);
return 0;
break;
}
} while (1);
}
In C, array indices for an array with n elements run from 0 to n−1.
int coord[2] = {0, 0}; defines coord to have two elements, so their indices are 0 and 1.
Throughout the code, coord[1] and coord[2] are used. coord[2] is outside the defined array, so the behavior of the program is not defined by the C standard.
This program is about converting Roman number to decimal number. The program can convert the alphabet to number but it can not process the last roman digit. I think my flow is alright but the output is not right. Can any body give me a helping hand?
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int roman_to_int(const char s[], int length) {
// Please complete the function body
int ans = 0, value[length];
for (int i = 0; i < length; i++) {
switch (s[i]) {
case 'I': value[i] = 1; break;
case 'V': value[i] = 5; break;
case 'X': value[i] = 10; break;
case 'L': value[i] = 50; break;
case 'C': value[i] = 100; break;
case 'D': value[i] = 500; break;
case 'M': value[i] = 1000; break;
}
}
for (int i = 0; i < length - 1; i++) {
if (value[i] >= value[i+1])
ans += value[i];
else {
ans = ans + value[i+1] - value[i];
i++;
}
}
return ans;
}
int main() {
char roman_num[] = "III";
char roman_num_2[] = "CXXIII";
char roman_num_3[] = "MMMCDLIX";
printf("roman_to_int(%s) = %d\n", roman_num,
roman_to_int(roman_num, strlen(roman_num)));
printf("roman_to_int(%s) = %d\n", roman_num_2,
roman_to_int(roman_num_2, strlen(roman_num_2)));
printf("roman_to_int(%s) = %d\n", roman_num_3,
roman_to_int(roman_num_3, strlen(roman_num_3)));
}
You should add the value of the last roman digit after the end of the second loop.
As an alternative, you could make value on entry longer than n and set the last entry to 0 so you won't need the make a special case of the last roman digit.
Note that you should also handle the case of unrecognised roman digits: either by ignoring them or by returning an error code, such as a negative value -1.
It is also simpler for roman_to_int to take a null terminated C string and compute the length there.
Here is a modified version:
#include <stdio.h>
#include <string.h>
int roman_to_int(const char s[]) {
// Please complete the function body
int length = strlen(s);
int ans = 0, value[length + 1];
for (int i = 0; i < length; i++) {
switch (s[i]) {
case 'I': value[i] = 1; break;
case 'V': value[i] = 5; break;
case 'X': value[i] = 10; break;
case 'L': value[i] = 50; break;
case 'C': value[i] = 100; break;
case 'D': value[i] = 500; break;
case 'M': value[i] = 1000; break;
default: return -1;
}
}
value[length] = 0;
for (int i = 0; i < length; i++) {
if (value[i] >= value[i + 1])
ans += value[i];
else
ans -= value[i];
}
return ans;
}
int main() {
char roman_num[] = "III";
char roman_num_2[] = "CXXIII";
char roman_num_3[] = "MMMCDLIX";
char roman_num_4[] = "MMMCDLIZ"; // error
printf("roman_to_int(%s) = %d\n", roman_num, roman_to_int(roman_num));
printf("roman_to_int(%s) = %d\n", roman_num_2, roman_to_int(roman_num_2));
printf("roman_to_int(%s) = %d\n", roman_num_3, roman_to_int(roman_num_3));
printf("roman_to_int(%s) = %d\n", roman_num_4, roman_to_int(roman_num_4));
return 0;
}
int T, i;
scanf("%d", &T);
char a[T], b[T], c[T];
int temp[T], temp2[T], temp3[T];
int point1[T], point2[T], point3[T];
for(i=0;i<T; i++){
scanf("%c %c %c", &a[i], &b[i], &c[i]);
switch(a[i]){
case '!':
point1[i] = 5;
break;
case '%':
point1[i] = 4;
break;
case '&':
point1[i] = 3;
break;
case '^':
point1[i] = 2;
break;
case '|':
point1[i] = 1;
break;
default :
point1[i]=10;
}
switch(b[i]){
case '!':
point2[i] = 5;
break;
case '%':
point2[i] = 4;
break;
case '&':
point2[i] = 3;
break;
case '^':
point2[i] =2;
break;
case '|':
point2[i] =1;
break;
default :
point2[i]=10;
}
switch(c[i]){
case '!':
point3[i] = 5;
break;
case '%':
point3[i] = 4;
break;
case '&':
point3[i] = 3;
break;
case '^':
point3[i] =2;
break;
case '|':
point3[i] =1;
break;
default :
point3[i]=10;
}
if(point1[i]<point2[i]) {
temp[i]=point1[i];
point1[i]=point2[i];
point2[i]=temp[i];
}
if(point1[i]<point3[i]){
temp2[i]=point1[i];
point1[i]=point3[i];
point3[i]=temp2[i];
}
if(point2[i]<point3[i]){
temp3[i]=point2[i];
point2[i]=point3[i];
point3[i]=temp3[i];
}
printf("%d %d %d\n", point1[i], point2[i], point3[i]);
}
return 0;
So first of all, i was asked to input certain characters randomly arranged and make them printed arranged from the highest precedence.
The precedence of the operators (from the highest to the lowest) are "!" (logical NOT), "%" (remainder), "&"
(bitwise AND), "^" (bitwise XOR), , "|" (bitwise OR).
So i try to change the characters into numbers and try to arrange the number first then change the number again to the characters.
But when i try to check if the numbers have been correctly arranged, it's not.
Any idea what's wrong with my code?
Or any idea to make my code simpler without having to turn the characters into numbers?
Here's the sample
Sample Input
3
& ^ %
& ^ !
& ^ !
Sampe Output
Case #1: % & ^
Case #2: ! & ^
Case #3: ! & ^
A few issues have already been noted in the comments. Specifically, scanf leaves the trailing newline in the input buffer. You can fix that using the suggestion by #4386427.
You can avoid manually assigning numbers for each character by noting that their ASCII is already in required order. That is, '!' < '%' < '&' < '^' < '|'. So you can simply read them into a char array of the appropriate size and just sort them in ascending order before printing the char array. This will significantly shorten and clean up your code.
#include <stdio.h>
#include <stdlib.h>
int cmpfunc (const void * a, const void * b) {
return (*((char*)a) > *((char*)b)) - (*((char*)a) < *((char*)b));
}
int main(int argc, char *argv[])
{
int T, i, j;
scanf(" %d", &T);
/* TODO: Check if number of chars per line is T or 3. */
char *a = malloc(T * sizeof(char));
for(i = 0; i < T; i++) {
for (j = 0; j < T; j++) {
scanf(" %c", &a[j]);
}
printf("Before sort\n");
for (j = 0; j < T; j++) {
printf("%c ", a[j]);
}
printf("\n");
qsort(a, T, sizeof(a[0]), cmpfunc);
printf("After sort\n");
for (j = 0; j < T; j++) {
printf("%c ", a[j]);
}
printf("\n");
}
free(a);
return 0;
}
I have a coding assignment for my CIS class. The assignment is to write a program the will create an array of structures that will hold information on at max 10 dogs. At the end of the program, you are supposed to sort the array of dogs by either name or size. But I am unable to code the sorting of the array of dog. I was wondering how to sort the array of dogs for later use in the main function.
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Dog{
char name[20];
int weight;
int age;
int ageDogYears;
char size[7];
};
typedef struct Dog DG;
void calc(DG[], int);
void sort(DG[], int);
void display();
int main(){
DG dArray[10];
int x = 0;
char str[80], *i;
FILE *inFile;
inFile = fopen("dogfile.txt", "r");
if (inFile == NULL){
printf("Error opening file");
exit(1);
}
while(fgets(str, 80,inFile) != NULL){
i = strtok(str, ", ");
strcpy(dArray[x].name, i);
puts(dArray[x].name);
i = strtok(NULL, ", ");
dArray[x].weight = atoi(i);
printf("%d\n", dArray[x].weight);
i = strtok(NULL, ", ");
dArray[x].age = atoi(i);
printf("%d\n", dArray[x].age);
x++;
}
calc(dArray, x);
sort(dArray, x);
return 0;
}
void calc(DG dog[], int numDogs){
int y, i, total;
for(i = 0; i < numDogs; ++i){
if(dog[i].weight <= 20){
//sets the dog size to small
strcpy(dog[i].size, "Small");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 15;
else if(y == 1)
total += 8;
else if(y == 2)
total += 5;
else
total += 4;
}
}
else if(dog[i].weight <= 50){
//sets the dog size to medium
strcpy(dog[i].size, "Medium");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 14;
else if(y == 1)
total += 9;
else if(y == 2)
total += 7;
else
total += 5;
}
}
else{
//sets the dog size to Large
strcpy(dog[i].size, "Large");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 12;
else if(y == 1)
total += 9;
else if(y == 2)
total += 8;
else
total += 7;
}
}
dog[i].ageDogYears = total;
total = 0;
}
}
void sort(DG dog[], int numDogs){
int sortType, i, y, temp;
printf("\n wlould you like to sort by name(N) or size(S): ");
scanf("%c", &sortType);
switch(sortType){
case 'N': case 'n':
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs); ++y){
if(dog[y].weight > dog[y+1].weight){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}
break;
default:
if((sortType != 's') && (sortType != 'S'))
printf("\n invalid input! Setting sort type to size.");
//sorting of dog names
}
}
Sample Input
Fluffy,23,6
Fido,65,7
Pepper,44,5
Bowser,75,10
Victor,10,2
Sassy,51,1
Any help would be much appretated! Thanks.
In my opinion, your error resides (despite of other comments I'll do below) in specifying %c as format descriptor to pass a pointer to int to match. You have to pass a pointer to char to make scanf(3) to select the proper place to put the character into. You probably are not getting the right character or no character at all (this leads to Undefined Behaviour in your program)
Some other problems are that you are using the weight field of the structure when requested to sort by name (on n input char) and other errors like this. This includes that you use y < (numDogs) in the inner loop limit condition (it must be y < (numDogs - 1), or you'll compare the y-esim with the y+1-esim element (out of array bounds)
Also, as you are using the same algorithm for both sorting options, I should include the switch statement inside the inner loop (where you do the comparison) as doing otherwise will force you to copy the same sorting code twice (for the overall sorting algorithm), as in:
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs - 1); ++y){
int sortResultGreater;
switch (sortType) {
case 'n': case 'N':
sortResultGreater = strcmp(dog[y].name, dog[y+1].name) > 0;
break;
default: { /* this should be done as soon as you know the sorting type, not here inside the loop, of course */
static int not_already_printed = 1;
if (not_already_printed) {
printf("Error, sortType must be [nNsS], defaulting to n\n");
not_already_printed = 0; /* so we don't get here again */
}
} /* scope of not_already_printed finishes here */
/* no break used here to fallback to the next case */
case 's': case 'S':
sortResultGreater = dog[y].weight > dog[y+1].weight;
break;
} /* switch */
if(sortResultGreater){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}
I want to that this function after than player 1 puts position program chack where on the left is player's 1 pawn and all of opponent's paws between player's 1 two pawns turning on 'X', like in reversi games.
This is whole unfinished code:
#include<stdio.h>
#define SIZE 7
char board[SIZE][SIZE];
char letter;
int number;
void make_board(char tab[SIZE][SIZE]){
int w,k;
for(w=0; w < SIZE; w++){
for(k=0; k < SIZE; k++){
tab[w][k] = '.';
}
}
tab[0][0] = 'X';
tab[1][0] = '1';
tab[2][0] = '2';
tab[3][0] = '3';
tab[4][0] = '4';
tab[5][0] = '5';
tab[6][0] = '6';
tab[0][1] = 'A';
tab[0][2] = 'B';
tab[0][3] = 'C';
tab[0][4] = 'D';
tab[0][5] = 'E';
tab[0][6] = 'F';
tab[4][4] = 'X';
tab[4][3] = 'O';
tab[3][4] = 'O';
tab[3][3] = 'X';
}
char draw_board(char tab[SIZE][SIZE]){
int w, k;
for(w=0; w < SIZE; w++){
for(k=0; k < SIZE; k++){
printf("%2c", tab[w][k]);
}
printf("\n");
}
}
int translate(char letter){
int letter_to_number;
switch(letter){
case 'A':
case 'a':
letter_to_number = 1;
break;
case 'B':
case 'b':
letter_to_number = 2;
break;
case 'C':
case 'c':
letter_to_number = 3;
break;
case 'D':
case 'd':
letter_to_number = 4;
break;
case 'E':
case 'e':
letter_to_number = 5;
break;
}
return letter_to_number;
}
int finished(char tab[SIZE][SIZE]){ // looking '.' in array
int i,j;
for(i=1;i<=SIZE;i++){
for(j=1;j<=SIZE;j++){
if(tab[i][j]=='.'){
return 1;
}else{
return 0; // if don't find any '.' game is finish
}
}
}
}
void hit(char tab[SIZE][SIZE], int player ){
int i,j;
int *poz1, *poz2;
printf("Call out a letter and a number of a row and column on the grid:\n");
scanf(" %c %d", &letter, &number);
i=translate(letter);
poz1=&tab[number][i];
if(tab[number][i]=='.'){
if(player==1){
*poz1='X';
for(poz1-1;*poz1=='X';poz1--){
poz2=&poz1;}
poz1=&tab[number][i];
for(poz2;poz2<=poz1;poz2++){
*poz2='X';}
}else{
*poz1='O';
for(poz1-1;*poz1=='O';poz1--){
poz2=&poz1;}
poz1=&tab[number][i];
for(poz2;poz2<=poz1;poz2++){
poz2='O';}
}
}else{
printf("On this place already is pawn\n");
}
draw_board(board);
getchar();
}
int main(){
int i,j,k, pg1=0, pg2=0, player=1;
make_board(board);
draw_board(board);
do{
if(player==1){
printf("Player 1\n");
hit(board, gracz);
k=finished(board);
gracz=2;
}else{
printf("Player 2\n");
hit(board, gracz);
k=finished(board);
player=1;
}
}while(k==1);
for(i=1;i<=SIZE;i++){
for(j=1;j<=SIZE;j++){
if(board[i][j]=='X'){
pg1++;
}else{
pg2++;
}
}
}
if(pg1>pg2){
printf("Player 1 wins");
}else{
printf("Player 2 wins");
}
return 0;
}
Bit buggy code:
poz1=&tab[number][i];
if(tab[number][i]=='.'){
if(player==1){
*poz1='X';
for(poz1-1;*poz1=='X';poz1--){
poz2=&poz1;}
poz1=&tab[number][i];
for(poz2;poz2<=poz1;poz2++){
*poz2='X';}
How can you asgn &pos1 to pos2. For this you need pointer to a pointer, i.e, pos 2 should be declared as **pos2.
Also, what do you want to achieve by looping over poz1 (set 'X' earlier)?
Anyhow, some cleanup to your code:
if(tab[number][i]=='.'){
if(player==1){ //considering player 1 is 'X'
// Loop to the left till you find opponent's piece or come to edge.
for(j=i-1;tab[number][j]=='O' && j!=0 ;j--)
;
// Validation check
if(i-j <=1 || tab[number][j] != 'X');
//Invalid move
return 1;
else
// convert all the opponents pieces between two of yours piece
for(k=i;k>j;k--)
tab[number][k] = 'X';
The above part of code is informative only..this will check if the move is valid for left side..and if valid convert the opponents pieces.. you need to understand this and put similar logic for "Right", "Diagonal" etc to complete the reversi game.