试图在C中运行多个循环

时间:2016-02-17 00:03:44

标签: c loops nested-loops

我的任务是创建一个程序,该程序使用4个不同的循环来打印相同的东西4次(x, x^2, x^3, x!)。我遇到的问题是,一次只能运行一个循环。如何使所有循环运行,以便我的输出如下:

0 0 0 1
1 1 1 1
0 0 0 1
1 1 1 1
0 0 0 1
1 1 1 1
0 0 0 1
1 1 1 1

下面是我到目前为止编写的代码,但我无法同时运行所有循环。我的输出只会打印到屏幕一次,而不是打印4次。有人可以查看我的代码,让我知道我哪里出错了吗?

#include<stdio.h>

    void main()
    {
    int i =1 ,num;
//Prompt user for an input
    printf("Enter a number: ");
    scanf( "%d", &num);
     if ( num < 0)
            printf("Error: Factorial of negative number doesn't exist.");
     //Loop 1
     for(i = 1; i <= num; i++)

     printf("%d %d %d %d  \n", i, (i) * (i), (i) * (i) * (i), factorial(i));
     //Loop 2
        while(i < num) {
     printf("%d %d %d %d  \n", i, (i) * (i), (i) * (i) * (i), factorial(i));
        i++;
       //Loop 3
        do {
       printf("%d %d %d %d  \n", i, (i) * (i), (i) * (i) * (i), factorial(i));

        i++;
        }while( i < num);

        }   
    //Loop 4 without for, while, do while
    if ( i <= num)
    printf("%d %d %d %d  \n", i, (i) * (i), (i) * (i) * (i), factorial(i));
    i++;
    }


//Function to calculate a factorial

int factorial(int n)

    {
      int c;
      int result = 1;

      for (c = 1; c <= n; c++)
        result = result * c;

      return result;
    }

该程序旨在从用户处获取一个数字,并使用该数字运行4个不同的循环(for,while,do-while,以及通过if语句构造的循环)。

2 个答案:

答案 0 :(得分:0)

您需要重置变量“i”

你有int i = 1;

然后在第一次循环后,我将不会是&lt; = num;

 int i = 1;
 for loop...//1

 i=1;
 while loop...//2

答案 1 :(得分:0)

你的问题并不像我们能得到的那么明确,但是你正在寻找以并行方式运行循环,这可以通过你可以检查的线程来完成:https://computing.llnl.gov/tutorials/pthreads/我做了一个简单的例子没有线程,如果这可以帮助您完成您的工作:

#include <stdio.h>

int factorial(int n) {
  int c;
  int result = 1;

  for (c = 1; c <= n; c++)
    result = result * c;

  return result;
}

void forLoop(int num) {
  static int i = 1;
  int j;
  for(j = 0 ; i <= num && j < 2; i++, j++)
     printf("%d %d %d %d  \n", i, (i) * (i), (i) * (i) * (i), factorial(i));
}

void whileLoop(int num) {
  static int i = 1;
  int j = 0;
  while(i <= num && j < 2) {
    printf("%d %d %d %d  \n", i, (i) * (i), (i) * (i) * (i), factorial(i));
    i++;
    j++;
  }
}

void doWhileLoop(int num) {
  static int i = 1;
  int j = 0;
  do {
    printf("%d %d %d %d  \n", i, (i) * (i), (i) * (i) * (i), factorial(i));
    i++;
    j++;
  } while(i <= num && j < 2);
}
void constructedLoop(int num) {
  static int i = 1;
  int j = 0;
  loop:
    if(i <= num && j < 2) {
      printf("%d %d %d %d  \n", i, (i) * (i), (i) * (i) * (i), factorial(i));
      i++;
      j++;
      goto loop;
    }
}

int main() {
    int i =1 ,num;
//Prompt user for an input
  printf("Enter a number: ");
  scanf( "%d", &num);
  if ( num < 0){
    printf("Error: Factorial of negative number doesn't exist.");
    return 0;
  }
  while(i <= num) {
    forLoop(num);
    whileLoop(num);
    doWhileLoop(num);
    constructedLoop(num);
    i += 2;
  }
  return 0;
}