Search code examples
c++functioncallcout

c++ weird result from showing lettters from cout


I'm new to programming and I started reading some c/c++ books to understand better. So i'm not very newbie and i will go straight to the subject. I want to make a program that show all the letters from a to z, so i made 2 programs. One in C and other in C++. The one in C works as expected, here is the code:

#include <stdio.h>

void alfa(){
char c;
    for(c='A'; c<='Z'; ++c)
       printf("%c ",c);
}

int main()
{
    alfa();
    getchar();
    return 0;
}

but the other in C++ is showing an "[" or numbers..

#include <iostream>
using namespace std;

void alphabet(){
    char abc;
    for(abc='A'; abc<='Z'; abc++);
    cout<<abc;
}

int main(){
    cout<<"This will show letters from a to z"<<endl;
    alphabet();
    cin.ignore();
    return 0;
}

PS: If I made the c++ program in one function it works... but I still learning and I want it to be called. Thanks


Solution

  • You have a column ; after the for loop. As stated by tadman, the for loop runs nothing because of this.

    for(abc='A'; abc<='Z'; abc++)
        cout<<abc;
    

    You can also put some brackets to make sure you are not doing any mistake when writing your first pieces of code.

    for(abc='A'; abc<='Z'; abc++) {
        cout<<abc;
    }