Learning C/C++ Step-By-Step - Page 5

05. Step-by-Step C/C++ --- C Programming - Looping Statements

  1. Branching Statement - goto
  2. Looping Statements
    for
    while
    do..while

 

1. Branching Statement

goto
It transfers the control pointer from one place to another in the current program.

  Syntax:

goto <label>;

Note: Label name must be defined with colon(:) and it should not exceed more than 32 characters in length.

  Eg.

abc:
     printf(“Hello”);
     goto abc;

/* 01. A demonstration program to illustrate goto statement */

/* 19_goto.c */
#include <stdio.h>
int main()
{
     abc: /* Label name */

          printf("\nHello");
     goto abc; /* branching statement */
     return 0;
}

/* 07. Continuous execution will be stopped with a carry varaible and a conditional statement */
/* Find the difference between the last program and this, note all the differences in this program*/

/* 20_goto.c */
#include <stdio.h>
int main()
{
     int i = 1;
     abc:
          printf("\nHello");
          i ++;
          if ( i<= 10 ) /* Take care of this statement */
     goto abc;
     return 0;
}

 

2. Looping Statements

for
An iterative statement to execute a statement block for a number of times.

  Syntax:

for(<initialization> ; <condition> ; <step value>)
{
     <st. block>
}

  Eg.

for(I=1;I<=10; I++)
     printf(“\n%d”,i);

  Eg.

for(I=1, j = 0; I<10; I+=2, j+=2)
     printf(“%d %d\n”, i, j);

/* 08. To print a message 5 times */

/* 21_for.c */
#include <stdio.h>
int main()
{
     int i;
     for(i = 1; i <= 5; i++ )
          printf("\nHello");
     return 0;
}

/* 09. To print a message with it's count upto 5 times */

/* 22_hello.c */
#include <stdio.h>
int main()
{
     int i;
     for(i = 1; i <= 5; i++ )
          printf("\nHello - %d", i);
     return 0;
}

/* 10. To print 1 to 10 natural numbers */

/* 23_nat.c */
#include <stdio.h>
int main()
{
     int i;
     for(i = 1; i <= 10; i++ )
          printf("\n%d", i); /* Eleminating message */
     return 0;
}

/* 11. To print second multiplication table */
/* Note : Compare it, with the last program */

/* 24_table.c */
#include <stdio.h>
int main()
{
     int i;
     for(i = 1; i <= 20; i++ )
          printf("\n%d * 2 = %d", i, i * 2);
     return 0;
}

/* 12. To print a multiplication table for the given number */

/* 25_tablen.c */
#include <stdio.h>
#include <conio.h>
int main()
{
     int i, t; /* a new variable 't' */
     clrscr();
     printf("Which table to print :"); scanf("%d", &t);
     for(i = 1; i <= 20; i++ )
          printf("\n%d * %d = %d", i, t, i * t);
     return 0;
}

/* 13. To print a multiplication table for the given number */
/* Note : Compare it, with the last program */

/* 26_tablen.c */
#include <stdio.h>
int main()
{
     int i, t;
     clrscr();
     for(t = 1; t <= 20; t++) /* One more for loop */
          for(i = 1; i <= 20; i++ )
               printf("\n%d * %d = %d", i, t, i * t);
     return 0;
}

/* 14. To print numbers in triangle form */
/* Note : Compare it, with the last program */

/* 27_tri.c */
#include <stdio.h>
int main()
{
     int i, j;
     clrscr();
     for( i = 1 ; i<= 5; i++ )
     {
          for( j = 1; j <= 5; j++ )
               printf("%4d", j);
          printf("\n");
     }
     return 0;
}

Few more examples of for loops:

  /* Infinite Loop */
for ( ; ; )
{
     printf("\nHello");
}
/* Print 1-5 numbers */
for ( i=1; i<=5; )
{
     printf("\n%d", i++);
}
  /* Explicit Loop break*/
for ( i=1; ; )
{
     printf("\n%d", i++);
     if ( i> 5 ) break;
}
int i = 1;
for ( ;i<=5 ; )
{
     printf("\n%d", i++);
}

while
An iterative statement to execute a statement block until the given condition is satisfied.

do.. while
This iterative statement executes statement block at the begin and then it checks the condition validity. If the condition is true it executes the statement block again and vice versa.

  Syntax:

while( < condition > )
{
      <st. block>;
}

Syntax:

do
{
      <st. block>
} while(<condition>);

Eg.
The following example displays natural numbers from 1 to 10.
 

int main()
{
      int i=1;
      while( i<=10)
      {
            printf(“\n%d”,i);
            i++;
      }
      return 0;
}

int main()
{
      int i=1;
      do
      {
            printf(“\n%d”,i);
            i++;
      }while(i<=10);
      return 0;
}

  It checks the condition first and executes the block next , So you should have an initial value for the condition It executes the block first and checks the condition next , You can determine the initial value in the st.block.
More Examples
 

/* 15. To print 1 to 5 numbers */
/* Note : It's a reference program */

/* 28_while.c */
#include <stdio.h>
int main()
{
     int i;
     i = 1; /* Initial value is 1 */
     while( i<= 10 )
      /* True i is less than or equal to 10 at first */
     {
          printf("\n%d", i);
          i ++;
     }
     return 0;
}

/* 16. To print 1 to 5 numbers */

/* 29_dowhile.c */
#include <stdio.h>
int main()
{
     int i;
     i = 1; /* Initial value is 1 */
     do
     {
          printf("\n%d", i);
          i ++;
     }while( i<=10 );
     /* True, i is less than or equal to 10 at Second */
     return 0;
}

 

/* 17. Demonstration of while */
/* Note : If the initial value is 100 what was the output?, Check it. */

/* 30_demow.c */
#include <stdio.h>
int main()
{
     int i;
     i = 1;
     while( i<= 10 )
     {
          printf("\n%d", i);
          i++;
     }
     return 0;
}

/* 18. Demonstration of do */
/* Note : If the initial value is 100 what was the output?, Check it. */

/* 31_demod.c */
#include <stdio.h>
int main()
{
     int i;
     i = 1;
     do
     {
          printf("\n%d", i);
          i++;
     }while( i<= 10 );
     return 0;
}

Share this page:

19 Comment(s)

Add comment

Comments

From: at: 2009-01-09 15:11:23

The tutorial looks so great. But I have some doubts. Why do you use "clrscr()" function and conio.h library, if you are using the C/C++ standard? (I found that in the pages number 4 and 5, but that is as far as i got).

From: at: 2009-01-20 16:25:53

I tried to lead learners from learning C to C++, so the pages 4 and 5 reflects most of the usage of C language, so it introduces users to learn about other header files.

From: Shantanu Goel at: 2009-01-08 04:44:05

Great tutorial Ganesh. And here is a link for people who finish your tutorial and want to learn a bit about how to make their code secure and optimized: Safer Code - Secure Coding in C/C++ This has a lot of stuff regularly published to cater to various security and performance related issues with C/C++ and anyone can follow it easily at a gradual pace.

From: Anonymous at: 2010-02-01 06:01:52

Very nice!

From: pickatutorial at: 2010-10-09 12:52:44

Great Work. Keep it up.

From: TodaysTech at: 2011-07-12 21:31:29

If anyone is interested, I have an ongoing blog that is covering the transition from the Business world to the Programming world.  Since it's from my own perspective, I think it can be easy to read and relate to for most first timers.

 http://livingtodaystech.blogspot.com/2011/07/learning-c.html

From: Crosility at: 2012-12-06 23:44:36

In the chart, it says 'vhar', not 'char'.

From: Jason at: 2013-04-16 14:58:31

Why using conio.h ?   It is not part of C standard, C++ standard, nor is it part of any Linux or Unix libraries.  

The inclusions of Microsoft specific libraries in chapters 4 & 5 have me doubting the validity the rest of the tutorial (learning c/cpp on Linux).

The tutorial is well written, however,  but I think it would be more appropriate on a .Net or Msdn blog. 

Thanks Ganesh!

From: Anonymous at: 2009-09-01 11:56:38

Shouldn't

\* 0001_hello.c *\ and  \* 0001_hello.cpp *\

 be

/* 0001_hello.c */ and /* 0001_hello.cpp */

?

 

From: Scott_R at: 2012-01-03 22:24:55

The numbering for the examples is off by one.

For example:

"10. Write a program to find the total and average marks of a student"

/* 11_stud.c */

From: Erica at: 2012-12-31 19:56:21

In 11_stud.c

avtg = total / 3;

should be

avg = total / 3;

Also the clrscr() function won't compile in g++. If others need you can add // to the start of the line and the line will become a comment.

From: Bob at: 2011-09-09 12:50:09

Ex 13 :

  if ( age >= 13 and age <= 19 ) printf("Teen Age");
  if ( age >= 20 and age <= 35 ) printf("Young Age");
  if ( age >= 36 and age < 50 ) printf("Middle Age");

should read as :

      if ( age >= 13 && age <= 19 ) printf("Teen Age");
      if ( age >= 20 && age <= 35 ) printf("Young Age");
      if ( age >= 36 && age < 50 ) printf("Middle Age");

From: Anonymous at: 2009-06-25 12:57:51

Example 14 would be less ....rectangular and much more triangular if, instead of

for (j=1;j<=5;j++)

one had

for (j=i; j<=5;j++)

From: Snehal at: 2009-06-15 07:00:15

In the difference between union and structure ,the names are misplaced ...means in union , structure points are placed and viceversa... Make it correct

From: bzero in c programming at: 2014-07-30 10:54:51

Hi,

There is a bug in the number 4 example. You will get compilation error while running this program you will get a compilation error like below:

 binaryover.cpp:31:11: error: expected ‘;’ before ‘t1’

binaryover.cpp:32:6: error: ‘t3’ was not declared in this scope

binaryover.cpp:32:11: error: ‘t1’ was not declared in this scope

binaryover.cpp:32:16: error: ‘t2’ was not declared in this scope

Because you are using "using namespace std;" but in the standard library there is a function named time (). So, to solve the problem, you can change the name of the function time ()  to any other name like time1 (), then you will be able to run your code without any error. 
 

From: Abhijeet at: 2009-01-11 01:25:52

Though i haven't done it myself, mingw32 can create win32 executables from linux. As its description says "Minimalist GNU win32 (cross) compiler, A Linux hosted, win32 target, cross compiler for C/C++, Freedom through obsolescence. Those who still really need to can now build windows executables from the comfort of Debian." You could check it out.

From: Paul at: 2009-01-07 22:40:39

Thanks, this is a nice tutorial, I'm actually a php programer and I saw a lot similar with php's language, but I have a question:

Can I compile a c++ program under linux to make a .exe to run on windows and viceversa?

And how to do that if it is possible?

From: dbrion at: 2009-06-30 11:58:40

"Can I compile a c++ program under linux to make a .exe to run on windows "

Yes :

I confirm the last post and cross compilers can natively be found with recent Fedora (and any linux distribution, messeems!) The way all the stuff necessary could be downloaded and made working can be found with adaptations of :

cran.r-project.org/doc/contrib/cross-build.pdf 

(one just has to stop at "make xtools": they are downloaded and put into a proper place).

Else, if you like linux and have "only"  Windows, you can use cygwin (avoids dualbooting or switching to another computer)  with the sources (it is very rare that sources need to be different between both systems, they use the same compiler -gcc/g+++- and almost the same include file names.... ) ...

 

"and viceversa"

No (not because linux executables do not have a .exe suffix!):

 but you can edit/compile/test your program(s) under cygwin (google search can find it) until it works and port it (i.E the source, the compilation  and test scripts) to Linux (there is almost no effort, apart the efforts linked with different disk nomenclatures, of course).

 Else, unless emulating linux with vmplayer/qemu/vbox -all these emulators are Windows ported-? but it is more complicated than C/C++....

From: Iftekhar Ahmed at: 2010-05-14 19:31:55

Dude........

Its relly helpful, I have 48 Hrs for my Exams..........................

Thanks for posting ............

Regards,

Iftekhar Ahmed