Hello You In Many Programming Languages

Examples of the standard "What's your name?"/"Hi Joe!" program.


AplLanguage is too hard due to lack of suitable graphics :(

AppleScript:

Each of these scripts displays an input dialog with default OK and Cancel buttons. If the user presses Cancel, the script is aborted and the user is not greeted. It's nice that the Cancel logic comes for free.

 set yourname to text returned of
    (display dialog "What is your name?" default answer "")
 display dialog "Hello, " & yourname & "!"
or
 say "What is your name?"
 set yourname to text returned of (display dialog "" default answer "")
 say "Hello" & yourname & "!"

x86 AssemblyLanguage: (assuming DOS IO facilities are available)

     ; write the prompt
     mov ah, 009 ; write string
     mov dx, offset prompt
     int 021

; gather the name one character at a time into buffer mov di, offset buffer read_next: mov ah, 006 ; read character from stdin into al (zf set if none available) mov dl, 0ff int 021 jz read_next mov ah, 002 ; write character to stdout mov dl, al int 021 cmp al, 00d ; did the user press enter? jne read_store mov al, '$' read_store: stosb jne read_next

; write the salutation mov ah, 009 mov dx, offset before int 021

; write the user's name mov ah, 009 mov dx, offset buffer int 021

; write the exclamation mov ah, 009 mov dx, offset after int 021

; terminate program int 020

prompt db "What is your name?", 00d, 00a, "$" before db "Hello, $" after db "!", 00d, 00a, "$" buffer db 064 dup 000
BasicLanguage:

Okay, since I'm such a (winged) dinosaur... Works correctly with a classic Basic

 10 INPUT "WHAT IS YOUR NAME? ", NAME$
 20 PRINT "HELLO, " + NAME$ + "!"
Doesn't the input statement generate it's own question mark, so that you don't need to code it explicitly?

I believe the comma suppresses the usual question mark input prompt. That's what my IBM PC book says. The following variation should automatically add a question mark prompt:

 10 INPUT "WHAT IS YOUR NAME"; NAME$
Yep, that worked with classic basic ("blassic" interpreter)

CeeLanguage:

 #include <stdlib.h>
 #include <stdio.h>

int main(void) { char name[64], *ok; size_t len;

/* puts() includes an implicit newline */ puts("What is your name?"); /* fgets() will only read size-1 characters to leave room for the zero terminator */ ok = fgets(name, sizeof(name), stdin); /* fgets() returns NULL on error */ if(!ok) { perror(NULL); return EXIT_FAILURE; } len = strlen(name); if(len > 0) { /* fgets() includes the terminating newline if it finds one */ /* we want to replace it with a zero terminator */ if('\n' == name[len - 1]) name[len - 1] = '\0'; } printf("Hello, %s!\n", name); return EXIT_SUCCESS; }
OK, I think I've improved the above code & clarified some of the tricky points in the comments. I've deleted the associated commentary.

A valiant attempt to avoid BufferOverflow, but I suspect it's still not quite right. Let's try again:

 #include <stdio.h>
 #define NUM_ELEM(x) (sizeof (x) / sizeof (*(x)))

int main(void) { char name[64]; puts("What is your name?"); fgets(name, NUM_ELEM(name)-1, stdin); name[ NUM_ELEM(name)-1 ] = '\0'; printf("Hello, %s!\n",name); return 0; }
Doesn't the standard dictate that sizeof(char)==1 (even if it isn't 8 bits)? The NUM_ELEM() macro might make sense if you were using wchar_t, but that would require changing the fgets() to fgetws() & printf() to wprintf() as well.

A wide character version:

 #include <stdlib.h>
 #include <stdio.h>
 #include <wchar.h>

#define NUM_ELEM(x) (sizeof(x)/sizeof(*(x))) #define NAME_SIZE 64

int main(void) { wchar_t name[NAME_SIZE], *ok; size_t len;

wprintf(L"What is your name? "); fflush(stdout); ok = fgetws(name, NUM_ELEM(name), stdin); if(!ok) { perror(NULL); return EXIT_FAILURE; } len = wcslen(name); if(len > 0) { if('\n' == name[len - 1]) name[len - 1] = L'\0'; } wprintf(L"Hello, %ls!\n", name); return EXIT_SUCCESS; }
CeePlusPlus:

 #include <iostream>
 #include <string>
 using namespace std;

int main(void) { string name; cout<<"What is your name?"<<endl; getline(cin, name); cout<<"Hello "<<name<<"!"<<endl; return 0; }
Does that look object oriented to you? Try:

 #include <iostream>
 #include <string>

using std::cin; using std::cout; using std::endl; using std::string;

class SalutationInput { private: string name; public: SalutationInput() { cout << "What is your name? "; std::getline(cin, name); } string getName() { return name; } }; class SalutationOutput { public: SalutationOutput(SalutationInput& in) { cout << "Hello " << in.getName() << "!" << endl; } }; int main(void) { SalutationInput whoever_the_hell_you_are; SalutationOutput say_hello_to(whoever_the_hell_you_are); return 0; }
C++ is so marvelously terse. :-)

Especially when used so well.

CeeSharp:

 using System;

class HelloYou { static void Main(string[] args) { Console.WriteLine("What is your name?"); string name=Console.ReadLine(); Console.WriteLine("Hello, {0}!",name); } }
CobolLanguage:

 000110 ENVIRONMENT DIVISION.  
 000120 INPUT-OUTPUT SECTION. 
 000130 FILE-CONTROL.
 000140    
  :
 000210       SELECT PRINT-FILE ASSIGN TO PRINTER. 
 000220                             
 000230       
 000240 DATA DIVISION.
 000250 FILE SECTION.  
  :                                  
 000580 FD PRINT-FILE.   
 000590 01 NAME-OUT      PIC X(80). 
  :  
 000630 WORKING-STORAGE SECTION. 
 000640            
  :
    .......ah, screw it, I don't have the energy....
CommonLisp:

 (format t "What's your name? ")
 (format t "Hi, ~A!" (read-line))
ForthLanguage:

 : hello-you
   cr ." What is your name? "
   pad dup 80 accept -trailing
   cr ." Hello, " type ." !" ;
FortranLanguage:

This is probably Fortrash 77. I'm just winging it here without a compiler, but this looks reasonable. Placing the exclamation point immediately after the final non-blank character in the user's name is left as an exercise for the student.<teehee> Compiles and runs correctly other than that.

       PROGRAM HELYOU
 C     
       CHARACTER*20 NAME
 C
 C     PROMPT USER FOR NAME
       WRITE (6,*) 'WHAT IS YOUR NAME? '
 C
 C     GET NAME FROM USER
       READ (5,*) NAME
 C
 C     GREET USER
       WRITE (6,100) NAME
   100 FORMAT (1X, 'HELLO, ', A20, '!')
 C
       STOP
       END
GuileScheme

 #!/usr/bin/guile  --debug -e main -s
 !#

(use-modules (ice-9 format))

(define (main args) (format #t "What is you name? ") (format #t "Hello, ~a!~%" (read-line)))
If you think the SheBang line needs editing, see: http://www.gnu.org/software/guile/docs/docs-1.6/guile-ref/The-Meta-Switch.html#The%20Meta%20Switch.

Again: The SheBang line is written as it is for a reason.

HaskellLanguage:

 main = do
         putStrLn "What is your name?"
         name <- getLine
         putStrLn $ "Hello, " ++ name ++ "!"
Or, if you want a one-liner and don't care about the exclamation:
 main = putStrLn "What is your name?" >> getLine >>= putStrLn . ("Hello, " ++)

JavaLanguage:

 import java.io.*;

public class HelloYou { public static void main( String [] args) throws IOException { // I hate Java InputStreamReader isr = new InputStreamReader(System.in); // I hate Java BufferedReader inStream = new BufferedReader(isr); // I hate Java

System.out.print("What is your name? "); String name = inStream.readLine(); System.out.println("Hello, " + name + "!"); } }
JavaSwing:

 import javax.swing.*;

public class HelloYou { public static void main(String[] args) { String name = JOptionPane.showInputDialog(null, "What's your name?"); if (name != null) JOptionPane.showMessageDialog(null, "Hello, " + name + "!"); } }
JavaScript:

 var name = prompt('What is your name?');
 alert('Hello, ' + name + '!');
JayLanguage
    wru =. 3 : 0
  'Who are you?' 1!:2 <2
  'Hi ',(1!:1 <1),'!'
 )
LogoLanguage
 to hello.you
 type "|What is your name? |
 make "name readlist
 type sentence "Hello :name
 print "!
 end
ObjectiveCaml:

 print_endline "What is your name?";
 Printf.printf "Hello, %s!\n" (read_line ());
PascalLanguage:

I'm winging it again. Good luck with this. Compiles and runs correctly.

 PROGRAM HELLOYOU;

VAR NAME: STRING;

BEGIN WRITE ('WHAT IS YOUR NAME? '); READLN (NAME); WRITELN ('HELLO, ', NAME, '!'); END.
PerlLanguage:

 #/usr/bin/perl
 print "What is your name? ";
 $name = <>;
 chomp($name);
 print "Hello $name!\n";
PythonLanguage:

 print 'Hello, %s!' % raw_input('What is your name? ').strip()
RubyLanguage:

 print 'What is your name? '
 puts "Hello, #{gets.strip}!"
SmlLanguage:

Lines starting with a dash contain the code. The other lines have been printed by the compiler/program. I also wrote my first name and pressed enter.

  Standard ML of New Jersey v110.57 [built: Fri Feb 10 21:37:49 2006]
  - val inputLineButLn = (fn NONE => NONE | SOME s => SOME (substring (s, 0, size s - 1))) o TextIO.inputLine ;
  [autoloading]
  [library $SMLNJ-BASIS/basis.cm is stable]
  [autoloading done]
  val inputLineButLn = fn : TextIO.instream -> string option
  - val () = (print "What is your name? " ; print ("Hello, "^valOf (inputLineButLn TextIO.stdIn)^"!\n")) ;
  What is your name? Vesa
  Hello, Vesa!
Explanation: The standard TextIO.inputLine function also returns the newline character (even when the input doesn't contain one). The above inputLineButLn doesn't.

Troff/groff:

This has a number of output flaws, and requires hitting enter twice rather than just once on input. I hate troff.

With groff, should be invoked via

   /usr/bin/groff -Tascii FILENAME | col -b -x
(what could be simpler? :-S )

 .pl 1
 .de nm
 Hello,
 'rd What_is_your_name?
 !
 ..
 .nm
UnixShell (bash):

 #!/bin/bash
 IFS=\#
 read -p "What is your name? " name
 echo "Hello, $name!"
VbClassic: (also doubles as VbScript)

    MsgBox "Hello, " & InputBox("What is your name?") & "!"


I think this is a great idea as it includes a simple interaction with the user.


JanuaryZeroSix

CategoryInManyProgrammingLanguages


EditText of this page (last edited June 9, 2011) or FindPage with title or text search