Transferring skills - Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

13. Transferring skills

This chapter demonstrates similarities and differences in coding various popular programming languages.

Understanding compilers

Compiling code

Coding C

Coding C++

Coding C#

Coding Java

Summary

Understanding compilers

Modern apps are coded in “high-level” languages that provide a high level of abstraction between machine code, which is understood by computers, and source code that is human-readable. In order to run programs the source code must first be rendered into machine code that the computer can execute. This process is accomplished either by an “interpreter” or by a “compiler” depending upon the language in which the program is written.

The Python programming language, used for demonstration throughout the previous chapters of this book, uses an interpreter to translate program source code. As a program proceeds, the interpreter dynamically translates its functions and statement code objects into “bytecode”. The bytecode can then be executed via Python’s bytecode interpreter (a.k.a “Virtual Machine” or “VM”).

image

Often languages that employ an interpreter are referred to as “interpreted languages” and those that use a compiler are referred to as ”compiled languages”.

Other programming languages that employ an interpreter to translate source code into bytecode for execution by the computer via their virtual machine include Java and Ruby.

image

Traditional programming languages, such as the C language, use a compiler to convert program source code into machine code. Compilation takes the entire source code and first generates intermediate “object code” representing the program’s functions and statements in binary machine code format. The compiler then combines the object code into a single binary machine code file (.exe) that can be executed directly by the computer.

image

Notice that the Virtual Machine (VM) must be present on the user’s computer to execute those programs written in interpreted languages.

Other programming languages that employ a compiler to convert source code into machine code for direct execution by the computer include C++ (“C plus plus”) and C# ( “C sharp”).

image

There are, therefore, fundamental differences in the way programs written in “interpreted languages”, such as Python, and “compiled languages” such as the C language, are executed by the computer. Each offers some advantages and disadvantages in terms of performance and portability, as listed in the table below:

Interpreter:

Compiler:

Takes individual code objects as input for translation

Takes the entire source code as input for conversion

Does not generate intermediate object code

Does generate intermediate object code

Executes conditional control statements slowly

Executes conditional control statements quickly

Requires little memory as object code is not generated

Requires more memory as object code is generated

Translates the source code every time the program runs

Converts the source code once during compilation

Reports any errors immediately when they occur in a statement

Reports any errors only after an attempt to compile the entire source code

Programs run slower while code objects get individually translated to machine code

Programs run faster while machine code runs directly on the computer

Distributed programs are human-readable source code so are easy to modify

Distributed programs are compiled machine code so are difficult to modify

Offers poorer protection of intellectual property rights

Programs run faster while machine code runs directly on the computer

image

Don’t be confused by Java programs. They are “compiled” into bytecode as a distributable (.class) file that nonetheless require the Java VM bytecode interpreter to run.

Compiling code

To more fully understand the compilation process it is useful to examine in detail the compilation of a simple C language program. In producing an executable file from an original C source code file the compilation process actually undergoes four separate stages, which each generate a new file:

Preprocessing – the preprocessor stage first substitutes all “preprocessor” directives, such as statements to import libraries, with the actual library code. For instance, in the C language the library code is substituted for #include import directives. The generated file containing the substitutions is in text format and typically has a .i file extension

Translating – the compiler stage translates the high-level instructions in the .i file into low-level Assembly language instructions. The generated file containing the translation is in text format and typically has a .s file extension

Assembling – the assembler stage converts the Assembly language text instructions in the .s file into machine code. The generated object file containing the conversion is in binary format and typically has a .o file extension

Linking – the linker stage combines one or more binary object .o files into a single executable file. The generated file is in binary format and typically has a .exe file extension

image

Strictly speaking, “compilation” describes the first three stages above, which operate on a single source code text file and ultimately generate a single binary object file. Where the program source code contains syntax errors, such as a missing statement terminator or a missing parenthesis, they will be reported by the compiler and compilation will fail.

The linker, on the other hand, can operate on multiple object files and ultimately generates a single executable file. This allows the creation of large programs from modular object files that may each contain re-usable functions. Where the linker finds a function of the same name defined in multiple object files it will report an error and the executable file will not be created.

Normally, the temporary files created during the intermediary stages of the compilation process are automatically deleted, but the GNU C Compiler (gcc) provides a -save-temps option in the compiler command that allows them to be saved for inspection.

imageFor a simple “Hello World!” program in the C language, type a command gcc hello.c -save-temps -o hello.exe then hit Return to compile and save the temporary files

image

imageOpen the hello.i file in a plain text editor, such as Windows’ Notepad, to see the source code appear at the very end of the file – preceded by substituted library code

imageNow, open the hello.s file in a plain text editor to see the translation into low-level Assembly code and note how unfriendly that appears in contrast to high-level code

image

image

In the command here, gcc invokes the compiler, the source code file is hello.c, and -o hello.exe specifies the executable file to be output.

image

A complete example demonstrating how to code and compile programs in the C programming language is provided overleaf.

Coding C

The coding data structures and control structures described and demonstrated throughout this book in the Python programming language also exist in other programming languages. Your skills gained with Python coding can be transferred to other languages, such as the C programming language, by recognizing similarities. The C programming language originated way back in the 1970s and is designed to be easily compiled to low-level machine code. Its efficiency makes it suitable for a wide range of applications in everything from embedded systems to operating systems.

The simple Guessing Game program, described in Python code here and here, can be recreated in a similar C equivalent.

image

guess.c

imageStart a new C program by importing libraries to make input-output, random number, and time functions available

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

imageNext, define a “main” function body that will enclose the entire game code and return a zero value on completion

int main( )

{

/* Statements to be added here */

return 0 ;

}

imageNow, add statements to initialize variables with a random number in the range 1-20, a Boolean true, and an integer

srand( time( NULL ) ) ;

int num = ( rand() % 20 ) + 1 ;

int flag = 1 ;

int guess = 0 ;

imageAdd a statement to request user input

printf( “Guess my number 1-20 : “ ) ;

imageThen, add a loop statement that reads input into the integer variable and will enclose a conditional test

while ( flag == 1 )

{

scanf( “%d” , &guess ) ; fflush( stdin ) ;

/* Conditional test to be added here */

}

image

This C program will accept floating-point guesses as their value gets truncated to an integer in the assignment to the guess variable.

imageFinally, add a conditional test inside the loop then save, compile, and run the program

if( guess == 0 )

{

printf( “Invalid! Enter only digits 1-20\n” ) ;

break ;

}

else if ( guess < num ) { printf( “Too low, try again : “ ) ; }

else if ( guess > num ) { printf( “Too high, try again : “ ) ; }

else

{

printf( “Correct... My number is %d \n” , num ) ;

flag = 0 ;

}

image

image

The GNU C Compiler (gcc) is widely used and is freely available as part of the Minimalist GNU for Windows (MinGW) package from sourceforge.net/projects/mingw For installation instructions and other help refer to the documentation at mingw.org/wiki

Guessing Game in C – program comparison

•Library functions are made available in C programs with an #include directive, like using Python’s import keyword

•C programs always have a main() function that gets called automatically whenever the program runs

•Statements in C programs are grouped inside { } braces

•Variables in C are not loosely typed so their data type, such as int (integer), must be defined in their declaration

•The end of each statement in C must be denoted with a ; semi-colon character – tabs and spaces are irrelevant

•Control structures in C programs use if , else, and while keywords – in much the same way as Python programs

Coding C++

The coding data structures and control structures described and demonstrated throughout this book in the Python programming language also exist in the C++ programming language. Your skills gained with Python coding can be transferred to that language by recognizing its similarities to Python code. The C++ programming language originated back in the 1980s as an enhancement of the C language, known as “C with classes”. These classes define programming objects that transform the procedural nature of C for object-oriented programming in C++.

The simple Guessing Game program, described in Python code here and here, can be recreated in a similar C++ equivalent.

image

guess.cpp

imageStart a new C++ program by importing libraries to make input-output, random number, and time functions available

#include <iostream>

#include <cstdlib>

#include <ctime>

imageNext, define a “main” function body that will enclose the entire game code and return a zero value on completion

int main( )

{

/* Statements to be added here */

return 0 ;

}

imageNow, add statements to initialize variables with a random number in the range 1-20, a Boolean true, and an integer

srand( time( 0 ) ) ;

int num = ( rand() % 20 ) + 1 ;

bool flag = true ;

int guess = 0 ;

imageAdd a statement to request user input

std::cout << “Guess my number 1-20 : “ ;

imageThen, add a loop statement that reads input into the integer variable and will enclose a conditional test

while ( flag == 1 )

{

std::cin >> guess ; std::cin.ignore( 256 , ‘\n’ ) ;

/* Conditional test to be added here */

}

image

This C++ program will accept floating-point guesses as their value gets truncated to an integer in the assignment to the guess variable.

imageFinally, add a conditional test inside the loop then save, compile, and run the program

if( guess == 0 ) {

std::cout << “Invalid! Enter only digits 1-20\n” ;

break ;

}

else if ( guess < num ) {

std::cout << “Too low, try again : “ ; }

else if ( guess > num ) {

std::cout << “Too high, try again : “ ; }

else {

std::cout << “Correct... My number is ” << num << “\n” ;

flag = 0 ;

}

image

image

The Minimalist GNU for Windows (MinGW) package from sourceforge.net/projects/mingw also optionally provides a compiler for C++ code. In the command here c++ invokes the compiler, the source code file is guess.cpp, and -o guessplus.exe specifies the executable file to be output.

Guessing Game in C++ – program comparison

•Library functions are made available in C++ programs with an #include directive, like using Python’s import keyword

•C++ programs always have a main() function that gets called automatically whenever the program runs

•Statements in C++ programs are grouped inside { } braces

•Variables in C++ are not loosely typed so their data type, such as int (integer), must be defined in their declaration

•The end of each statement in C++ must be denoted with a ; semi-colon character – tabs and spaces are irrelevant

•Control structures in C++ programs use if, else, and while keywords – in much the same way as Python programs

Coding C#

The coding data structures and control structures described and demonstrated throughout this book in the Python programming language also exist in the C# programming language. Your skills gained with Python coding can be transferred to that language by recognizing its similarities to Python code. The C# programming language was developed by Microsoft for its .NET initiative. Programs in C# require the Common Language Runtime (CLR) to be installed on the host computer to produce machine code at runtime – a process known as “Just-In-Time” ( JIT) compilation.

The simple Guessing Game program, described in Python code here and here, can be recreated in a similar C# equivalent.

image

guess.cs

imageStart a new C# program by importing the namespace to make input-output and random number functions available

using System ;

imageNext, define a class structure to enclose the entire game code within a “Main” function

class Guess

{

static void Main( )

{

/* Statements to be added here */

}

} ;

imageNow, add statements to initialize variables with a random number in the range 1-20, a Boolean true, and an integer

Random generator = new Random( ) ;

int num = generator.Next( 1 , 20 + 1 ) ;

bool flag = true ;

int guess = 0 ;

imageAdd a statement to request user input

Console.WriteLine( “Guess my number 1-20 : “ ) ;

imageThen, add a loop statement that reads input into the integer variable and will enclose a conditional test

while ( flag == true )

{

int.TryParse( Console.ReadLine( ) , out guess ) ;

/* Conditional test to be added here */

}

image

This C# program will not accept floating-point guesses as they are intelligently recognized as non-integers by the int.TryParse() function.

imageFinally, add a conditional test inside the loop then save, compile, and run the program

if( guess == 0 ) {

Console.Write( “Invalid! Enter only digits 1-20\n” ) ;

break ;

}

else if ( guess < num ) {

Console.Write( “Too low, try again : “ ) ; }

else if ( guess > num ) {

Console.Write( “Too high, try again : “ ) ; }

else {

Console.Write( “Correct... My number is ” + num + “\n” ) ;

flag = false ;

}

image

image

The Visual Studio Community IDE is a great development environment for C# programming. It is available free from visualstudio.com and includes the C Sharp Compiler (csc.exe). In the command here csc invokes the compiler, /out: guesssharp.exe specifies the executable file to be output, and the source code file is named guess.cs.

Guessing Game in C# – program comparison

•Library functions are made available in C# programs with a using directive, like using Python’s import keyword

•C# programs always have a class structure enclosing a Main() function that gets called automatically when the program runs

•Statements in C# programs are grouped inside { } braces

•Variables in C# are not loosely typed so their data type, such as bool (Boolean), must be defined in their declaration

•The end of each statement in C# must be denoted with a ; semi-colon character – tabs and spaces are irrelevant

•Control structures in C# programs use if, else, and while keywords – in much the same way as Python programs

Coding Java

The coding data structures and control structures described and demonstrated throughout this book in the Python programming language also exist in the Java programming language. Your skills gained with Python coding can be transferred to that language by recognizing its similarities to Python code. The Java programming language has the admirable mantra “write once – run anywhere”. Programs in Java require the Java Runtime Environment ( JRE) to be installed on the host computer to produce machine code at runtime – a process known as “Just-In-Time” ( JIT) compilation.

The simple Guessing Game program, described in Python code here and here, can be recreated in a similar Java equivalent.

image

Guess.java

imageStart a new Java program by defining a class structure to enclose the entire game code within a “main” function

class Guess

{

public static void main( String[ ] args )

{

/* Statements to be added here */

}

} ;

imageNow, add statements to initialize variables with a random number in the range 1-20, a Boolean true, and an integer

int num = ( int ) ( Math.random( ) * 20 + 1 ) ;

boolean flag = true ;

int guess = 0 ;

imageAdd a statement to request user input

System.out.print( “Guess my number 1-20 : “ ) ;

imageThen, add a loop statement that reads input into the integer variable and will enclose a conditional test

while ( flag == true )

{

try {

guess = Integer.parseInt( System.console().readLine() ) ; }

catch ( NumberFormatException ex ) { }

/* Conditional test to be added here */

}

image

This Java program will not accept floating-point guesses as they are recognized as non-integers by the function Integer.parseInt( ).

imageFinally, add a conditional test inside the loop then save, compile, and run the program

if( guess == 0 ) {

System.out.println( “Invalid! Enter only digits 1-20” ) ;

break ;

}

else if ( guess < num ) {

System.out.print( “Too low, try again : “ ) ; }

else if ( guess > num ) {

System.out.print( “Too high, try again : “ ) ; }

else {

System.out.println( “Correct... My number is ” + num ) ;

flag = false ;

}

image

image

The Java Development Kit (JDK) is needed to create Java programs. It is available free from oracle.com and includes the command-line Java Compiler (javac.exe). In the command here javac invokes the compiler for Guess.java source code and will automatically output an executable file named Guess.exe. This can then be run by the JRE using the java command.

Guessing Game in Java – program comparison

•Input-output and random number functions are readily available in Java programs without import statements

•Java programs always have a class structure enclosing a main() function that gets called automatically when the program runs

•Statements in Java programs are grouped inside { } braces

•Variables in Java are not loosely typed so their data type, such as boolean, must be defined in their declaration

•The end of each statement in Java must be denoted with a ; semi-colon character – tabs and spaces are irrelevant

•Control structures in Java programs use if, else, and while keywords – in much the same way as Python programs

Summary

•Modern programming languages, like Python or C, provide a high level of abstraction from low level machine code

•Human-readable high-level source code can be rendered into low-level machine code by an interpreter or by a compiler

•Interpreted programming languages, such as Python, translate source code into bytecode, which can then be executed via their Virtual Machine bytecode interpreter

•Compiled programming languages, such as C, generate intermediate object code that gets combined into machine code, which can then be executed directly on the computer

•The compilation of a C program translates high-level source code into low-level Assembly language then machine code

•Intermediate files generated during the compilation process are normally deleted automatically by the compiler

•The data structures and control structures used in Python also exist in the C, C++, C#, and Java programming languages – so programming skills are transferrable across languages

•Compiled programming languages, such as C, have a main function that is called automatically when the program runs

•Statements in many programming languages are grouped within { } braces and must end with a ; semi-colon

•Programming languages that have strongly typed variables require the data type that the variable may contain, such as int integer, to be defined in the variable declaration

•Like Python, other programming languages can also import functionality from their libraries

•C# programs require the Common Language Runtime (CLR) to be installed to produce machine code at runtime

•Java programs require the Java Runtime Environment (JRE) to be installed to produce machine code at runtime