printf placement in nested for if [duplicate] - c

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Flushing buffers in C
(1 answer)
Closed 3 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
#include<stdio.h>
int main(){
int T, N, K;
scanf("%d", &T);
for(int i = 1; i <= T; i++){
scanf("%d %d", &N, &K); getchar();
char hall;
int hold = 0;
for(int j = 0; j < N; j++){
scanf("%c", &hall); getchar();
printf("Case #%d:", i);
if(hall == '0'){
hold++;
} else{
hold = 0;
}
if(hold >= K){
printf("Dead\n");
return 0;
}
}
printf("Alive\n");
return 0;
}
return 0;
}
I got a case where i need to make a program that we must know the outcome of a man who trapped inside a building that caught on fire, we have to make a program where we know he ended up Dead or Alive. This problem includes a testcase (int T), length of a hall (int N), and the duration of the man's capability to hold his breath (int K). In the int N (hall) will contain '0' and '1' where each of it indicates there's stair (1) and there's no stair (0); if there's stair that means the man can take a breath.
Example input:
2 -> this is how many testcase
8 2 -> int N and int K, case 1
01010100 -> int N numbers
10 3 -> case 2
0001001110
The output should be:
Case #1: Dead
Case #2: Alive
Code above already works, but i wonder where should i put the printf("Case #%d:", i); because if i put it there, the if wont run so it wont print either Dead or Alive. Does anyone have an idea?

Related

Write a C function that takes a number as a parameter and returns 1 if it is prime, otherwise, it returns 0. It prints 1 for 23 and 0 for 22 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
I just want a 1 or 0 if it is prime or not.
but I am getting multiple 0's and 1's. How can I solve this.
#include <stdio.h>
int num() {
int a, i;
printf("Enter a number:");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
printf("1");
else
printf("0");
}
}
int main() {
num();
return 0;
}
Based on the naming used and specific combination of function use, I am almost certain OP's code is based off this which is my first google response to c check if number is prime.
I challenged myself to "fix" it with least number of modification to the original code, here is the version that works the way OP expects. It is ugly but the point is to make it clear where it differs from his code.
OP seems to have mixed up the inner if statements with the outer if statements, and completely forgot about the counter. Also OP seems to have got confused in the function num, as it should either print 1 or 0 and be a void function, or return 1 or 0 and take a as input to a function that returns int eg int num(int a) or void num(), whereas OP ended up going halfway int num().
The working(if you can call it that, since fflush(stdout) is not called after printf is called, so the program will not not show the question on mingw without winpty) program would look like this:
#include <stdio.h>
void num() {
// a is the user input number
// c is the count
// i is the iterator
int a, i, c = 0;
printf("Enter a number: ");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
++c;
}
if (c != 0)
printf("0");
else
printf("1");
}
int main() {
num();
return 0;
}
The reason you get multiple 0s and 1s is you print them for every potential factor. You should instead test the factors to determine if none of the factors up to the square root of the number divide the number evenly, printing a 1 in this case and a 0 otherwise.
Function isprime should take an int argument and return 1 or 0, the main() function takes case of getting the number from the user and printing the result.
Here is a modified version:
#include <stdio.h>
int isprime(int a) {
int i;
if (a < 2)
return 0;
for (i = 2; a / i >= i; i++) {
if (a % i == 0)
return 0;
}
return 1;
}
int main() {
int a;
printf("Enter a number:");
if (scanf("%d", &a) == 1) {
printf("%d\n", isprime(a));
}
return 0;
}
Also note how the code is indented and uses spaces to improve readability. Learn how to do this for your next projects.

Output the input Array in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
My code:
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
printf("%d", menu[i]);
}
I'm trying to ask the user for input and add it to the array and then at the end to output the whole array e.g 1,2,3,4....16, however as of now it always returns the value 16 no matter what the user input.
You need to run loop twice. Once for taking inputs and then for displaying all numbers.
#include <stdio.h>
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
{
printf("%d\n", menu[i]);
}
}
Your code has an array index bound check failure.
printf("%d", menu[i]);
The value of i here is going to be 16 because you are using it after the loop. The loop terminal condition is i == 16. The menu array is only defined for index values of [0..15]. The value you see in the output is entirely random depending on the state of the execution stack. You could test this by printing instead menu[65] and see random data or maybe a segmentation fault.
Printing out the array to the console is the same loop as your input, but with the printf embedded in it instead. So your code should have 2 loops in it. One loop to gather input, and the other loop to output the input.
The answer is in the comments.
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
printf("%d ", menu[i]);
you can add a loop at the end of your code like this
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for (i = 0;i<16;i++)
{
printf("%d ",menu[i]);
}
}
"I'm trying to ask the user for input and add it to the array and then at the end to output the whole array"
Just because it has not been suggested yet...
This can be done using a single loop, or with no loops at all.
(The looping option below is an adaptation of your code with comments describing differences.)
//The following items, are optionally
//defined here instead of in-line with code.
//they are used to clean up the scanf() and sprintf() calls below
#define data menu[0],menu[1],menu[2],menu[3],menu[4],menu[5],menu[6],menu[7],menu[8],menu[9],menu[10],menu[11],menu[12],menu[13],menu[14],menu[15]
#define input_data &menu[0],&menu[1],&menu[2],&menu[3],&menu[4],&menu[5],&menu[6],&menu[7],&menu[8],&menu[9],&menu[10],&menu[11],&menu[12],&menu[13],&menu[14],&menu[15]
const char input_format[] = {"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d"};
const char format[] = {"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n"};
//it also preferred to avoid magic numbers when possible
#define ELEMENTS 16
#define MAX_LEN_INT 11
//to demonstrate both looping and sequential methods to input and output the same thing
#define USE_LOOP 1 //change to zero for doing this with no loops
int main(void)//added void
{
int menu[ELEMENTS] = {0};
//char buffer `output` should accommodate room for max number of
//characters expressed in 32bit `int` data type: `11` (from the value: `-2147483648`)
//times count of elements to be output: ELEMENTS plus NULL terminator + punctuation.
//This should do it:
int size = ELEMENTS*MAX_LEN_INT+ELEMENTS + 1;
char output[size];//buffer for outputing final line showing user input values
memset(output, 0, sizeof(output));
#if USE_LOOP
int i;
printf("Input array values:\n");//moved outside the loop to display only once
for(i = 0; i < ELEMENTS; i++)
{
printf("enter value %d:\n", i+1);//prompt user for each input value
scanf("%d", &menu[i]);//scan value into array element
}
#else //Use sequential data entry
printf("Enter %d space delimited integer values (eg: 1 2 -45 78... 123) then <enter>:\n", ELEMENTS);
scanf(input_format, input_data);
#endif
//again, outside the loop to display only once
//place all data into printable buffer
sprintf(output, format, data);//using short representations of format specifier and data for readability
printf("%s", output);
return 0; //added return to comply with int function type.
}
Tested with largest possible number of digits using sequential method:

If we want to call switch statement more than 1 in C Program, what should I do? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For example, if I want to call switch statement in for loop, I got an error.How can I correct this issue?If I want to move my switch statement outer part in determined condition which is to be using more than calling switch statement. Thanks in advance.
#include<stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#define SIZE 50
int i = 0;
int main() {
char usertxt[SIZE], myoperator[SIZE];
printf("addition='+',subtraction='-',multiplication='*',division='/'\n");
usertxt[0] = 0;
int x, myarray[SIZE];
printf("How many numbers should be entered? ");
scanf_s("%d", &x);
for (i = 0; i < x; i++) {
scanf_s(" %c", &myoperator[i], 1);
switch (myoperator[i]) {
case '+':printf("Addition operation\n");
printf(" Enter your number: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '-':printf("Subtraction operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '*':printf("Multiplication operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '/':printf("Division operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
default :if (myoperator[i] == '\0') {
break;
};
}
}
}
As #Gerhardh said, welcome to SO.
But I really think that the logic behind your code isn't good enough.
I take some time to understand your goal and I make a new clearer version.
While testing and understanding your code, I've encountered the following problems:
Implicit declaration of function 'scanf_s' is invalid in C99
Declarations of global variables as counters and their usage inside the loop were the main reason why your code doesn't work as expected.
The printf() function is used for printing the output. It returns the number of characters that are printed. If there is some error then it returns a negative value. You used it like it returns a char or even a string.
Switch statement is useless if you have to do always the same operations.
Char reading doesn't work correctly.
I'm gonna attach here the updated code. Hope that it could be helpful and that actually it has the same "goal" that your code has.
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#define SIZE 500
#define nOperator 4
int main() {
char usertxt[SIZE], myoperator[nOperator];
printf("addition='+',subtraction='-',multiplication='*',division='/'\n");
usertxt[0] = 0;
int nOperations;
int x, myarray[SIZE];
printf("How many numbers should be entered? ");
scanf("%d", &x);
printf("How many operations would you like to try? ");
scanf("%d", &nOperations);
for (int i = 0; i < nOperations; i++) {
fseek(stdin, 0, SEEK_END);
printf("\n\nEnter operation #%d: ", i + 1);
myoperator[i] = getchar();
for (int j = 0; j < x; j++) {
printf("Enter number #%d: ", j + 1);
scanf("%d", &myarray[j]);
}
int k = 0;
for (int m = 0; m < x; m++) {
if (m == x - 1) {
usertxt[k] = myarray[m];
printf("%d", myarray[m]);
} else {
usertxt[k] = myarray[m];
usertxt[k + 1] = myoperator[i];
printf("%d%c", myarray[m], myoperator[i]);
}
k++;
}
printf("\n\n");
}
}
As you can see, I tried to stay as much as next to your code idea and implementation.
For instance, I've not deleted the initial pragma and define. Probably you are going to use them later.
I've used fseek(...) as suggested here:
How to clear input buffer in C?
in order to read correctly char and integers together.
First thing first, it reads the numbers that you want to use and the number of operations that you want to do. After that, it takes the numbers associated with a certain operation, and at the end, it prints the expression as you are doing in your own code.
If you want to add the result, you just need a little edit in the code to sum all the numbers in the array or counting them while reading from input.
Variable Counters Description:
i is for 'myoperator' array
k is for 'usertxt' array
m is for 'myarray' array
Next steps:
Add the result variable to display the result of the operation
Use dynamic memory
Note that:
fseek(...) works on some systems; if not, then it is not surprising as nothing guarantees that it will work when standard input is an interactive device (or a non-seekable device like a pipe or a socket or a FIFO, to name but a few other ways in which it can fail).
If you need that it has to be portable, then check the link that I've placed before.
Hope that it was helpful.
Cheers,
Denny

C: why does my program not continue after while loop? (scanf)

I'm currently learning C and wanted to write a program that takes a number ganzeZahl to determine array length.
Then you have to input the numbers being stored in that array of size n and after that it's supposed to do a selection sort (which I cut out here, because my program doesn't even reach to that part).
I can't get past the while loop whenever I try to run it. It compiles fine.
It never reaches the printf("!!!--------!!!"); //this part isn't reached for some reason? test5.
#include<stdio.h>
int main() {
int ganzeZahl;
scanf("%d", &ganzeZahl);
//printf("ganze Zahl ist: %d\n", ganzeZahl); //test
int array[ganzeZahl];
int i = 0;
for(int z = 0; z < ganzeZahl; z++) {
printf("%d\n", array[z]);
}
while(i<ganzeZahl) {
//printf("!!!hier!!!\n"); //test2
scanf("%d", &array[i]);
//printf("zahl gescannt!\n"); //test 3
i++;
//printf("i erhöht!\n"); //test 4
}
printf("!!!--------!!!"); //this part isn't reached for some reason? test5
//selection sort here
//[...]
return 0;
}
Your program does execute correctly, and eventually reaches the last printf call.
When, it enters the whileloop, it keeps on calling scanf, what causes it to stop and wait until you enter a value every iteration. If you provide ganzeZahl inputs (enter a number and press 'enter'), it will complete the loop and proceed. I guess that if you add a printf before scanf within the loop, it should be more intuitive.
for(int z = 0; z < ganzeZahl; z++){
printf("%d\n", array[z]);
The array is not initialized and so you can't print the array yet.
Actually you messed up with the order of code.The while loop should come first and then the for loop. I have corrected your code below. Happy coding!
#include<stdio.h>
int main() {
int ganzeZahl;
scanf("%d", &ganzeZahl);
//printf("ganze Zahl ist: %d\n", ganzeZahl); //test
int array[ganzeZahl];
int i = 0;
while(i<ganzeZahl) {
//printf("!!!hier!!!\n"); //test2
scanf("%d", &array[i]);
//printf("zahl gescannt!\n"); //test 3
i++;
//printf("i erhöht!\n"); //test 4
}
for(int z = 0; z < ganzeZahl; z++) {
printf("%d\n", array[z]);
}
printf("!!!--------!!!"); //this part isn't reached for some reason? test5
//selection sort here
//[...]
return 0;
}

What does this statement means on a C program? " While (scanf ("%d", &t) ==1)" And why should I write the rest of the program in that while loop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Why should I write the statement "while(scanf("%d",&t)==1)" on the online judges ? Why I get WRONG verdict if i Submit without this statement ? As my IDE (Code blocks compiler) doesn't find any error .
#include<stdio.h>
int main()
{
int t,i;
float h,l,w;
while(scanf("%d",&t)==1)
{
for(i=1;i<=t;i++)
{
scanf("%f%f%f",&l,&w,&h);
if (l<=20 && w<=20 && h<=20)
printf("Case %d: good\n",i);
else
printf("Case %d: bad\n",i);
}
return 0;
}
}
"While" loop isn't necessary. Your code works perfectly fine without while loop, if you write like this:
scanf("%d", &t);
for (i = 1; i <= t; i++)
If you want multiple "t" inputs you should move your return statement after while brace:
int t, i;
float h, l, w;
while (scanf("%d", &t)) {
for (i = 1; i <= t; i++)
{
scanf("%f%f%f", &l, &w, &h);
if (l <= 20 && w <= 20 && h <= 20)
printf("Case %d: good\n", i);
else
printf("Case %d: bad\n", i);
}
}
return 0;
Also, checking if scanf returned 1 is some kind of protection. scanf returns number of elements filled (int this case 1). If you try to write non-digits it returns 0. You can check what your scanf returns with this or similar code:
printf("%d", scanf("%d", &t));
Good luck!

Resources