My code runs in VSCode but does not run in DevC - c

#include <stdlib.h>
#include <stdio.h>
void arraydescending(int array[]){
for (int j=0; j<9; j++){
for (int i=0; i<8; i++)
{
if(array[i]<array[i+1]){
int swapper = array[i+1];
array[i+1]=array[i];
array[i]=swapper;
}
}
}
for (int c=0; c<9; c++){
printf("%d",array[c]);
}
}
void arrayreverse(int array[])
{
for(int i = 0; i<4; i++)
{
int swapper = array[i];
array[i] = array[8-i];
array[8-i] = swapper;
}
for (int c=0; c<9; c++){
printf("%d",array[c]);
}
}
int main()
{
int choice;
printf("Please enter your choice:");
scanf("%d", &choice);
if(choice == 1)
{
int mynumberarray[9] = {1,1,0,2,0,0,0,4,7};
int choice_2;
printf("Write 1 for reverse order, write 2 for descending order:");
scanf("%d", &choice_2);
if(choice_2 == 1)
{
arrayreverse(mynumberarray);
}
else if(choice_2 == 2)
{
arraydescending(mynumberarray);
}
else
{
printf("Invalid choice");
}
}
else if(choice == 2){
int userarray[9];
char * user_entry;
printf("Please enter your school no (9 digits):");
scanf("%s",user_entry);
for(int i = 0; i < 9; i++)
{
userarray[i] = user_entry[i] - '0';
}
int choice_2;
printf("Write 1 for reverse order, write 2 for descending order:");
scanf("%d", &choice_2);
if(choice_2 == 1)
{
arrayreverse(userarray);
}
else if(choice_2 == 2)
{
arraydescending(userarray);
}
else
{
printf("Invalid choice");
}
}
else
{
printf("Invalid choice");
}
return 0;
}
This code runs correctly when I compiled it with gcc -std=c99; but my friend has DevC 5.11 version can compile the code but it doesn't run correctly in his DevC (It exits the program in the second scanf). Both compiles but why it does not run in DevC 5.11 with the compiler gcc 4.9.2? I am waiting for your suggestions because I didn't understand the reason behind it, my code looks like it has not any mistakes.

Your program has undefined behavior at least because in this code snippet
char * user_entry;
printf("Please enter your school no (9 digits):");
scanf("%s",user_entry)
you are using the uninitialized pointer user_entry that has an indeterminate value. You need to declare a large enough character array where you are going to read a string of digits. Do not forget to reserve in the array a space for the terminating zero character of the read string.

Related

Get a problem when make a hangman game ? ( c language)

I'm still really new to the C language and I'm trying to make a hangman game but I keep failing to end the game when I win.
Here is the code:
const int true = 1;
const int false = 0;
char words[][20] = {
"hangman",
"computer",
"programming",
"microsoft",
"visual",
"studio",
"express",
"learning"
};
int isletterinword(char word[], char letter)
{
int i;
for (i = 0; i < strlen(word); i++) {
if (word[i] == letter) {
return true;
}
}
return false;
}
int iswordcomplete(char secretword[], char rights[])
{
int i;
for (i = 0; i < strlen(secretword); i++) {
if (rights[i] == secretword[i] ) {
return true;
}
}
return false;
}
void printhangman(int numofwrongs)
{
// Line 1
printf("\t ______\n");
// Line 2
printf("\t | |\n");
// Line 3
printf("\t | +\n");
// Line 4 - left arm, head and right arm
printf("\t |");
if (numofwrongs > 0) printf(" \\");
if (numofwrongs > 1) printf("O");
if (numofwrongs > 2) printf("/");
printf("\n");
// Line 5 - body
printf("\t |");
if (numofwrongs > 3) printf(" |");
printf("\n");
// Line 6 - left leg and right leg
printf("\t |");
if (numofwrongs > 4) printf(" /");
if (numofwrongs > 5) printf(" \\");
printf("\n");
// Line 7
printf("\t |\n");
// Line 8
printf("\t__|__\n");
}
void printletters(char letters[])
{
int i;
for (i = 0; i < strlen(letters); i++) {
printf("%c ", letters[i]);
}
}
void printscreen(char rights[], char wrongs[], char secretword[])
{
int i;
for (i = 0; i < 25; i++)
printf("\n");
printhangman(strlen(wrongs));
printf("\n");
printf("Correct guesses: ");
printletters(rights);
printf("\n");
printf("Wrong guesses: ");
printletters(wrongs);
printf("\n\n\n");
printf("\t");
for (i = 0; i < strlen(secretword); i++) {
if (isletterinword(rights, secretword[i])) {
printf("%c ", secretword[i]);
}
else {
printf("_ ");
}
}
printf("\n\n");
}
int main()
{
int i;
int secretwordindex;
char rights[20];
char wrongs[7];
char guess;
secretwordindex = 0;
srand(time(0));
secretwordindex = rand() % 8;
for (i = 0; i < 20; i++) {
rights[i] = '\0';
}
for (i = 0; i < 6; i++) {
wrongs[i] = '\0';
}
while (strlen(wrongs) < 6) {
printscreen(rights, wrongs, words[secretwordindex]);
printf("\nPlease enter your guess: ");
scanf(" %c", &guess);
if (isletterinword(words[secretwordindex],guess)) {
rights[strlen(rights)] = guess;
}
else {
wrongs[strlen(wrongs)] = guess;
}
}
printscreen(rights, wrongs, words[secretwordindex]);
if ( iswordcomplete(words[secretwordindex],rights[20])==true && strlen(wrongs) <= 6 ) { // The if condition here might be problematic.
printf("You have won!\n");
}
else {
printf("You have lost!\n");
}
}
Here is the error message:
main.c:197:48: warning: passing argument 2 of ‘iswordcomplete’ makes
pointer from integer without a cast [-Wint-conver sion]
main.c:55:5: note: expected ‘char *’ but argument is of type ‘char’
First things first: The compiler error is caused by the fact that you are passing a single character to your call to iswordcomplete(), rather than an array of characters. So, in the check near the end of your main function, you need to pass rights (unadorned) as the argument, in place of rights[20] (which, incidentally, is an out-of-bounds element of the array). Also, you don't – at that stage – need the second check (counting the number of wrongs – see later). Here's the fix for that part of the code:
// if (iswordcomplete(words[secretwordindex], rights[20]) == true && strlen(wrongs) <= 6) { // The if condition here might be problematic.
if (iswordcomplete(words[secretwordindex], rights)){// && strlen(wrongs) <= 6) { // Needs the whole string as an argument
printf("You have won!\n");
}
Now to address a couple of other issues that will stop your code from working properly ...
(1) Your main while loop won't stop running until you have entered 6 'wrong' letters – even if you do guess the word correctly. So, you need to add an iswordcomplete() check to the while condition (negating it with the !operator†), to keep running the loop only if the word isn't complete. Like this:
while (strlen(wrongs) < 6 && !iswordcomplete(words[secretwordindex], rights)) { // Need to break loop if we win!!
printscreen(rights, wrongs, words[secretwordindex]);
//...
(2) The logic of your iswordcomplete function is flawed, as it will return "true" as soon as it finds any match. Instead, you need two loops, returning false if any of the word's letters is not found in the list of 'rights'. Here's one possible version:
int iswordcomplete(char secretword[], char rights[])
{
int i, j;
for (i = 0; i < strlen(secretword); i++) {
for (j = 0; j < strlen(rights); j++) {
if (secretword[i] == rights[j]) break;
}
if (j >= strlen(rights)) return false; // Didn't find this letter
}
return true;
}
Please feel free for any further clarification and/or explanation.
† If you're not (yet) familiar with this use of the ! operator, then you can explicitly compare the function's return value to the false constant, if you are more comfortable with that, like so:
while (strlen(wrongs) < 6 && iswordcomplete(words[secretwordindex], rights) == false) { // Break loop if we win!

C program to insert elements into an array until user inputs a 0 or less number

I'm trying to make a C program to insert elements into an array until user inputs a 0 or less number, as the title says. But when I print the array out, it doesn't show the numbers I inputted. I have tried using a while as well as do-while loops but without success.
#include <stdio.h>
int main() {
int data[100];
int i;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
int n = sizeof(data[i]);
for (int i = 0; i < n; i++) {
printf("%d ", &data[i]);
}
}
Try this:
#include <stdio.h>
int main() {
int data[100];
int i;
int counter = 0;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
counter++;
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
for (int j = 0; j < counter - 1; j++) {
printf("%d ", data[j]);
}
}
The problem was that you had printf("%d ", &data[i]); instead of printf("%d ", data[i]);.
And also you've trying to get the sizeof() of an element data[i], not the size of the whole array. That's why there's counter in my code.
int n = sizeof(data[i]);
this is wrong, you want
int n = i;
sizeof(data[i]) gives you the size of an int (4 on my machine)
On the other hand, you need to check the result of scanf, if a bad input is entered do not increment the counter, something like:
int i = 0;
while (i < 100)
{
int res = scanf("%d", &data[i]);
if (res == EOF)
{
break;
}
if (res == 1)
{
if (data[i] <= 0)
{
break;
}
i++;
}
else
{
// Sanitize stdin
int c;
while ((c = getchar()) != '\n');
}
}
Finally, scanf wants a pointer to the object, but this is not the case of printf:
printf("%d ", &data[i])
should be
printf("%d ", data[i])

C: Alphabetical sorting of array of character arrays

This showed up in our laboratory finals examination:
Make a program that takes in 10 string inputs into an array.
Then outputs the strings in alphabetical order.
I couldn't figure it out during the examination and now I want to know how exactly is it done.
So far this is what I've done. It doesn't work well with similar or equivalent strings, their index gets lost? Anyone can share their solution using only the stdio.h and string.h libraries?
/*Write a program that takes 10 strings input into an array and outputs them in alphabetical order*/
#include<stdio.h>
#include<string.h>
char strings[10][150];
char ordered[10][150];
int i,j,k;
int ind;
main()
{
printf("INPUT 10 STRINGS\n");
for(i=0;i<10;i++)
{
gets(strings[i]);
}
for(i=0;i<10;i++)
{
ind=0;
for(j=0;j<10;j++)
{
if(strings[i][0]<strings[j][0])
{
ind++;
}
else if(strings[i][0]==strings[j][0])
{
k=0;
while((strings[i][k]==strings[j][k])&&strings[j][k+1]!='\0')
{
if(strlen(strings[i])<strlen(strings[j]))
{
if(strings[i][k+1]=='\0')
{
ind++;
}
else if(strings[i][k+1]<strings[j][k+1])
{
ind++;
}
}
else if(strlen(strings[i])>strlen(strings[j]))
{
if(strings[i][k+1]<strings[j][k+1])
{
ind++;
}
}
k++;
}
}
}
strcpy(ordered[ind],strings[i]);
}
printf("STRINGS: \n");
for(i=9;i>-1;i--)
{
puts(ordered[i]);
}
}
Just Found a simple way for that:
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
gets(str[i]);
}
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("The sorted string\n");
for(i=0;i<=n;i++)
{
puts(str[i]);
}
return 0;
}
strcmp and strcpy are inbuilt functions defined in string.h
for (i=0; i<10; i++) {
for (j=0; j<9; j++) {
if (strcmp(strings[j], strings[j+1]) > 0) {
strcpy(temp, strings[j]);
strcpy(strings[j], strings[j+1]);
strcpy(strings[j+1], temp);
}
}
}
Here's a solution retrieved from here that does what you want but with 5 strings instead. I have adapted it so that it sorts 10 strings instead of 5. All strings have 20 characters at most :
#include<stdio.h>
#include<string.h>
void main() {
char s[10][20], t[20];
int i, j;
clrscr();
printf("\nEnter any five strings : ");
for (i = 0; i < 10; i++)
scanf("%s", s[i]);
for (i = 1; i < 10; i++) {
for (j = 1; j < 10; j++) {
if (strcmp(s[j - 1], s[j]) > 0) {
strcpy(t, s[j - 1]);
strcpy(s[j - 1], s[j]);
strcpy(s[j], t);
}
}
}
printf("\nStrings in order are : ");
for (i = 0; i < 10; i++)
printf("\n%s", s[i]);
getch();
}

How to alter my program to use while loops instead of for loops. Asterisk triangle in c

For my programming assignment I have to create 3 programs that print out an asterisk based triangle in c based on the user's input. The difference between the 3 programs would be one will use for loops, the other would use while loops and the last one would use goto. I have the for loop program as well as the goto program, but as for the while loop program I'm not sure how incorporate it into my program. This is my program with a for loop and the second program is my attempt at the while loop version.
#include <stdio.h>
int main() {
int lines, a, b;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
/*create triangle based on inputed value */
for(a = 1; a <= lines; a++) {
for(b=1; b<= a; b++) {
printf("*");
}
printf("\n");
}
} while(1);
system("pause");
}
Progam #2:
#include <stdio.h>
int main() {
int lines, a = 1, b = 1;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
while(a <= lines) {
a++;
while (b <= a) {
b++;
printf("*");
}
printf("\n");
}
} while(1);
system("pause");
}
Here is how you convert a for loop like the following
for (stat1; stat2; stat3) {
stat4;
}
to a while loop
stat1;
while (stat2) {
stat4;
stat3;
}
So here is the while loop you want:
a = 1;
while(a <= lines) {
b = 1;
while (b <= a) {
printf("*");
b++;
}
printf("\n");
a++;
}
Set b=1 before 2nd while loop
while(a <= lines) {
a++;
b=1; //you want to start b from 1 for each inner loop
while (b <= a) {
b++;
printf("*");
}
printf("\n");
}
The program2 can be changed as below. The below code result is equivalent to program1.`
#include <stdio.h>
int main() {
int lines, a = 1, b = 1;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
while(a <= lines) {
//a++;
while (b <= a) {
b++;
printf("*");
}
b =1;
a++1;
printf("\n");
}
} while(1);
system("pause");
}`

how can i fix these errors in c?

I keep getting these errors. Im trying to make a mine sweeper like game.
well.c: In function 'main':
well.c:170: warning: passing argument 1 of 'bombCheck' makes pointer from integer without a cast
well.c:170: warning: passing argument 3 of 'bombCheck' makes integer from pointer without a cast
well.c: In function 'fillGameBoard':
well.c:196: error: expected declaration or statement at end of input
#include <stdio.h>
#include <stdlib.h>
#define Rows 5
#define Columns 5
#define Bombs 5
void introduction(void)
{
puts("Welcome to the minefield!");
puts("In this level 2 game, you will win by choosing.");
puts("all of the viable wells and not any of the.");
puts("tool breaker spaces. In both games, there are.");
puts("20 viable spaces and 5 tool breakers!");
puts("Have fun and good luck!");
}
void fillGameBoard(char gameBoard[][Columns])
{
int i, j;
FILE *inputFile;
char gameDataFileName[30];
int yes = 0;
do
{
printf("choose your spot");
printf("\nfield1 field2\n");
scanf(" %s",&gameDataFileName);
if ((inputFile = fopen(gameDataFileName,"r")) == NULL)
{
puts("\nWrong input! Try again!");
puts("check spelling, spacing, etc. make it exact!");
}
else
{
yes = 1;
}
} while (yes == 0);
for (i=0; i<Rows; i++)
{
for (j=0; j<Columns; j++)
{
fscanf(inputFile, " %c", &gameBoard[i][j]);
}
fclose(inputFile);
return;
}
void fillUserBoard(char userBoard[][Columns])
{
int i,j; // counters
for (i=0; i<Rows; i++)
{
for (j=0; j<Columns; j++)
{
userBoard[i][j] = '~';
}
}
return;
}
void displayBoard(char board[][Columns])
{
int i, j;
printf("\n ");
for (i = 1; i <= Rows; i++)
{
printf("%d ",i+5);
}
puts("");
for (i = 0; i <=Rows; i++)
{
printf("__");
}
puts("");
for (i=0; i<Rows; i++)
{
printf("%d|",(i+1));
for (j=0; j<Columns; j++)
{
printf(" %c", board[i][j]);
}
puts("");
}
return;
}
char bombCheck (char board[][Columns], int a, int b)
{
char gameOver;
if (board[a][b] == '*')
{
puts("");
puts(" BOOM");
puts("You hit a mine.");
puts("you are deaded.\n");
puts(" GAME OVER!!\n");
gameOver = 'y';
}
else
{
gameOver = 'n';
}
return gameOver;
}
int main (void)
{
char gameBoard[Columns][Rows];
char userBoard[Columns][Rows];
char done;
char win;
char gameOver;
int count;
int i;
int col;
int row;
introduction();
do
{
done=win='n';
count=0;
fillGameBoard(gameBoard);
fillUserBoard(gameBoard);
displayboard(userBoard);
bombcheck();
do
{
displayBoard(userBoard);
printf("choose your column, numbered 1-5\n");
scanf(" %i", &col);
printf("choose your row, numbered 1-5\n");
scanf(" %i", &row);
done = bombCheck(col, row, gameBoard);
if (done='n')
{
count+1;
if (count==((Columns*Rows)-Bombs))
{
printf("you win!\n");
done='y';
}
else
{
done='n';
userBoard[col][row]=gameBoard[col][row];
}
}
} while (done != 'y');
printf("do you want to play again? y/n \n");
scanf(" %c", win);
}while (win != 'y');
return 0;
}
You're missing a brace in fillGameBoard().
for (i=0; i<Rows; i++)
{
for (j=0; j<Columns; j++)
{
fscanf(inputFile, " %c", &gameBoard[i][j]);
} /* Note closing brace! */
}
fclose(inputFile);
You're passing the arguments to bombCheck() in the wrong order.
/* Declared: char bombCheck (char board[][Columns], int a, int b) */
done = bombCheck(gameBoard, col, row);
What's with the bombcheck() call with no arguments? Note that bombcheck() is different from bombCheck(). The C programming language is case-sensitive.
For future reference, post only the minimal code snippets relevant to your question, instead of an entire program.
Case matters in C. bombcheck is not the same as bombCheck.
Argument order matters. You have declared bombCheck with (board, a, b) but are calling it with (col, row, board).
Taking the address of an array is redundant. The & is not necessary in scanf("%s",gameDataFileName);
scanf with %s is pretty unsafe. Watch what happens if you type in more than 30 characters (perhaps substantially more). Try fgets instead.
You're missing a closing brace in fillGameBoard (probably in the second inner for loop).
Your indenting is inconsistent in some places, particularly where you have left aligned return statements (and some other statements at the end of blocks).
Overall, this is a pretty good beginner program. Keep at it, and you'll get familiar with those compiler errors in no time!
There is a missing closing brace } to end the fillGameBoard function.
The number of opening and closing braces don't add up.
line 170: wrong order of arguments
line 51: missing }

Resources