user3025998
user3025998

Reputation: 19

suggestions on constructing nested statements properly

I am having trouble constructing my own nested selection statements (ifs) and repetition statements (for loops, whiles and do-whiles). I can understand what most simple repetition and selection statements are doing and although it takes me a bit longer to process what the nested statements are doing I can still get the general gist of the code (keeping count of the control variables and such). However, the real problem comes down to the construction of these statements, I just can't for the life of me construct my own statements that properly aligns with the pseudo-code.

I'm quite new to programming in general so I don't know if this is an experience thing or I just genuinely lack a very logical mind. It is VERY demoralising when it takes me a about an hour to complete 1 question in a book when I feel like it should just take a fraction of the time.

Can you people give me some pointers on how I can develop proper nested selection and repetition statements?

Upvotes: 0

Views: 127

Answers (1)

nestedloop
nestedloop

Reputation: 2646

First of all, you need to understand this:

An if statement defines behavior for when **a decision is made**.

A loop (for, while, do-while) signifies **repetitive (iterative) work being done** (such as counting things).

Once you understand these, the next step, when confronted with a problem, is to try to break that problem up in small, manageable components:

    i.e. decisions, that provide you with the possible code paths down the way, 
and various work you need to do, much of which will end up being repetitive,  
hence the need for one or more loops.

For instance, say we have this simple problem:

Given a positive number N, if N is even, count (display numbers) from 0(zero) to N in steps of 2, if N is odd, count from 0 to N in steps of 1.

First, let's break up this problem.

Step 1: Get the value of N. For this we don't need any decision, simply get it using the preferred method (from file, read console, etc.)

Step 2: Make a decision: is N odd or even?

Step 3: According to the decision made in Step 2, do work (count) - we will iterate from 0 to N, in steps of 1 or 2, depending on N's parity, and display the number at each step.

Now, we code:

//read N    
int N;
cin<<N;

//make decision, get the 'step' value
int step=0;
if (N % 2 == 0) step = 2;
else step = 1;

//do the work
for (int i=0; i<=N; i=i+step)
{
   cout >> i >> endl;
}

These principles, in my opinion, apply to all programming problems, although of course, usually it is not so simple to discern between concepts.

Actually, the complicated phase is usually the problem break-up. That is where you actually think.

Coding is just translating your thinking so the computer can understand you.

Upvotes: 1

Related Questions