I'm have trouble with a for loop. Basically, I get the output that I want, but for the wrong reason. This program prints out
xoxoxoxo
oxoxoxox
xoxoxoxo
oxoxoxox
xoxoxoxo
oxoxoxox
xoxoxoxo
oxoxoxox
The problem is the order in which this is produced. I'm required to have the inner loop iterate 8 times for every outer loop (also iterating 8 times), which isn't happening.
The compiler keeps returning to the if statement instead after printing, instead of returning to check the inner for loop (j).
#include <stdio.h>
int main() {
int i;
int j = 0;
for (i = 1; i < 9; i++) {
for (j = 1; j < i + 4 && j < 5; j++) {
if (i % 2 == 0) {
printf("o");
printf("x");
}
else {
printf("x");
printf("o");
}
}
printf("\n");
}
getchar();
return 0;
}
I assume you misinterpret the behavior of your debugger, and the code actually does exactly what it is supposed to do. Why your debugger does not jump to the head of the for loop but instead immediately to the if again, I cannot say. But they are all different about these things :)
Related
Beginner question on C function here so please bear with me...
#include <stdio.h>
#include <stdlib.h>
int some_function(void);
int result;
result = some_function();
printf("%d", result);
return 0;
}
int some_function(void)
{
int i;
for (i = 0; i < 10; i++)
{
// printf("%d", i);
}
return (i);
}
I commented out the result of running the for loop which is all integers from 0 to 9.
I can not clearly understand why the final result of local int i is increased once more to finally provide a return of 10 out of int some_function(void).
Thank you so much for any help.
for (i = 0; i < 10; i++) says:
Initialize i to zero.
Test whether i < 10 is true. If it is, execute the body of the loop. If it is not, exit the loop.
Increment i and go to step 2.
Therefore, the loop continues executing until i < 10 is false.
When i is nine, i < 10 is true, and the loop does not exit. When i is ten, then i < 10 is false, and the loop exits.
Therefore, when the loop exits, i is ten.
for (i = 0; i < 10; i++) {
...
}
is equivalent to
i = 0
while (i < 10) {
...
i++;
}
When i is 9, the loop body is executed, then i is incremented (and its value is now 10), then the test of the while loop is executed once more, and the loop exits, with i still having the value 10.
I would like to know if there's a way for me to get the current value of "j" outside of the foor loop whenever the conditions is true. The variable "totalvalid" will tell me how many times the condition was met but I would also like to know the exact value of j when the condition is true so that I can use it at a later point. So I would want to extract the value of "j" whenever the "totalvalid = totalvalid +1" happens. Sorry if it looks messy. I'm new to coding and still have no idea how to make it cleaner. Thank you.
for(int j = 0; j < stringnumber; j++){
int valid = 0;
if(str[j][10] == '\0'){
for(int k = 0; k < 10; k++){
if(str[j][k] >= 'A' && str[j][k] <= 'Z'){
valid++;
}
}
if (valid == 10){
totalvalid = totalvalid + 1;
}
}
}
It seems that you want an array of numbers from that pass the condition.
My suggestion would be to make an array of ints, where you will keep these numbers.
Before loop:
int *array_of_valid_ints = (int *) calloc(stringnumber, sizeof(int)); // allocate the array
int number_of_valid_ints = 0;
Inside the if statement:
array_of_valid_ints[number_of_valid_ints] = j;
number_of_valid_ints++;
After the loop ends, you can check the good values with:
printf("This are the good ints: ")
for (int i = 0; i < number_of_valid_ints; i++) {
printf("%d ", array_of_valid_ints[i]);
}
printf("\n");
maybe you can define a variable before the loop as int j=0; then use a while loop instead of for.also remember to write j++ in the while loop.this way you can use the value of j outside of the loop too!
Wrote this to find the prime numbers between 2 to 1000. But it stops after showing that 2 and 3 are prime numbers. I know I can find how to write a code for finding out prime numbers on the internet. But I really need to know what's going wrong here.
#include <stdio.h>
main() {
int i, j;
int ifPrime = 1;
for (i = 2; i < 1000; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
ifPrime = 0;
break;
}
}
if (ifPrime == 1) {
printf("%d is prime\n", i);
}
}
}
The line
int ifPrime=1;
must be inside the outer for loop. There it will be initialized for every i. This corresponds to the natural language words "to check whether a number i is prime, first assume it is. Then check if it is divisible". The code you had before said "to check whether the numbers 2 to 1000 are prime, first assume they are", and this wording was too broad.
The code should be:
int main()
{
for (int i = 2; i < 1000; i++)
{
int ifPrime = 1;
for (int j = 2; j < i; j++)
I replaced main with int main since that is required since 20 years. (You should not learn programming from such old books.)
I moved the int i and the int j into the for loops so that you cannot accidentally use these variables outside the scope where they have defined values.
To avoid this bug in the future, it's a good idea to extract the is_prime calculation into a separate function. Then you would have been forced to initialize the ifPrime in the correct place.
Another way of finding the cause of this bug is to step through the code using a debugger and ask yourself at every step: does it still make sense what the program is doing?
You are not setting ifPrime back to 1 after checking for the single number. So once you get a number that is non_prime, ifPrime is now 0 and hence if(ifPrime == 1) would never return true post that and hence you only see 2, 3 as prime
#include <stdio.h>
int main(void) {
for( int i=2;i<1000;i++)
{
int ifPrime = 1;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
ifPrime=0;
break;
}
}
if(ifPrime==1)
{
printf("%d is prime\n",i);
}
}
return 0;
}
I'm trying to make my own bubble-sort function in C.
As you can see in the code below this, I'm trying to only using while / if loop to create this function. I put 5 numbers (1,3,2,5,4) so that size of array of this would be 5, and I got 5 (I checked it with Python(C)tutor. However, It works well until tab[j] gets 3. I'm trying to figure it out, but couldn't figure it out why it keeps going out when tab[j] gets 3.
Could you anybody explain what's wrong to me? I would appreciate it.
Here is my code below:
#include <stdio.h>
void ft_sort_integer_table(int *tab, int size)
{
int i;
int j;
int tem;
i = 0;
j = 0;
while(tab[i] < size)
{
if(tab[j] > tab[j+1])
{
tem = tab[j];
tab[j] = tab[j+1];
tab[j+1] = tem;
printf("%d ", tab[j]);
j++;
}
else if(tab[j] < tab[j+1])
{
printf("%d ",tab[j]);
j++;
}
i++;
}
}
int main(void)
{
int tab[] = {1,3,2,5,4};
int size = sizeof(tab)/sizeof(*tab);
ft_sort_integer_table(tab, size);
return(0);
}
You'll need an inner loop in your bubble sort, which is responsible for moving the largest element to the back and performing swaps i times (these large elements are "bubbling up"). Start the inner loop at 0 on each iteration and iterate through size - i (we know that the last i elements are sorted and in their final positions).
i controls your outer loop and should be incremented at the end of the loop (just as you would with a for loop). j controls the inner loop and should be incremented at the end of the loop.
While you're at it, it's a good idea to move your printing out of the sort function, which causes an unnecessary side effect and might frustrate your debugging efforts.
Also, it's worth mentioning that (1) for loops are more semantically appropriate here and (2) there is an optimization available by adding a boolean--as soon as you have a pass through the inner loop that performs no swaps, end early!
#include <stdio.h>
void ft_sort_integer_table(int *tab, int size)
{
int i = 0, j, tem;
while (i < size)
{
j = 0;
while (j < size - i)
{
if (tab[j] > tab[j+1])
{
tem = tab[j];
tab[j] = tab[j+1];
tab[j+1] = tem;
}
j++;
}
i++;
}
}
int main(void)
{
int tab[] = {1,3,2,5,4,6,7,1,5,6,8,9,1,4,5,1,2};
int size = sizeof(tab) / sizeof(*tab);
ft_sort_integer_table(tab, size);
for (int i = 0; i < size; i++)
{
printf("%d ", tab[i]);
}
return(0);
}
Output:
1 1 1 1 2 2 3 4 4 5 5 5 6 6 7 8 9
I'm trying to figure it out, but couldn't figure it out why it keeps
going out when tab[j] get 3.
From your code above, j increment in the same fashion as i. That means both variables will have the same value since j will be incremented by one after the if-then-else statement, and i will also be incremented by one at the end of each loop. Therefore, tab[j] is referencing the same value as tab[i]
With that being said, the boolean condition in the while loop checks whether the value in the tab[i] is less than the value of size.
When i == 3, tab[i] == 5 since in the loop, only the values in the array of index less then i are swapped/changed. Since the size variable holds that value of 5, tab[i] < size will result in a false value and exit the loop.
More information on bubble sort can be found here, https://www.geeksforgeeks.org/bubble-sort/
if don't use else, the answer will be only one .just like 11111...111, when use else, I can get the right answer.
the codes:
void f(int cur, int n)
{
if(cur == n)// print answer
{
for(int i = 0; i < n; i++)
printf("%d", A[i]);
printf("\n");
}
//else no else no whole answer
for(int i = 1; i <= n; i++)
{
A[cur] = i;
f(cur + 1, n);
}
}
If you do not add else then, when cur == n, your function will also execute this for statement:
for(int i = 1; i <= n; i++)
{
A[cur] = i;
f(cur + 1, n);
}
But when you do, each time your condition is true you will only execute
if(cur == n)// print answer
{
for(int i = 0; i < n; i++)
printf("%d", A[i]);
printf("\n");
}
instead of both.
Without that else the code never stops.
Each call of function f() checks if (cur == n), prints something if this is true then, no matter the above condition, it enters the for loop. On its first iteration it calls itself with the next value of cur and everything repeats forever.
Well, not really forever. Since at every call it writes in the A array without any bounds checking, sooner or later it will attempt to write at an address that is not writeble and the SO will kick in and forcibly terminate the program.
Ok, let's imagine cur == n. (cur = 3 and n = 3)
Then f() would print the output, but it also continuous with the rest of the code.
So if f(3, 3) would be called, after the printing the A[] array it would continue with the second for loop calling f((3 + 1), 3) and this again would call f((4 + 1), 3) and so on, forever (or when your program crashes due to out of bound memory).
Conlusion: your function should stop at a moment and return to terminate, which it doesn't.