I'm trying to pass the code to list prime OpenMP numbers, I have two problems,
The first problem is to remove the Break and that the code works
the second problem is that marks this error error: missing increment expression
List item
in the line of for (count = 2; count <= n;)
// If I add an expression as count ++ code does not work correctly.
Here is my codes :
int n, i = 3, count, c;
// n is the number's prime
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
}
Depends on the rest of the code, but:
If you delete the increment in the first FOR loop, the error is obvious. You cant delete that. "count ++" is mandatory.
Check if the initial valor of count is less than n (i.e: if "n" is 1, and you start with count =2, the FOR loop will not start)
Be careful: in the first IF block, you are trying to modify the value of "count", but that variable is being used by the FOR loop to control the remaining iterations. As I said, it depends on the code functionality, but usually you dont want that to happen (modify a loop-control variable)
Without further information, I'm afraid we wont be able to help you more.re.
Related
My book says for programming using while-loop, we must first initialize with a number, provide the condition mentioning 'while', and then it's to be followed by the statement to partake in the loop until the condition is met as well as to increment value in the loop.
Example :
i = 1;
while(i<=10)
{
s = s + i;
p = p * i;
i++;
}
But, in case of summing of odd numbers program no such incrementing value has been shown.
And, strangely enough(for me), I get correct result w/o the use of i++. I absolutely cannot wrap my head around why that is the case. Is mentioning i++ or i+1 not really a rule within loops?
int s, i, n;
s = 0;
i = 1;
while (i <= n)
{
s = s + i;
i = i + 2;
}
This line is the incrementing value:
i = i + 2;
The first loop increments by 1 with i++. But since you only want the odd numbers, you need to increment by 2.
You can simplify this to:
i += 2;
There is no such rule that we must use i++ in every loop(and for that matter using i as a loop variable).
As #Barmar indicated, you are incrementing i using the line :
i = i + 2;
There are cases where we need to increment by 3, 10, √n, logn, etc.
There are even cases where we need to run a loop backwards hence, we decrement i.
The point is, the value of i must change at some point otherwise we'll end up in an infinite loop.
#import <stdio.h>
int main(void) {
int sum,i;
sum = 0;
for(i=0;i<10;i++) {
if(i%2)
continue;
sum+=i;
}
printf("\n%d",sum);
return 0;
}
How does if(i%2) works in the above code?
In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).% is the modulus operator.
So i%2 returns the remainder left after i is divided by 2.
Therefore if i is odd i%2=1(TRUE)
else it is 0(FALSE).(even condition)
Therefore if i is even i is added to sum else the loop continues.
if condition knows only TRUE or FALSE.
If your modulo operation make a true condition then it will execute continue. Otherwise it will do sum.
**True condition = any number without zero(0)
Here, the % used is called the modulo operator. It checks the remainder of a division.
Regarding the if statement, the C11 standard says, from chapter §6.8.4.1
Syntax : if ( expression ) statement
and
... the first sub-statement is executed if the expression compares unequal to 0.
So, for a statement like if(i%2), the result
is TRUE, when the i value is not a multiple of 2, i.e., produces a non-zero remainder, so continue; is encountered.
is FALSE, when i is perfectly divisible by 2. so, continue; is skipped and
sum+=i; is executed.
That said, there is no #import <stdio.h> in C, it should be #include <stdio.h>
Finaly,
How does if(i%2) works in the above code?
It is used to add all the even numbers up to 9. The result, 20, is then printed out.
The condition in the if statement
if ( i % 2 )
is equivalent to
if ( i % 2 != 0 )
This condition is equal to true if i is an odd number.
So the program finds the sum of even numbers in the range [0, 10 )
According to the C Standard (6.8.4.1 The if statement)
2 In both forms, the first substatement is executed if the
expression compares unequal to 0.
Here "the first substatement" means the if statement (if else is present then it is the second substatement).
It is better to rewrite the loop without the break statement. For example
for ( i = 0; i < 10; i++ )
{
if ( i % 2 == 0 ) sum += i;
}
It is the same as
for ( i = 0; i < 10; i += 2 )
{
sum += i;
}
I know that I shouldn't put semicolon after a loop. But I am learning and accidentally I inserted one. And I wanted to know exactly what is happening with my error. So next time something similar happens, I know the source of the mistake.
In the following code below, in this portion of the code:
triangularNumber = 0;
for ( n = 1; n <= number; ++n )
;
I accidentally inserted a semi colon after the for loop. When I execute the entire code, it prompts the user to insert a number for calculating a TriangularNumber. But with the semicolon the result is wrong. For example, when I insert 10, the answer should be 55, but with the semicolon error it delivers to me 56. I wanted to understand why 56.
The complete code is below:
#include <stdio.h>
int main(void)
{
int n, number, triangularNumber, counter;
for(counter = 1; counter <=5; counter++)
{
printf("What Triangular Number do you want?");
scanf("%i", &number);
triangularNumber = 0;
for ( n = 1; n <= number; ++n )
**;**
triangularNumber += n;
printf("Triangular number %i is %i\n\n", number, triangularNumber);
}
return 0;
}
The other answers are all good, but to answer your question about why you get the specific number that you do (which would be 11 when you enter 10, not 56), it's because this:
for ( n = 1; n <= number; ++n )
;
does essentially nothing except loop until n is exactly 1 more than number, so when number is equal to 10, n will equal 11.
Then, this:
triangularNumber += n;
just sets triangularNumber to 11, since before the loop you set it to 0, so when it's sitting outside the loop as it does with the semi-colon there, triangularNumber += n; is basically equivalent to triangularNumber = n;.
Incidentally, if you'd defined n within the for loop, instead of at the beginning of main(), like so (you may need to put your compiler in C99 mode with -std=c99 or similar to do this):
for ( int n = 1; n <= number; ++n )
;
triangularNumber += n;
then you'd have spotted the error immediately because the program wouldn't compile, as by the time you got to triangularNumber += n; outside the loop, n would no longer be in scope. This is one good reason why limiting the scope of your variables to the minimum amount of code you need it can often be a good idea.
The second for statement has no braces, so the code runs ; number times!
You want:
for ( n = 1; n <= number; ++n )
{
**;**
triangularNumber += n;
}
Think of it like this:
loop {
do this;
and also this;
}
and more code outside the loop;
now, if you have a ";" with no code it will look like this:
loop {
;
}
and more code outside the loop;
the ; is a blank statement that gets run each time through the loop.
now if you remove the brackets take a look at this:
loop
;
and some code outside of the loop;
since there are no brackets the loop will only contain the very next line of code, in this example the empty line ";". then the line after that "and some code outside of the loop;" gets executed no matter what since it is outside of the loop.
basically, the code is interpeted as having brackets around one line of code if you don't have brackets. anything after the one line is outside of the brackets and is not in the loop.
i hope this clears things up!
The keyword for is a preface for a single statement that is run each time the loop completes. Since a semicolon ends a statement, the following loop does precisely nothing upon each iteration.
for ( n = 1; n <= number; ++n ) ;
Then execution continues to the subsequent statement (triangularNumber += n;), which is executed one time.
The same principle applies to if, while, and do keywoards as well. What gives you flexibility in all of these cases is this rule: Everything enclosed within a pair of braces is considered as one statement.
Thus, your code needs to look like one of these examples to work how you probably want it to.
for ( n = 1; n <= number; ++n ) triangularNumber += n;
-or-
for ( n = 1; n <= number; ++n )
{
triangularNumber += n;
} //everything between the braces is considered to be the one statement executed by the loop
So I'm trying to check if an array that was previously inputted is increasing in intervals of 1, starting with the number 1 and ending with n (n being the array size).
Here's what I got so far:
for (int i =0; i<n;i++){
for (next=i;next<n;next++){
if(arr[i]+1 = arr[next]){
x = 1; //ignore this, it relates to the rest of the code.
}
else{
printf ("\nThis is not a permutation.");
break;
}
}
}
Now, my thinking is that this code would compare parameters that are next to each other, and if the following parameter is equal to the previous +1, then it is obviously increasing by 1. Problem is, when this is false, it wont print "This is not a permutation," and wont break the loop.
Any help would be appreciated.
Also, any insight as to checking if the array starts with the number 1 would be appreciated.
Thanks
Looks like in this line:
if(arr[i]+1 = arr[next]){
You intended comparison:
if(arr[i]+1 == arr[next]){
Have you tried if(arr[i]+1 == arr[next]) instead of if(arr[i]+1 = arr[next])??
If you need to check that a sequence is increasing, why are you comparing every element against the others? You should only need one for loop:
for (i = 1; i < n; i++)
{
if (arr[i - 1] + 1 == arr[i])
... // keep going
else
... // not a permutation
}
Basically, what your code does is check that every element after the i-th one is greater than that i-th one by one. Ultimately, this leads to an impossible case (as two numbers must be equal but must differ by one at the same time).
It sounds like you want to test if arr[0] == 1 and every subsequent array element is 1 greater than the previous element. Isn't that the same as checking your array for the values [1,2,3,...,n]?
for (int i = 0; i < n; ++n) {
if (arr[i] != i + 1) {
printf("\nThis is not a permutation.");
break;
}
}
I know a while loop can do anything a for loop can, but can a for loop do anything a while loop can?
Please provide an example.
Yes, easily.
while (cond) S;
for(;cond;) S;
The while loop and the classical for loop are interchangable:
for (initializer; loop-test; counting-expression) {
…
}
initializer
while (loop-test) {
…
counting-expression
}
If you have a fixed bound and step and do not allow modification of the loop variable in the loop's body, then for loops correspond to primitive recursive functions.
From a theoretical viewpoint these are weaker than general while loops, for example you can't compute the Ackermann function only with such for loops.
If you can provide an upper bound for the condition in a while loop to become true you can convert it to a for loop. This shows that in a practical sense there is no difference, as you can easily provide an astronomically high bound, say longer than the life of the universe.
Using C
The basic premise is of the question is that while loop can be rewritten as a for loop. Such as
init;
while (conditional) {
statement;
modify;
}
Being rewritten as;
for ( init; conditional; modify ) {
statements;
}
The question is predicated on the init and modify statements being moved into the for loop, and the for loop not merely being,
init;
for (; conditional; ) {
modify;
}
But, it's a trick question. That's untrue because of internal flow control which statements; can include. From C Programming: A Modern Approach, 2nd Edition you can see an example on Page 119,
n = 0;
sum = 0;
while ( n < 10 ) {
scanf("%d", &i);
if ( i == 0 )
continue;
sum += i;
n++;
}
This can not be rewritten as a for loop like,
sum = 0;
for (n = 0; n < 10; n++ ) {
scanf("%d", &i);
if ( i == 0 )
continue;
sum += i;
}
Why because "when i is equal to 0, the original loop doesn't increment n but the new loop does.
And that essentially boils down to the catch,
Explicit flow control inside the while loop permits execution that a for loop (with internal init; and modify; statements) can not recreate.
While loops can be more helpful when the number of loop iterations are not known while for loops are effective when the loop iterations are known.
Consider the following code snippet for student marks, but the number of students is not known
ArrayList studentMarks = new ArrayList();
int score = 100;
int arraySize = 0;
int total = 0;
System.out.println("Enter student marks, when done press any number less than 0 0r greater than 100 to terminate entrancies\n");
while(score >= 0 && score < 101) {
System.out.print("Enter mark : ");
score = scan.nextInt();
if(score < 0 | score > 100)
break;
studentMarks.add(score);
arraySize += 1;
}
// calculating total, average, maximum and the minimum values
for(int i=0;i<studentMarks.size();i++) {
total += studentMarks.get(i);
System.out.println("Element at [" + (i+1)+"] : " +studentMarks.get(i));
}
System.out.println("Sum of list element is : " + total);
System.out.println("The average of the array list : " + (total/(studentMarks.size())));
Collections.sort(studentMarks);
System.out.println("The minimum of the element in the list is : " + studentMarks.get(0));
System.out.println("The maximum of the element in the list is : " + studentMarks.get(studentMarks.size()-1));
scan.close();
While loop does not have as much flexibility as a for loop has and for loops are more readable than while loops. I would demonstrate my point with an example. A for loop can have form as:
for(int i = 0, j = 0; i <= 10; i++, j++){
// Perform your operations here.
}
A while loop cannot be used like the above for loop and today most modern languages allow a for each loop as well.
In my opinion, I could be biased please forgive for that, one should not use while loop as long as it is possible to write the same code with for loop.
In C-like languages, you can declare for loops such as this:
for(; true;)
{
if(someCondition)
break;
}
In languages where for is more strict, infinite loops would be a case requiring a while loop.