Understanding a loop output - c++

Can somebody explain to me why the output will be as follows?
Why the loop runs a second time after (int i) gets as value 9, which is not less than 5?
It seems that even if (int i) is greater than 5 it still adds another 3 but the body won't run a second time. Why?
#include <iostream>
using namespace std;
int i=0;
int main()
{
for(;i<5;i+=3){
i=i*i;
}
cout << i << endl;
//Output: 12(i)

it works that way, more or less:
i = 0
i < 5 ? yes, keep on
i*i = 0
i+=3 => i ==3 now
i < 5 ? yes, keep on
i*i = 9
i+=3 => i is 12 now
i < 5 ? no, exit loop
You write a for(initialization; condition; excuteAtTheEndOfCycle):
initialization is executed only once at the beginning, condition is evaluated before each cycle, excuteAtTheEndOfCycle (i+=3, in your case), it's executed at the end of each cycle, before a further evaluation of condition

it is not running because you are giving condition of the loop to be less than five,
What are you want ,that output will be?

Related

Why does i print the same value as the number I want less than?

Consider
#include <iostream>
int main()
{
int i = 0;
while (i < 10)
i++;
std::cout << i << endl;
}
I just wanted to know, why does this print out 10? if it is i < 10, shouldn't it be 9 that is printed? I appreciate any help
Because when i is 9, (i < 10) is true, so the while body runs, which increments i by 1 thereby setting it to 10. Sure, on that last iteration of the while body, i++ is an expression equal to 9, but with the side-effect of increasing i.
Regardless of what happens inside the loop,
do this as long as i is less than 10
is the same as
do this until i is greater than or equal to 10
So the value of i after the loop must be (at least) 10, since that's when it stops.
Because the i in while(i < 10) stays in the loop til i is equals to 10, i compares the values with 10 so when it reaches 10 it will break out of the loop and it would print it out

C++ for loop to find "sum of digits of a given number"

I'm a very beginner. I'm trying to solve some problems and being stuck right at the first one. The while loop runs but then I try using for loop and it never runs
#include <iostream>
using namespace std;
int main(){
int n=910;
int digits_sum=0;
for(int i=n;i=0;i/=10)
digits_sum+=(i%10);
cout<<digits_sum;
return 0;}
I googled and found on codescrackers:
int num, rem, sum;
cout<<"Enter the Number: ";
cin>>num;
for(sum=0; num>0; num=num/10)
{
rem = num%10;
sum = sum+rem;
}
cout<<"\nSum of Digits = "<<sum;
The code runs and it gives me other questions:
why is the init value sum=0?
Why is condition num>0
It seems I still don't get the for loop statement fully so this is how it runs with my understanding:
init value i = n = 910
condition to be out of the loop: i = 0
decrement: i = 910/10 = 91
Could you please tell me where did I go wrong?
To quoute from your question:
condition to be out of loop: i=0
You have two misunderstandings here:
i = 0 is an assignment, you want a comparison i == 0
It looks you interpreted this as "exit if this is condition is fullfilled", but in fact the opposite happens: The loop will continue as long as this condition is true.
So the only thing you have to do is to change
for(int i=n;i=0;i/=10)
to
for(int i = n; i != 0; i /= 10) // loop as long as i does not equal 0

I need better understanding on for loops

can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!
1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5 int main(){
6 int n, a , b , ma=0,mb=1000000001;
7 cin >> n ;
8 cin >> a;
9 for( n--; n ; --n ){
10 cin >> b;
11 if(abs(a-b) < abs(ma-mb))
12 ma=a , mb=b;
13 else
14 if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15 ma=a , mb=b;
16 a = b;
17 }
18 cout << ma << " " << mb;
19 return 0;
20 }
A for loop is simply another way to write a while loop. So this:
for( n--; n ; --n ){
...
}
is the same as this:
n--;
while(n) {
...
--n;
}
Which, in this specific case, is easier to read. First it decrements n, then does the loop, decrementing n again at the end of each loop, until that decrement causes n to evaluate to false by becoming 0.
This code smells a lot. If you give to n the value 10,it gives
9 (first time into loop, exectues n--)
every other iteration it executes --n till when n!=0 (which is the condition n
A for loop works the following way:
It runs for a certain number of times. We signify this with a condition. It has a start and an increment:
for (start ; condition ; increment )
{
// loop body
}
For loops and all loops are very useful when you want to perform repetitive tasks.
Lets say that you want to make a game and this game will have 3 rounds. Each one of those rounds can be implemented as an iteration of a for loop. It will look like this:
for(int round = 0; round < 3; ++round) {
// game round logic
}
In the above loop we start at 0. Once we reach 3, we would have already executed the for-loop 3 times. After each iteration of the for loop ++round gets executed, this increments the variable round by 1. We can increment it by a different value by doing: round+=2 or round*=2 etc.

Using ++ operator leads to unexpected results

I do not understand why the two codes below lead to the same result. Shouldn't the latter print from 6 to 10 since n is incremented first?
Edit: I used both Visual Studio 2019 and repl.it.
#include <iostream>
using namespace std;
int main() {
int n=5;
for (n; n<10; n++)
cout << n << endl;
return 0;
}
>>> 5
6
7
8
9
#include <iostream>
using namespace std;
int main() {
int n=5;
for (n; n<10; ++n)
cout << n << endl;
return 0;
}
>>> 5
6
7
8
9
From https://en.cppreference.com/w/cpp/language/for
attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement
The above syntax produces code equivalent to:
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
Your two for loops are therefore equivalent to
{
n;
while (n < 10) {
cout << n << endl;
n++;
}
}
and
{
n;
while (n < 10) {
cout << n << endl;
++n;
}
}
In a for loop:
The first statement is executed exactly once
The conditional is checked, and if true
The body is executed
Then the iteration expression is executed
Goto (2.)
If you want your loop to start at 6, you need to explicitly tell it to start at 6.
There's Nothing wrong here, its just how its supposed to work
Firstly, you should know a for loop works
for loop, without loss of generality can be written as:
for(exp1; exp2; exp3)
{
//body
}
here exp1 will be executed only when entering the loop first time, then exp2 will be evaluated, if true loop will continue, otherwise not.
exp3 is evaluated only after each iteration is complete.
also the only difference between i++ and ++i, is when you assign it to something.
say i is 5, then after statement
i++;
i will be 6
which is also true for this statement:
++i;
but say i=5,
but you try something like this:
a=i++;
after this statement, a will be 5, and i will be 6.
but after this statement, with same initial condition(i = 5):
a=++i;
both a and i will be 6.
The only difference is this:
for (n; n<10; n++)
vs. this:
for (n; n<10; ++n)
The first and third expressions in a for statement are evaluated only for their side effects, with any result discarded. (The second is evaluated and its result used to determine whether to continue the loop.) The only difference between n++ and ++n is their results; their side effects are identical. So in this context n++ and ++n are effectively identical.
I'll also mention that the first expression n has no side effects, so it might well be omitted:
for (; n<10; n++)
Or, better yet, you could incorporate the declaration and initialization into the loop, replacing the existing declaration int n=5;:
for (int n = 5; n < 10; n++)

Prime number nested loop Logic

I am currently working on assignment which is stated below. My question is that why does my code only repeat prime number as 2 and not the remainder of the numbers. I would much appreciate if someone could help me to walk through the logic so i can try to solve the solution, rather than posting the answer outright. Kudos to all :)
Write a program that uses two nested for loops and the modulus
operator (%) to detect and print the prime numbers from 1 to 10,000.
(Prime numbers are natural numbers that are not evenly divisible by
any other number except for themselves and one). Display all the
primes found.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> n; // will store our values from 1-10000
for (int i= 0; i < 10000; i++) { // vector loading
n.push_back(i);
n[i]= n[i] + 1;
for (int j= 1; j < 10000 ; j++ ) { // Error is here?
if (n[j] % j == 0) { // supposed to go through all the numbers
// and flag the prime numbers
cout<<n[i] <<" is a prime";
i++;
break;
}
}
}
return 0;
}
The trivial method is rather easy to understand.
Outer loop (suppose the loop variable here is num) go through from 2 to 10000, and check every number whether it is a prime number.
Inner loop (suppose the loop variable here is fact) go through form 2 to num - 1
Check if num has a factor fact by num % fact == 0. If fact is a factor of num, then break the inner loop and continue to check the next number.
If after checking all the numbers from 2 to num - 1 and none of them is the factor of num, then we are sure that num is a prime number and continue to check the next number.
Note that 0 and 1 are special case so we exclude them from the loop.
This method doesn't need any array. The time complexity is O(n2) and space complexity is O(1).
BTW, there are other better solution to this problem, for example Sieve of Eratosthenes.
There are a couple of problems but for a starter consider the very first loop.
i = 0
n.push_back(i); // Now n[0] is now valid (having the value 0)
n[0] = n[0] + 1; // Now n[0] is still valid (having the value 1)
j = 1;
if (n[j] % j == 0) // Ups... access to n[1] which is invalid
// as you have only pushed one element, i.e. n[0]
Understand the purpose of your loops
The outer loop is the one that supplies the numbers, therefore you
don't need the vector
The inner loop is the one that does the checking
Where do you print?
The inner loop checks if a number is not prime. The only way it
knows this is if the number supplied by the outer loop is not divisible by any number supplied by the inner loop. Therefore the inner loop
does not print anything because it has to exhaust all checks before it knows that a number is prime
Your print statement should come last. This means it should be after the inner loop but still inside the outer loop and it should print the number if it is prime based on what was discovered by the inner loop. So you should have a way of knowing if the inner loop found a prime or not
Finally note that the inner loop has to start at 2 and end at i - 1 because every number is divisible by 1 and itself
Do not need to iterate through the entire range for inner loop, for inner loop there will possible values are starting from 2 to <= that number /2 .
Like if you want to check whether 99 is prime or not then you need to
set inner loop from 2 to 49 (99 / 2 is the max possible factor for
that number) so do not iterate through the rest all.
So if you iterate inner loop from 2 to 98 then it's meaning less to
iterate this loop after 49, think about it.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//vector<int> n; // will store our values from 1-10000
int flag =0;
for (int i= 2; i < 10000; i++) // vector loading
{
//n.push_back(i);
//n[i]= n[i] + 1;
flag =0;
for (int j= 2; j <= i / 2 ; j++ )
{
if (i % j == 0)
{
flag = 1;
break;
}
}
if(flag == 0)
{
cout << "%d number is Prime" << i;
}
}
return 0;
}