#define MAX 20 //defines max as 20
#include< stdio.h>
main() //main function starts
{
int a[MAX],i,n; //defines a array along with some variables `
printf("Enter the value of n\n"); //take the size of the array from user
scanf("%d",&n); //reads the value
printf("Enter the numbers\n"); //asks to enter the values of array
for(i=0;i< n;i++) //for loop is used to read the elements of the array
scanf("%d",&a[i]); //reads the element
i=0; //initialises i to zero to point it to the first element of array
do //starts the do while loop
{
a[i]=a[i]+1; //increases the stored value of the array by 1
i++;
} while(i< n); //checks the while condition whether i is less than n
printf("The final array is \n");
for(i=0;i< n;i++) //for loop is used to print the array
printf("%d\t",a[i]); //prints the final array
}
如果i的值在do while循环内部发生变化,并且如果它发生变化,那么效率是否会发生变化。
如果while循环改变如下,效率
int j=0;
do{
if(j==n-2 || j==n-3)
i--;
else
{
a[i]=a[i]++;
i++;
j++;
}
} while(i< n);
答案 0 :(得分:1)
答案是O(3n)= O(n),因为你的循环从0增加到(n-1)3次..
答案 1 :(得分:0)
算法为O(∞),因为i
永远不会在中间循环中递增。
答案 2 :(得分:0)
O(n)
我认为这是您尝试以“聪明”的方式编写的内容:
#include< stdio.h>
main()
{
int *a;
int i;
int n;
printf("Enter the value of n\n");
scanf("%d",&n);
a = (int*)malloc(n * sizeof(*a));//dynamically allocate the array in the needed size.
printf("Enter the numbers\n");
for(i=0; i<n; ++i)
{
scanf("%d",&a[i]);
}
for(i=0; i<n; ++i)
{
a[i]++;
}
for(i=0; i<n; ++i)
{
printf("%d\t",a[i]);
}
}