Programming Workshop (basic level)
Previous: Chapter 1

Chapter 2

At the end of chapter 1 I promised to tell you about the origin of the names C and C++. Well, when Dennis Ritchie invented C in the 70s it was the third attempt on a programming language, the other two called "A" and "B".

C has features to generate especial fast machine code. The operators "+=" and "++" are such elements. The CPU is much faster incrementing a variable and using it than loading a second value, add it to the variable and store the variable and after that using the variable again.

In the last chapter you heard that the operation "c++" uses the variable c and then increments it. This is what the language C++ does in comparison to C. You can use the programming language C and then add some extras of the new language.

C/C++ are compiled languages. This means after writing the code you "compile" the program. The result is an executable file. On the windows OS these files have the file extension ".exe". There are many compilers available. For the Windows OS most use the compiler that comes with Microsoft "Visual Studio" which is a powerful IDE ("Integrated development environment"). As installing and setting up Visual Studio needs a few hours, we have to look for a faster option.

In chapter 1 we dived into the world of programming using JavaScript. We started with JavaScript as there is nothing needed except a web browser to start. Now we want to explore further into the realm of coding and once again (thanks to the internet) we don't have to install anything:

A first C program

I added comments (after "//") for explanation and comparison to our JavaScript examples

// Programming language: C // Load the library #include <stdio.h> // The main function. Execution starts here. int main(void) { // var a = 3; double a = 3; // var b = 4; double b = 4; // var c; double c; // a = prompt("Please enter a number", 3); puts("Please enter a number"); scanf("%lf", &a); // b = prompt("Please enter a second number", 4); puts("Please enter a second number"); scanf("%lf", &b); // c = a * b; c = a * b; // alert(c); printf("%g\n\n\n", c); // End and return the number 0 return 0; }

Operator "//": Comment until the end of the line.

Operator "/*": Comment until the operator "*/".

Comments work in Javascript too!

#include <stdio.h>

This loads the library "stdio" which means standard input and output (2).

int main(void)

This defines a function (or subroutine) by the name "main". The compiler looks for a function "main" as the starting point. We don't need any arguments, so the argument is "void" which means empty. The function returns a number of the type "int" which stands for integer.

Coding block is between "curly brackets" "{" and "}"

double a = 3;

Declares a variable of the type "double". This means double precision floating-point number. Sets its value to the number 3.

puts("Please enter a number");

"Put String" - works like "alert" in JavaScript.

scanf("%lf", &a);

"Scan File" - the "file" in this case is the keyboard. "%lf" - read a "long float". "&a" - save it in the variable a.

printf("%g\n\n\n", c);

"Print Formatted". "%g" - Take the next argument (the value of the variable "c"), and print it on the screen (assuming it is a floating-point number). "\n\n\n" - print three times "new line".

return 0;

Return from this function the value 0.

Does JavaScript have variable types too?

<script> var a = prompt("Please enter a number", 3); var b = prompt("Please enter a second number", 4); // We replaced "*" by "+" var c = a+b; c = c + 1; alert(c); </script>

What went wrong? Try entering text instead of a number!

The secret power of web browsers

Most web browsers have Web development tools integrated!

Press F12 to open the developer tools in Firefox or Chrome!

ctrl + shift + I works too!

Inspect an element in the page.

Debug: Run, step over, step into, step out...

Let us fix our problem!

<script> var a = prompt("Please enter a number", 3); var b = prompt("Please enter a second number", 4); // Make a number out of the text a = parseInt(a); b = parseInt(b); var c = a+b; c = c + 1; alert(c); </script>

"parseInt" makes an integer out of the text. Guess what "parseFloat" means!

Functions and comparison

A vew new concepts in this code:

<script> function hyp(x, y) { return Math.sqrt(x*x+y*y); } var a = prompt("Please enter the x-coordinate", 3); var b = prompt("Please enter the y-coordinate", 4); var c = hyp(a, b); alert("The hypotenuse is: " + c); if(a == b) { alert("a equals b"); } else if(a > b) { alert("a > b"); } else { alert("a < b"); } </script>

function hyp(x, y)

We know functions from C. In JavaScript functions start with the word "function" instead of the type.

if(a == b)

Compare a and b and execute code block when they are equal. Note the operator "==".

else

Execute this code block if the comparison went wrong.

else if

A second comparison after the first follows immediately.

By the way: "!=" stands for "not equal".

Using arrays

<script> function hyp(x, y) { return Math.sqrt(x*x+y*y); } var nr = [3, 4]; nr[0] = prompt("Please enter the x-coordinate", nr[0]); nr[1] = prompt("Please enter the y-coordinate", nr[1]); var c = hyp(nr[0], nr[1]); alert("The hypotenuse is: " + c); </script>

Loops

while(...) {...}

Repeat code block as long as comparison is true.

for(int i = 0; i < 1000; i++) {...}

Set the variable "i" to 0.

Compare "i" to 1000 and start the loop if it is true.

Increment "i".

Next step in the loop...

Calculating prime numbers

Now let us get bigger:


<html> <head> </head> <body> <script> /* Calculate Prime Numbers author: gerold@zuderstorfer.com Modified version of the Sieve of Eratosthenes */ function out(txt) { var el = document.createElement("span"); el.innerHTML = txt; document.body.appendChild(el); } const nr_max_prime = 430; var prime = Array(nr_max_prime); var rest = Array(nr_max_prime); function calc_primes() { var next_p_idx = 0; var cur_num = 1; var cur_p_idx; var is_prime; while(next_p_idx < nr_max_prime) { cur_num++; is_prime = true; for(cur_p_idx = 0; cur_p_idx < next_p_idx; cur_p_idx++) { rest[cur_p_idx]++; if(rest[cur_p_idx] == prime[cur_p_idx]) { is_prime = false; rest[cur_p_idx] = 0; } } if(is_prime) { prime[next_p_idx] = cur_num; rest[next_p_idx] = 0; out("#" + (next_p_idx+1) + ": " + cur_num + "<br />"); next_p_idx++; } } } calc_primes(); </script> </body> </html>

Try it out!

Try out also this interactive version!

Look at the code in C

Look at the code in Matlab


Footnotes:

(2) "#include <mylib.h>" copies the content of the file "mylib.h" at this place. "mylib.h" normaly contains only declarations. So, we declare that we want to use the various elements of the library. After the compilation a program called "linker" glues the (already compiled) library "mylib.obj" to our code.