| Main | Basic Data Type 1 >| Site Index | Download |


 

 

 

 

 

MODULE 1

INTRODUCTION TO C and C++

 

 

 

 

 

 

 

My Training Period:   xx hours 

 

The source code for this Module is: C/C++ source codes and the practice worksheet is: Running my first C program and printf(), main(). For other compilers, please check the documentations.

 

The skills that supposed to be acquired in this session:

 

  • Able to understand the brief history of the C/C++ language.

  • Able to understand the C/C++ advantageous.

  • Able to understand the basic program development cycle.

  • Able to understand the basic structure of C/C++ program.

  • Able to be familiar with writing codes, compiling and running a program.

  • Able to recognize a portable main() function.

  • Able to recognize the C and C++ standards: ANSI C/C++, ISO/IEC C/C++, POSIX and Single Unix specification.

 

1.1   C and C++ Brief History

  • C evolved from two previous languages, BCPL (Basic Combined Programming Language) and B. BCPL was developed in 1967 by Martin Richards as a language for writing operating systems software and compilers.

  • Ken Thompson modeled many features in his language, B, after their counterparts in BCPL and used B to create early versions of UNIX operating system at bell Laboratories in 1970 on a DEC PDP-7 computer.

  • Both BCPL and B were typeless languages, that means the only data type is machine word and access to other kinds of objects is by special operators or function calls.

  • In C, the fundamental data type includes characters (char), integers of several sizes (int) and floating point (float) numbers.

  • The derived data types were created with pointers, arrays, structures, unions, functions and classes.

  • The C language was evolved from B by Dennis Ritchie at Bell Laboratories and was originally implemented on a DEC PDP-11 computer in 1972.

  • It was named C for new language.

  • Initially, C used widely as the development language of the UNIX.  Today, virtually all new major OS are written in C.

  • C is hardware independent, so it is portable to most computers without or with little code modification.

  • The rapid expansion of C over various types of computers led to many variations.  These are similar but incompatible.

  • So, a standard version of C was needed.  In 1983, the X3J11 technical committee was created under the American National Standards Institute (ANSI) Committee on Computer and Information Processing (X3) to provide an unambiguous and machine-independent definition of the language and approved in 1989, called ANSI C.

  • The document is referred to as ANSI/ISO 9899:1990.

  • The second edition of Kernighan and Ritchie, published in 1988, reflects this version called ANSI C, then used worldwide.

  • The more general ANSI then adopted by ISO/IEC, known as ISO/IEC C. Historically, from ISO/IEC, C programming language evolved from C89/C90/C95, C99 and the latest is C11.

  • Because C is a hardware-independent, applications written in C can be run with little or no modifications on a wide range of different computer systems.

1.2    C and C++ Advantageous

1.3   Very Basic C and C++ Program Development

  1. Define the problem.

  2. Devise a plan to solve it.

  3. Implement the plan.

  4. Test the result to see whether the problem is solved.

  1. Determine the objectives of the program.

  2. Decide which method the program will use to solve the problem while preparing the pseudocode or flowchart.

  3. Translate this pseudocode or flowchart into a computer program using the C/C++ language.

  4. Run and test the program.

No

Step

Description

1

Using an editor to enter the source code

From a simple text editor up to complex Integrated/interactive Development Environment (IDE).  Examples:

UNIX:  ed, ex, edit, emacs and vi.

Window OS:  notepad, Microsoft Visual Studio/.Net®, Borland® C++, Borland Turbo® C++, Borland Builder C++, BorlandX.

MSDOS®: editor and more...

2

Using a compiler

Computer can’t understand the roman alphabets like English words.  It only can understand machine language, 0’s and 1’s.  The compiler perform this task, yields an object code (such as.obj or .o).

3

Creating an executable file

C/C++ has function library that contains object code (codes that has been compiled) for predefined functions.  These codes are ready to be used and can be called in the main program such as printf() function.  They perform frequently needed tasks.  Executable program can be run or executed.  Before the executable program is created, a program called linker (to link other object and library files needed by the main program) performs a process called linking.

4

Running/executing the program

Running the executable file/image/binary.  If there is no error, that is your program! (a running program or a process).

5

Debugging

Debug, debug and debug, finding program bugs, this is in debug mode.

Alfa version - May still contains bugs, pre-release version.

Beta / RC, Release Candidate version - May still contains bugs, pre-release version.

Final release – Release mode or Retail version (in reality, still having bugs), solved by applying Patches and/or Service Packs (SP).)

6

Release/Distribution

Creating the installation program/package for distribution.

 

C C++ Compile link execute

C C++ very simple program structure

1.4   C++ Object Oriented Programming

1.5    Sample of Simple Program Examples

 

 

 

Program Examples – Warming up!

 

 

 

 

 

 

 

 

 

 

 

 

Example #1

// the simplest program example

// preprocessor directives - header files

#include <iostream>

using namespace std;

 

// main() function with no argument with int return value…

int main( )

{

     cout<<"testing 1..2..3..\n";

     // return to operating system, no error

     return 0;

}

 

Output:

 

C program example snapshot output

 

 

// a program to calculate total based on the given quantity and price

// preprocessor directives - header files

#include <iostream>

using namespace std;

 

// main() function with no argument and int return value…

int main(void)

{

// variables declaration and their respective the data types

int   quantity;

float price, total;

cout<<"testing 1..2..3..\n";

// standard output - read from user input

cout<<"\nEnter the item's price: RM ";

// standard input - store user's input at variable price

cin>>price;

cout<<"\nEnter the item's quantity: ";

cin>>quantity;

// multiply quantity and price store the result at total…

total = quantity * price;

// print the total value

cout<<"\nTotal price = RM  "<<total<<endl;

return 0;

}

 

Output:

 

 

C program example snapshot output

 

Example #2

 

// a simple greeting program using an array, pointer and selection

// you will learn more about array, pointer and selection later.

// the following #include … called preprocessor directive/header files.

// include the iostream file so that the compiler can find the definition for the cin and cout

#include <iostream>

using namespace std;

 

int main(void)

{

    // normal variable and array with their respective data type

    char name[10], name1[10], sex;

    cout<<"\nEnter your first name (max 10 characters): ";

    cin>>name;

    cout<<"Enter your last name (max 10 characters): ";

    cin>>name1;

    cout<<"\nEnter your sex (M or F): ";

    cin>>sex;

    // conditional test whether male or female, if character 'M'

    if (sex == 'M')

    // then display this...an array name without brackets is the pointer to the first array's element

         cout<<"\nHow are you, Mr. "<<name<<" "<<name1<<endl;

    // else, if character 'F' display this...

    else

         cout<<"\nHow are you, Ms/Mrs  "<<name<<" "<<name1<<endl;

    return 0;

}

 

Output:

 

C C++ program example snapshot output

 

Example #3

 

// one line comment in program

/* multiple lines comment, C program to display

square and square root for a given number */

#include <math.h>   /* for sqrt() function */

#include <stdio.h>

 

int main( )

{

    /* variable named x with floating-point data type */

    float x;

    /* standard output  writing a positive floating number */

    printf("\nEnter one positive number (1, 2, 3. . .): ");

    /* standard input reading floating number */

    scanf("%f", &x);

    printf("\nx = %f ", x);

    printf("\nSquare for x is = %f", x * x);

    // sqrt() is the predefined function, defined in math.h

    printf("\nSquare root for x is = %f\n", sqrt(x));

    return 0;

}

 

Output:

 

C C++ program example snapshot output

 

Example #4

 

/* a simple mathematics calculation */

// C header file…

#include <stdio.h>

 

// main() function…

int main( )

{

    // variables declaration

    int  x, y, z;

    // variables initialization, assign 20 to variable x…

    // or put the value of 20 in memory location labeled by x

    x = 20;

    y = 2;

    printf("Given x = 20, y = 2\n");

    printf("\nx / y = %d", x / y);

    // do some basic calculations

    x = x * y;

    y = y + y;

    printf("\nx = x * y");

    printf("\ny = y + y");

    printf("\nNew value for x / y = %d", x / y);

    z = 20 * y / x;

    printf("\nz = 20 * (y / x) = %d\n", z);

   return 0;

}

 

Output:

 

More C C++ program example snapshot output

 

Example #5

 

// another simple mathematics calculation

// C++ header file

#include <iostream>

using namespace std;

 

int main(void)

{

    // variables declaration, with variable names and type

    float a, b, c;

    // variables initialization

    a = 2.0;

    b = 5.0;

    c = b / a;

    cout<<"\nGiven a = 2.0, b = 5.0, c = b/a";

    cout<<"\nc = "<<c;

    c = c + (a/b);

    cout<<"\nc = c + (a/b) = "<<c<<endl;

 

   return 0;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

---------------------------------------------------------------------------------

 

C C++ snapshot output

 

 

Example #6

 

// another mathematics calculation

#include <iostream>

using namespace std;

 

int main(void)

{

    float x, y, z;

    // prompt for user data to standard output, a screen

    cout<<"\nKey in 1st positive integer, then press Enter key: ";

    // read the data from standard input, a keyboard

    cin>>x;

    cout<<"Key in 2nd positive integer, then press Enter key: ";

    cin>>y;

    cout<<"Key in 3rd positive integer, then press Enter key: ";

    cin>>z;

    cout<<"\nAverage for three numbers is \n";

    cout<<"\n    = ("<<x<<"+"<<y<<"+"<<z<<")/3 = "<<(x+y+z)/3<<"\n";

    return 0;

}

 

Output:

 

C C++ screen snapshot output

 

    // previous example compiled using VC++/VC++ .Net

    #include <iostream>

    #include <cstdlib>

    using namespace std;

   

    int main(void)

    {

        float x, y, z;

        // prompting for user data to standard output, a screen

        cout<<"\nKey in 1st positive integer, then press Enter key: ";

        // read the data from standard input, a keyboard

        cin>>x;

        cout<<"Key in 2nd positive integer, then press Enter key: ";

        cin>>y;

        cout<<"Key in 3rd positive integer, then press Enter key: ";

        cin>>z;

        cout<<"\nAverage for three numbers is \n";

        cout<<"\n = ("<<x<<"+"<<y<<"+"<<z<<")/3 = "<<(x+y+z)/3<<"\n";

        system("pause");

        return 0;

    }

 

  Output:

 

C snapshot output of the program example

1.6  The main() function

 

int main()

{

      return 0;

}

 

 

int main (int argc, char* argv[])

{

      return 0;

}

 

 

argc

Is an argument count that is the number of command line arguments the program was invoked with.

argv[ ]

Is an argument vector that is a pointer to an array of character strings that contain the arguments, one per string.

 

 

C C++ command line argument example console output

 

// echoing command-line arguments program example

#include <stdio.h>

 

int main(int argc, char *argv[])

{

   int x;

   // using for loop to iterate all the character...

   for(x = 1; x < argc; x++)

        printf("%s%s", argv[x],(x<argc-1) ? " ": "");

   // go to a new line...

   printf("\n");

   return 0;

}

 

return 0;

void main()

{...}

void main()

{

  return;

}

[bodo@bakawali ~]$ vi simath.c

/* A very simple mathematics calculation-simath.c */

// C header files.

#include <stdio.h>

 

// main() function.

int main( )

{

        // variables declaration

        int     x, y, z;

        // variables initialization, assign 20 to variable x.

        // or put the value of 20 in memory location labeled by x

        x = 20;

        y = 2;

        printf("Given x = 20, y = 2\n");

        printf("\nx / y = %d", x / y);

        // do some basic calculation

        x = x * y;

        y = y + y;

        printf("\nx = x * y");

        printf("\ny = y + y");

        printf("\nNew value for x / y = %d", x / y);

        z = 20 * y / x;

        printf("\nz = 20 * (y / x) = %d\n", z);

        return 0;

}

 

[bodo@bakawali ~]$ gcc simath.c -o simath

[bodo@bakawali ~]$ ./simath

Given x = 20, y = 2

 

x / y = 10

x = x * y

y = y + y

New value for x / y = 10

z = 20 * (y / x) = 2

 

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

C and C++ further reading and digging:

 

 

  1. Check the best selling C / C++ books at Amazon.com.

  1. Get the latest C/C++ standards reference.  You can download or read online the specifications at the following links.  These links are very useful if you want the update information such as new features, obsolete items etc.  ISO/IEC is covering ANSI and is more general.

a. ISO/IEC 9899 (ISO/IEC 9899:1999) - C Programming language.

b. ISO/IEC 9945:2002 POSIX standard.

c. ISO/IEC 14882:1998 on the programming language C++.

d. ISO/IEC 9945:2003, The Single UNIX Specification, Version 3.

e. The GNU C and GNU C++ libraries.

  1. For the use of the standard and non-standard header files with different compilers and mixing C and C++ codes and libraries, please refer to Namespaces, mainly Section 23.3 and above.  If you are a beginner, it is better for you to read this chunk first.

  2. Find a lot of information about C++ history and evolution at Bjarne Stroustrup's site.

 

 

 

 

 

 

| Main | Basic Data Type 1 >| Site Index | Download |