I wrote this code for a course.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i;
int numbersToPrint;
int fibonacci[50] = {0,1};
int defaultOrCustom;
printf("Do you want to run the default length of 15 numbers, or do you want to define your own length?\n1.Default\n2.Custom\n");
scanf("%i", &defaultOrCustom);
switch (defaultOrCustom){
case 1:
for (i = 2; i < 15; i++)
{
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
printf("%i, ", fibonacci[i]);
}
break;
case 2:
printf("How many numbers in the sequence do you want to print?\n");
scanf("%i\n", &numbersToPrint);
printf("%i", numbersToPrint);
for (i = 2; i< numbersToPrint; i++)
{
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
printf("%i\n", fibonacci[i]);
}
break;
default:{
printf("Please choose a valid option:\n");
main();
}
}
return 0;
}
My problem seems to be that the program hangs in case 2 after the line:
printf("%i", numbersToPrint);
I have verified this on both Linux and Windows, and have spoken to someone who has tried it on Mac, and he says the code works.
No errors show up however.
Any ideas how to fix it?
Change:
scanf("%i\n", &numbersToPrint);
to
scanf("%i", &numbersToPrint);
See c-faq for scanf hanging with '\n'
Related
Basically, I'm trying to create a program where you can read up to 100 inputs from the keyboard.
The inputs must be numbers between [1,100] and when "0" is entered, the program exits the loop and displays an array of all the numbers entered except the number zero.
I'm trying to work with "while,for,if" statements but it's a bit difficult to understand the logic.
Could you guys help me and give me some tips and feedback? Sorry for my ignorance but I'm programming for the first time.
#include <stdio.h>
int main(){
int long ship;
int array[100];
for(ship = 0; ship < 100; ship++){
printf("Repaired ship: ");
scanf("%li", &ship[array]);
while(ship[array] == 0){
printf("\n\t");
for(ship = 0; ship < 100; ship++)
printf("%li ", ship[array]);
printf("\n\nRepaired ships: %li", ship);
}
}
if(ship == 100){
printf("\n\t");
for(ship = 0; ship < 100; ship)
printf("%li ", ship[array]);
printf("\n\nRepaired ships: %li", ship);
}
return 0;
}
I have edited your code with some minor corrections.
In the comments below the code, I help clarify the changes.
Code:
#include <stdio.h>
int main(){
int ship;
int long array[100];
for(ship = 0; ship < 100; ship++)
{
printf("Repaired ship: ");
scanf("%ld", &array[ship]);
if(array[ship]==0)
break;
}
ship=0;
while(array[ship] != 0)
{
printf("\n\t");
printf("%ld ", array[ship]);
ship++;
}
printf("\n\nRepaired ships: %d", ship);
return 0;
}
The long int is not needed for ship as 100 is not that big of a value.
If required, the long int will be used for array.
The format specifier %ld is required for long int.
The for loop handles the input.
We don't need a for loop inside the while as it already deals with the output.
The use array[ship] type notation instead of ship[array] as the former is more common.
This if statement is not needed:
if(ship == 100){
printf("\n\t");
for(ship = 0; ship < 100; ship)
printf("%li ", ship[array]);
printf("\n\nRepaired ships: %li", ship);
}
I am able to write a program to find the mode provided there is only one mode. However, I'm not sure how to alter my code so it can function properly when there is more than one mode.
Here is what I have! Any advice on how to fix my code would be appreciated.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main ()
{
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i<=100)
{
c[i]=0;
i=i+1;
}
scanf("%d", &x);
while ((x>=0) && (x<=100))
{
c[x]=c[x]+1;
if (c[x]>=mode)
{mode=x;}
scanf("%d", &x);
}
printf("the mode is %d\n", mode);
}
You'd want to:
a) Have something that keeps track of how often each value occurred. You're already using an array of "occurrence counts" for this.
b) Find the highest "occurrence count"
c) Find all values that share the highest "occurrence count"
For your code, this can mostly be done by replacing:
if (c[x]>=mode)
{mode=x;}
..with something more like:
if (c[x] > highest)
{highest = c[x];}
..and then doing something like this at the end:
printf("the mode/s are:");
for(i = 0; i <= 100; i++) {
if(c[i] == highest) {
printf(" %d", i);
}
}
printf("\n");
Problem Statement
I'm facing difficulty in solving a programming contest problem, which reads as follows:
You are given T name(s) in english letters. Each name will include some
of the uppercase letters from A to Z, some of the lowercase letters
from a to z and some spaces. You have to transform the name(s) from
lowercase to uppercase. Letters that are originally uppercase
will remain the same and the spaces will also remain in their
places.
Sample Input-Output
If I type this in...
5
Hasnain Heickal Jami
Mir Wasi Ahmed
Tarif Ezaz
Mahmud Ridwan
Md Mahbubul Hasan
the computer should output this...
Case 1: HASNAIN HEICKAL JAMI
Case 2: MIR WASI AHMED
Case 3: TARIF EZAZ
Case 4: MAHMUD RIDWAN
Case 5: MD MAHBUBUL HASAN
Note that exactly one space is required between the semi-colon and the initial letter of the name.
My Coding
This is what I've coded in C:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
int main(void)
{
int T, i;
char string [100];
scanf("%d", &T);
for (i=0; i<T; i++)
{
gets(string);
printf("Case %d: ", i);
while (string[i])
{
putchar (toupper(string[i]));
i++;
}
printf("\n");
}
getch();
return 0;
}
Now, this code fails to produce the desired output. Where am I doing it wrong? Is there any matter with my syntax? Can somebody guide me? Please bear in mind that I'm a middle-schooler and just a beginner in C.
You need to cycle over each letter of the string one-by-one.
In this code below, I have done that with variable K, which goes from 0 to the length of the string.
Variable I keeps track of the number of strings.
int main(void)
{
int T, i, k;
char string [100];
scanf("%d", &T);
for ( i = 0; i < T; ++i)
{
gets (string);
for(k=0; k<strlen(string); ++k)
{
putchar (toupper(string[k]));
}
}
getch();
return 0;
}
In response your question: IDEOne Link
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
int T, i,k;
char string [100];
scanf("%d ", &T);
for ( i = 0; i < T; ++i)
{
gets (string);
printf("[%d] : %s\n", i, string);
for(k=0; k<strlen(string); ++k)
{
putchar (toupper(string[k]));
}
putchar('\n');
}
return 0;
}
Please go through the code and implement the test cases scenarios as per your requirement.
#include <stdio.h>
#include<string.h>
int main(){
char string[100];
int i;
scanf("%s",string);
for(i=0;i<strlen(string);i++){
string[i]=string[i]-32;
}
printf("%s",string);
return 0;
}
I want to repeat a set of command in my C program. This will depend on the number that the user enters. For example: if user enters 3, the codes inside the while loop I have will repeat 3 times. Here is my code:
#include <stdio.h>
int main(void){
int num1,i,num2,num3;
printf("Enter your number:");
scanf("%d", &num1);
num1 = i;
while (i < num1) {
printf("Enter days");
scanf("%d", &num1);
printf("Hello World");
printf("Bye World");
}
}
When I run the program it just asks me the number to enter and then the program ends.
num1 = i;
i is just declared not initialized and you compare it in loop-
while (i < num1) {
Initialize i and then use it .
What you wrote in question and what you did is little confusion , but to make it work -
i=0;
//num1=i; I didn't get these parts so commented it
while (i < num1) { //you loop will run now
// printf("Enter days"); // these also didn't get it either
//scanf("%d", &num1);
printf("Hello World");
printf("Bye World");
i++;
}
You can use a while loop if you want, but using a for loop might make more sense and reduce the amount of code you need to write. I think that in this case the following would be reasonable:
#include <stdio.h>
int main(void){
int num1, i;
printf("Enter your number:");
scanf("%d", &num1);
for(i = 0 ; i < num1 ; ++i) {
printf("Hello World");
}
printf("Bye World");
}
Best of luck.
num1 = i;
while (i < num1) {
How it is possible, while condition will be false always. It should be like
i = 0;
while (i < num1) {
Rest all looks good.
Hello everyone,
I decided some time ago to write my own version of Minesweepers as some practice and I did it. The game ran perfectly, but after deciding to add a "Choose difficulty" option the window freezes and I get an error message, saying that the program does not respond. Also the line 0xC0000005 appeares. I have tryed many, many things: moving code from main() to a seperate function(now all in int playGame()), allocating some more memory in the heap, even creating a seperate .c file to store some piece of the code, but nothing worked sofar. I came back to the code after a few weeks, but I still have no clue why it is happening.
Can anyone help me with this? I hope my code is not hard to read. I added some comments explaining what is what. I am still new to C.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "difLvl.c"
int displayFiled(char **field); //prints out the map of the field
int combine(char answer, int answer1); //combines user input and field numeration
int Randomizer(int **mineArray); //generates random mine map
int difficulty();
int playGame();
int main(){
int playGame();
playGame();
system("PAUSE");
return 0;
}
int Randomizer(int **mineArray){
int difficulty();
int i, j;
srand(time(NULL));
int mines;
int placeMine;
int totalMines;
//int difLvl=2;
int difLvl=difficulty();
for(i=0, totalMines=0; i<10; i++){
for(j=0, mines=0; j<10 && mines<difLvl; j++){
placeMine= rand() % 2;
mineArray[i][j] = placeMine;
if(placeMine==1){
++mines;
};
};
totalMines+=mines;
};
return totalMines;
}
int displayFiled(char **field){
int i, j;
printf(" A B C D E F G H I J\n");
printf(" --------------------\n");
for (i=0; i<10; i++){
if (i==9){
printf("%d |", i+1);
}else{
printf("%d |", i+1);
};
for (j=0; j<10; j++){
printf("%c ", field[i][j]);
if (j==9){
printf("\n");
};
};
};
printf("\n");
return 0;
}
int playGame(){
int displayFiled(char **field);
int combine(char answer, int answer1);
int Randomizer(int ** mineArray);
char Y_char; //column as character (a, b, c etc.)
int X; //row
int Y; //Y_char converted to a number
int **mineArray; //stores the map of mines
char **fieldDisplay; //prints out the map of the field
int i, j; //counters
int life=1;
int movePl=0; //no dying on the first move
int globalMines; //number of mines placed
int openedFields=0; //counts the number of fields opened
//int difLvl;
//int difficulty();
//difLvl= difficulty();
/*disabled the trhee lines above while I was trying some solutions*/
/*int difficulty() is now called from int Randomizer()*/
system("cls");
/*Allocates memory to mineArray*/
mineArray= (int*)calloc(10, sizeof(int));
for(i = 0; i < 10; i++){
mineArray[i] = calloc(10, sizeof(int));
};
/*Allocates memory to fieldDisplay*/
fieldDisplay= (int*)calloc(10, sizeof(int));
for(i = 0; i < 10; i++){
fieldDisplay[i] = calloc(10, sizeof(int));
};
/*default look of fields with ?*/
for (i=0; i<10; i++){
for (j=0; j<10; j++){
fieldDisplay[i][j]='?';
};
};
globalMines= Randomizer(mineArray);
while(life==1 && openedFields<(100-globalMines)){
/*for checking purposes only*/
/*for (i=0; i<10; i++){
for (j=0; j<10; j++){
printf("%d ", mineArray[i][j]);
if (j==9){
printf("\n");
};
};
};*/
//printf("\nDifficulty level %d\n", difLvl);
printf("Total number of mines is %d\n\n", globalMines);
printf("\tMove nr. %d\n\n", movePl+1);
displayFiled(fieldDisplay);
printf("Which field do You want to activate?\nType first the letter, space and then the number (A 1, B 10 etc.)\n");
scanf("%c %d", &Y_char, &X);
if (Y_char >= 'A' && Y_char <= 'Z'){
Y = Y_char - 'A';
}else if(Y_char >= 'a' && Y_char <= 'z'){
Y = Y_char - 'a';
};
/*checks if a field is a mine*/
/*X-1 because the player chooses from 1 to 10*/
if (mineArray[X-1][Y]==0 && fieldDisplay[X-1][Y]=='?'){
movePl++;
fieldDisplay[X-1][Y]='0';
openedFields=openedFields+1;
OPEN : if (((X-2)<10) && ((X-2)>=0)){
if (mineArray[X-2][Y]==0 && fieldDisplay[X-2][Y]=='?'){
fieldDisplay[X-2][Y]='0';
openedFields=openedFields+1;
};
};
if ((X<10) && (X>=0)){
if (mineArray[X][Y]==0 && fieldDisplay[X][Y]=='?'){
fieldDisplay[X][Y]='0';
openedFields=openedFields+1;
};
};
if (((Y+1)<10) && ((Y+1)>=0)){
if (mineArray[X-1][Y+1]==0 && fieldDisplay[X-1][Y+1]=='?'){
fieldDisplay[X-1][Y+1]='0';
openedFields=openedFields+1;
};
};
if (((Y-1)<10) && ((Y-1)>=0)){
if (mineArray[X-1][Y-1]==0 && fieldDisplay[X-1][Y-1]=='?'){
fieldDisplay[X-1][Y-1]='0';
openedFields=openedFields+1;
};
};
system("cls"); //clears console screen
}else if (mineArray[X-1][Y]==0 && fieldDisplay[X-1][Y]=='0'){
system("cls");
printf("You can't choose an already opened field!\n\n");
}else if(mineArray[X-1][Y]==1 && movePl==0){
/*only activates on the first turn if players hits mine*/
movePl++;
mineArray[X-1][Y]= 0;
fieldDisplay[X-1][Y]='0';
globalMines=globalMines-1;
goto OPEN;
system("cls");
}else{
system("cls");
printf("YOU DIED ! YOU DIED ! YOU DIED !\n\n");
printf("Moves successfully made: %d\n\n", movePl-1);
fieldDisplay[X-1][Y]='1';
displayFiled(fieldDisplay);
--life;
};
};
if(openedFields==(100-globalMines)){
printf("Congratulations! You won the game!\n\n");
displayFiled(fieldDisplay);
};
for(i = 0; i < 10; i++){
free(mineArray[i]);
};
free(mineArray);
for(i = 0; i < 10; i++){
free(fieldDisplay[i]);
};
free(fieldDisplay);
return 0;
}
The difLvl.c file:
#include <stdio.h>
#include <stdlib.h>
int difficulty(){
int difLvl;
while(1){
printf("Please choose a difficulty level:\n");
printf("Easy-1\nNormal-2\nNightmare-3\n");
printf("Your answer: ");
scanf(" %d", &difLvl);
if(difLvl>=1 && difLvl<=3){
break;
}else{
system("cls");
continue;
};
};
system("cls");
return difLvl;
}
I created it, because I thought that maybe main() had too many code in it and that maybe that was why the difficulty option wasnt working right.
EDIT
After the user is promped to enter the difficulty level, the mine map is created, but after choosing a filed, the program crashes.
SOLVED
scanf("%c %d", &Y_char, &X);
changed to
scanf(" %c %d", &Y_char, &X);
First, you don't allocate your two-dimensional fields correctly. The "outer" field must hold int *, not just int:
mineArray = calloc(10, sizeof(*mineArray));
for (i = 0; i < 10; i++) {
mineArray[i] = calloc(10, sizeof(*mineArray[i]));
}
Another potential source of the segmentation fault is that Y might end up uninitialised and therefore with a garbage value. The cause is the scanf:
scanf("%c %d", &Y_char, &X);
Most scanf formats skip white space before the conversion, but %c doesn't. It is very likely that you read the newline character as the char for %c when you expect to read a letter. Because the new-line character is white space, you can hot-fix the by placing a space before the %c? format:
scanf(" %c %d", &Y_char, &X);
(I say hot-fix, because it isn't a good solution. scanf doesn't treat new-line characters specially; they are just space. A better solution might be to read a line first with fgets and then scan that with sscanf. At least you can treat each line as frash input. (And your input really should ensure that bad input is ignored.)
Lastly, it is strange that you include a *.c file. If you want to spread ypur project over various files, which is basically a good idea, you should write a header file for each *.c, which has the file's interface. Include the header files in other *.c files; compile the *.c files into objects separately and then link them. This process is usually controlled by Makefiles or Projects.