Wednesday, 5 February 2014

A Code to Display Alphabets using For-Loop

Problem:

Write a program to display alphabets from A to Z using for-loop.

Solution:

Here is the code that displays alphabets from A to Z using for-loop:

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
for(ch='A';ch<='Z';ch++)
{
cout<<ch;
}
getch();
}

Explanation:


  1. Line 1 & 2: include header files required for the program.
  2. Line 3: initialize the main() function with void return-type.
  3. Line 4: start of the body of main() function.
  4. Line 5: clrscr() clears all the previous outputs from screen.
  5. Line 6: declare a variable of character datatype.
  6. Line 7: initialize a for-loop. In it's initialization part, we've initialized the variable with value='A'. In the conditional part, we've set the loop to work until ch remains less-than or equal-to 'Z'. And in the final part we've set an increment of 1 in the value of ch. (If a variable contains the value:A, and we increment 1 in its value then its value will become 'B' because B comes right after A. Similarly next increment will cause the value of that variable to become 'C' and so on)
  7. Line 8: the body of for-loop starts.
  8. Line 9: the value of variable ch is sent to output.
  9. Line 10: the body of for-loop terminates.
  10. Line 11: getch() will stop the output on the screen until the user will press a key from keyboard.
  11. Line 12: the body of main() function ends.

Output:

The output of above written code is given below:
Output of the code, displaying Alphabets from A to Z
Output of the code, displaying Alphabets from A to Z

No comments:

Post a Comment