• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Using While loop in C [Tutorial]

Status
Not open for further replies.
Level 6
Joined
Oct 10, 2013
Messages
173
Hey there,
Lets cover up While loop a little in this tutorial with one example.

Things you need before reading this tutorial.
  • Must be familiar with scanf, and print f.
  • Must have good knowledge about data types.

Things you will be able to do after the tutorial:
  • You will be able to make some fun programs using While loop, and show off your friends.
  • A bit concept clearance to some newcomers, I will be sharing my research here.
  • Make some interest calculating program, using interesting logic's.
  • Avoid some key errors, as I will guide your through my research.
Before creating this tutorial, I want to dedicate this to my GURU(mentor) Cokemonkey11. I miss you Sir.

Lets start!

Meaning Of While Loop.

So first what is the meaning "of while"? Think then click spoiler.
a period of time.
"we chatted for a while"
Now tell me what is the meaning of "Loop in C"?Think then click spoiler.
a loop is a sequence of instruction s that is continually repeated
Now merge them together, and now think the meaning of " While loop".
A set of instructions repeating themselves, until certain condition is reached :D
Now that should have cleared basic stand of meaning of while loop, lets go further.


Structure of While loop.
The structure of while loop is very simple.It looks like this.Do look the error section because of one common blunder!
while(condition)
{

Set of instructions(your desired functions)
}


Example of code using while loop.
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
    int year,period;
    float net,amount,rate;
    printf("This is a simple program, which will tell you your salary in future considering all the raise.\n");
    printf("Please enter your current salary\n");
    scanf("%f", &amount);
    printf("Now please enter the rate, at which you think your salary will increase\n");
    scanf("%f",&rate);
    printf("Enter the period, in which you want to calculate your salary hike\n");
    scanf("%d",&period);
    printf("Ok, so your salary is %f. Your desired rate is %f, and your time period is %d\n\n\n",amount,rate,period);
    year=0;
    while(year<=period)
    {

        year=year+1;
        net=amount+amount*rate/100;
        printf("Your salary at year %d is %f\n",year,net);
        amount=net;


    }

}
Short simple code, the output of this code is given below in i
mage.

OSUHbuq.png


Working.



    • The code above while loop has only one objective, that is to fetch data from user.
      Code:
      #include<conio.h>
      void main()
      {
          int year,period;
          float net,amount,rate;
          printf("This is a simple program, which will tell you your salary in future considering all the raise.\n");
          printf("Please enter your current salary\n");
          scanf("%f", &amount);
          printf("Now please enter the rate, at which you think your salary will increase\n");
          scanf("%f",&rate);
          printf("Enter the period, in which you want to calculate your salary hike\n");
          scanf("%d",&period);
          printf("Ok, so your salary is %f. Your desired rate is %f, and your time period is %d\n\n\n",amount,rate,period);
    • You would had noticed that the code
      Code:
        year=0;
      sets the current value of variable to zero, this value has great importance see below for more details.
    • Now talking of while loop. Notice that the code structure mentioned matches in this code.
      Code:
      while(year<=period)
      
          {
      
              year=year+1;
              net=amount+amount*rate/100;
              printf("Your salary at year %d is %f\n",year,net);
              amount=net;
      
      
          }
      This is the desired(you can set any condition you like) condition component in while loop
      Code:
      (year<=period)
      . Just like how coffee is made using components , while loop is also made by using its core component.
    • These are the statements
      Code:
      year=year+1;
      
              net=amount+amount*rate/100;
              printf("Your salary at year %d is %f\n",year,net);
              amount=net;
      This are the set of instructions that will be executed by the compiler till the specific condition is being satisfied.
    • Now you know that until the specific condition is reached this code will continue re executing its instruction inside the loop.Thus we put
      Code:
      year=year+1;
      as we want the value of year to increase until it reaches the user desired year.
    • Since our main algorithm to calculate interest is
      Code:
      net=amount+amount*rate/100;
      We type
      Code:
      amount=net;
      so that everytime it re executes the command , it will take the value of of amount = the last time value obtained during execution of the whole code in that particular time, since it will recur code, until the year will be equal to the period user typed.
Common Errors.



    • If you skipped a "&" in scanf you will get this error.My advice to recheck the
      gIbkGsb.png
      code if this error occurs
    • If you would had typed a ;(semi colon) after while(condition) like this while(condition); then the compiler think it is the end of code and won't go any further, or won't executes the code inside the while loop and will just skip through it.

That's all folks.
Feedbacks are welcomed, trolls ignored. New learners are always welcomed. :)


Edit

The scan f error is more elobrated here, why actually the program crashes,
Here is an example

scanf("%d", &i);
will write an int data by the user to the memory location allocated for i.

If & is not placed before i, then scanf will try to write the input data to the memory location i instead of &i. Since i contains indeterminate value, there are some possibilities that it may contain the value equivalent to the value of a memory address or it may contain the value which is out of range of memory address.



 
Last edited:

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
I thought the internet was full of these already?
For, While and Do While Loops in C - Cprogramming.com
While loop - Wikipedia, the free encyclopedia
Just two examples.

If you skipped a "&" in scanf you will get this error.
Why will you get that error? Maybe the error is because the application goes into an infinite loop and stops responding? Or is it because of invalid scanf call?
If you would had typed a ;(semi colon) after while(condition) like this while(condition); then the compiler think it is the end of code and won't go any further, or won't executes the code inside the while loop and will just skip through it.
It should execute the loop while the condition holds. That might be forever though as the body of the loop is now a separate code block so the test might never become false. The body of the loop should still execute once after the loop is finished.
 
Level 29
Joined
Jul 29, 2007
Messages
5,174
I find this "tutorial" to be very tedious and long for one of the simplest concepts of programming, which you wrote in exactly one sentence: "A set of instructions repeating themselves, until certain condition is reached".
The obnoxious text colors don't help.

Why will you get that error? Maybe the error is because the application goes into an infinite loop and stops responding? Or is it because of invalid scanf call?

Because you'd be reading into random garbage memory?
 
Level 6
Joined
Oct 10, 2013
Messages
173
Well , I was submitting my research(all the errors I have faced, and what should you care of), what I had researched key factors during learning.

I thought the internet was full of these already?
Why will you get that error? Maybe the error is because the application goes into an infinite loop and stops responding? Or is it because of invalid scanf call?

It should execute the loop while the condition holds. That might be forever though as the body of the loop is now a separate code block so the test might never become false. The body of the loop should still execute once after the loop is finished.
Here is an example

scanf("%d", &i);
will write an int data by the user to the memory location allocated for i.

If & is not placed before i, then scanf will try to write the input data to the memory location i instead of &i. Since i contains indeterminate value, there are some possibilities that it may contain the value equivalent to the value of a memory address or it may contain the value which is out of range of memory address.

In either case, the program may behave erratically and will lead to undefined behavior. In that case anything could happen.
  • So Infinite loop maybe, but it is definitely an invalid scan f call.
I find this "tutorial" to be very tedious and long for one of the simplest concepts of programming, which you wrote in exactly one sentence: "A set of instructions repeating themselves, until certain condition is reached".
The obnoxious text colors don't help.

I tried to cover every points even though it is most basic of loops in C, with high amount of precision. I don't wanna be that guy who submits wrong tutorial, I just help newbies like me. It may be long, but it should be comfortable . Give me suggestion to make it less tedious, although I thought it was attractive a bit.

@dsg

I have edited my post accordingly, keep giving more important reviews like that :)
 

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
Because you'd be reading into random garbage memory?
If & is not placed before i, then scanf will try to write the input data to the memory location i instead of &i. Since i contains indeterminate value, there are some possibilities that it may contain the value equivalent to the value of a memory address or it may contain the value which is out of range of memory address.
I was trying to point out that that information was missing from your common errors section. Telling someone the solution to an error without telling them why it was an error is not that helpful as it might not stop them from making the same mistake in the future.

Just in case you do not know, the following are all valid although some may not be easy to read.
Code:
int i;

i = 0;
while(i < 10) {
    i+= 1;
}

// note that this does not have a block so will only repeat the first statement that directly proceeds it
i = 0;
while(i < 10)
    i+= 1;

i = 0;
while(i < 10) {i+= 1;}

i = 0;
while(i++ < 10);
 
Status
Not open for further replies.
Top