variable unexpectedly changing - c

I'm learning the C and writing a program to calculate factorials. When I print the value of the variable it is displayed as "1111111111". I checked and upon initialization it is "1". I think its possibly an overflow but the problem is I do not know why it is happening. For the first iteration the prev_num variable should read "1".
#include <stdio.h>
int main(void)
{
int prev_num = 1;
int n = 0;
for (n=1; n<=10; n++)
printf("%i", prev_num);
prev_num = prev_num * n;
return 0;
}

You have forgotton the brackets around your for loop:
for (n=1; n<=10; n++) {
printf("%i\n", prev_num);
prev_num = prev_num * n;
}
Also, add a newline character to list the numbers below each other.

This is how the computer sees your program:
int main(void)
{
int prev_num = 1;
int n = 0;
for (n=1; n<=10; n++) // The loop runs 10 times
{
printf("%i", prev_num); // Every time, print the value "1"
}
prev_num = prev_num * n; // This line is NOT part of the loop!
return 0;
}
Indenting a line does not make it part of a loop.
Only putting { } around a set of statements makes it part of a loop.
When there are no brackets, only ONE line below the loop will be part of the loop.

Related

Can someone please explain why this C function is returning the value of 10?

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.

Why isn't this program showing any number above 3?

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;
}

Nested for loops in C

I'm try to complete a task set by a lecturer and I have the following code:
#include <stdio.h>
#define N 100
int main(void)
{
int i, a, cnt = 1;
for (a = 1; a < 6; a++){
for (i = 0; i < N; i++, cnt++) {
if (a%2 > 0){
a = 3*a + 1;
}
else{
a = (a/2);
}
printf("%3d\n", a);
if (a == 1){
printf("Count: %d\n", cnt);
return 0;
}
}
}
return 0;
}
The point of this code is to run a hailstone sequence on each integer, a. For now I have it to start at a = 1, then adding 1 to a, and running the sequence again up until a = 5.
This code runs it for the initial value of a but doesn't then add one to a to run it again. I really can't see why it won't do the outer loop again, please help!
A hailstone sequence is where it takes the integer before it in the sequence, if this integer is odd it computes 3*a +1, and if the integer is even it computes a/2. I've told the sequence to stop once a = 1.
Thanks in advance!!
Instead of return 0; in second loop add break; to move out of the inner loop and continue with outer loop.
If you don't want to add break this is another way and there are minor changes in your code which I have highlighted below.
1. You will have to reinititlize cnt for every new value of a.
2. You will have to take a new variable instead of a for calculations
3. For moving out of loop you can increase value of i.
#include<stdio.h>
int main()
{
int i, a, cnt=1, b;
for(a=1; a<6; a++){
cnt = 1;
b = a;
for(i=0; i<100; i++, cnt++){
if(b%2 > 0){
b = 3*b + 1;
}
else{
b = b/2;
}
printf("%d ", b);
if(b==1){
printf("\nCount %d\n", cnt);
i = 100;
}
}
}
return 0;
}
I'm only a student too, but try removing the first "return 0;", I think that's what is ending the code early.
return will end the function. I think what you are looking for is break

simple C program isn't working

I wrote this program:
#include <stdio.h>
/*Part B
Write a program that:
defines an array of 10 ints
assigns factorial(x) to array element x, for x in the range 0 through 9, inclusive
copies those array elements into a second array of 10 ints, but in reverse order (i.e., element 0 is factorial(9), element 1 is factorial(8), and so on)
prints out that second array to the terminal*/
int factorial(int n){
int factorial = 1;
while(n>1){
factorial = n*factorial;
}
return factorial;
}
int main(int argc, char **argv){
int arr1[10];
int arr2[10];
int i = 0;
for(i = 0; i<10; i++){
printf("%d", i);
arr1[i] = factorial(i);
}
for(i = 9; i>=0; i--){
arr2[i] = arr1[9-i];
printf("%d ", arr2[i]);
}
printf("\n");
return 0;
}
but when I run it it just sits there. I think it's something to do with the call to factorial, because when I comment that out it works instantly, but with it in, it isn't even getting to the first printf.
What am I doing wrong?
while(n > 1){
factorial = n*factorial;
}
you missed n--;
Your while loop:
while(n>1){
factorial = n*factorial;
}
Will run forever. There is nothing in that loop that can change n, so if the loop is entered then we know n will always be greater than 1. You should decrement n within your loop:
while(n > 1){
factorial = n--*factorial;
}
If you aren't used to seeing decremenent like that you can also do it on a new line:
while(n>1){
factorial = n*factorial;
n--;
}
You should decrement n in factorial function.
You have a wrong implementation of factorial method.
int factorial(int n){
int factorial = 1;
while(n>1){
factorial = n*factorial;
n--;
}
return factorial;
}
Your code simply didn't do anything with n variable and kept multiplying, without ever decreasing n value. Hope this helps

Controlled nested looping

I have the nested loops that nested (r=) 3 times. Each loop running for (n=) 5 times.
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
for (k=0; k<n; k++)
//
}
}
But how do we do the nesting dynamically at run time. Say we know it should be nested r times. Each loop running n times. I thought something like recursion but it goes indefinitely.
funloop (int r)
{
for (int i = 0; i < n; i++)
{
//
if (r < 3)
funloop (r++);
else
return;
}
}
Please let me know how this could be done? I couldn't find a sources online.
If you don't know the depth of the recursion statically, the most common approach is to use recursion to represent the looping. For example, suppose that you need to have d levels of nesting of loops that all need to iterate k times. Then you could implement that using recursion of this form:
void RecursivelyNestIterations(unsigned d, unsigned k) {
/* Base case: If the depth is zero, we don't need to iterate. */
if (d == 0) return;
/* Recursive step: If we need to loop d times, loop once, calling the
* function recursively to have it loop d - 1 times.
*/
for (unsigned i = 0; i < k; ++i) {
/* Recurse by looping d - 1 times using the same number of iterations. */
RecursivelyNestIterations(d - 1, k);
}
}
Hope this helps!
The simplest method is just to collapse it to one for loop:
for(i=0; i<pow(n, r); i++) {
}
That can however make it difficult to access the loop counters, if you need them, but that can be done mathematically. For example, the innermost loop counter variable value is given by :
int c = i % n;
You could have an array of such counters and determine the values with similar equations, or you can just increment them, when required, e.g.:
void iterate(int r, int n) {
int i, rc, *c = malloc(sizeof(int) * r);
memset(c, 0, sizeof(int) * r);
for(i = 0; i < pow(n, r); i++) {
// code here, using loop counters in the 'c' array, where c[0] is counter
// for the outer loop, and c[r - 1] is the counter for the innermost loop
// update the counters
rc = r;
while(rc > 0) {
rc--;
c[rc]++;
if(c[rc] == n) {
c[rc] = 0;
} else {
break;
}
}
}
free(c);
}
Just call if (r) funloop(r-1); in the loop body.
#include <stdlib.h>
#include <stdio.h>
static int n = 3;
void _funloop(int cur,int total)
{
if(cur!=total)
{
for(int cnt=0;cnt!=n;++cnt)
{
fprintf(stdout,"%d::%d\n",cur,cnt);
}
_funloop(cur+1,total);
}
}
void funloop(int total)
{
_funloop(0,total);
}
int main()
{
funloop(10);
return 0;
}
A solution that doesn't use recursion is discussed in this Tip
[link]http://www.codeproject.com/Tips/759707/Generating-dynamically-nested-loops
The code is in C++ and require # for the include and define statements
include <iostream>
define MAXROWS 9
define MAXVALUES 9
using namespace std;
char display[] = {'1','2','3','4','5','6','7','8','9'};
int main() {
int arrs[MAXROWS]; // represent the different variables in the for loops
bool status = false;
for (int r=0;r<MAXROWS;r++)
arrs[r] = 0; // Initialize values
while (!status) {
int total = 0;
// calculate total for exit condition
for (int r=0;r<MAXROWS;r++)
total +=arrs[r];
// test for exit condition
if (total == (MAXVALUES-1)*MAXROWS)
status = true;
// printing
for (int r=0;r<MAXROWS;r++)
cout << display[arrs[r]]; // print(arrs[r])
cout << endl; // print(endline)
// increment loop variables
bool change = true;
int r = MAXROWS-1; // start from innermost loop
while (change && r>=0) {
// increment the innermost variable and check if spill overs
if (++arrs[r] > MAXVALUES-1) {
arrs[r] = 0; // reintialize loop variable
// Change the upper variable by one
// We need to increment the immediate upper level loop by one
change = true;
}
else
change = false; // Stop as there the upper levels of the loop are unaffected
// We can perform any inner loop calculation here arrs[r]
r=r-1; // move to upper level of the loop
}
}

Resources