|< C/C++ Data Types 3 | Main | C/C++ Statements, Expressions & Operators 2 >| Site Index | Download |


 

 

 

 

 

MODULE 3

STATEMENTS, EXPRESSIONS AND OPERATORS 1

 

 

 

 

 

 

My Training Period: xx hours

 

The source code for this Module is: Module 3 C/C++ source codes. and the related worksheet for your practice is: C lab worksheets 5.

 

The C and C++ skills that supposed to be acquired after finishing this tutorial:

 

 

 

 

 

 

 

 

 

 

 

 

Able to understand and use:

  • Statements.

  • Expressions.

  • Operators.

  • The Unary Mathematical Operators.

  • The Binary Mathematical Operators.

  • Precedence and Parentheses.

3.1    Statements

  • A statement is a complete instruction asking the computer to carry out some tasks.

  • Normally written one per line, although some statements span multiple lines.

  • Always end with a semicolon ( ; ), except for preprocessor directive such as #define and #include.

  • For example:

←←←←←

Evaluation direction

x  =  2  +  3;

  • This statement instructs the computer to add 2 to 3 and assign the result to the variable x.

  • C/C++ compiler is not sensitive to white spaces such as spaces, tabs and blank lines in the source code, within the statements.

  • Compiler read a statement in the source code it looks for the characters and for the terminating semicolon and ignores the white space.  For example, three of the following examples are same.

x  =  2   +   3;  or

 

x=2+3;    or

 

x =

2

+

3;

  • You can try compiling the following program example; the ‘not so readable’ codes, then see whether it is valid or not.

#include <stdio.h>

// the main()

int main(){int num=24;char name[ ]="Mr. Testing";printf("My name is %s\n",name); printf("My age is %d\n",num);return 0;}

#include <stdio.h>

// the main()

int main(){int num=24;

char name[ ]="Mr. Testing";printf("My name is %s\n",name);

printf("My age is %d\n",num);return 0;}

#include <stdio.h>/* must be new line */

/* the main() */ int main(){/* variables */int num=24;char name[ ]="Mr. Testing";printf("My name is %s\n",name); printf("My age is %d\n",num);return 0;}

Output:

 

C C++ literal string output snapshot

C C++ literal string output snapshot

printf("Hello, \

      World");

printf("Hello, "

      "World");

cout<<"\nNow I'm in FunctTwo()!\nmay do some work here..."

              <<"\nReceives nothing but return something"

              <<"\nto the calling function..."<<endl;

"A" and  'a' both are same.

 

3.2    A Block of Code Structure

C/C++ a block of codes output snapshot

                     {    printf("Hello, ");

                     printf("world! ");    }

 

Note:

  1. Bracket / square bracket -  [ ]

  2. Parentheses -  ( )

  3. Curly braces/braces -  { }

  4. Angled brackets - <    >

 

3.3    Expressions

PI    // a symbolic constant defined in the program

        Evaluates to the value it was given when it was created with the #define directive.

 

20    // a literal constant

        Evaluates to its own value.

 

yield    // a variable

       Evaluates to the value assigned to it by the program.

1.25 / 8  +  5 * rate + rate * rate / cost;

 

x  =  2   +  8;

 

x  =  a  +  10;

 

variable  =  any_expression;

 

y = x = a + 10;

 

x = 6 + (y = 4 + 5);

 

3.4      Operators

x  =  2  +  3;

 

 +  and    =    are operators.

2  and    3     are operands.

x   is variable.

1.    The assignment operator ( = ).

2.    Mathematical operators ( +, -, /, *,  %).

3.    Relational operators ( >, <, >=, <=, ==, !=).

4.    Logical operators (AND, OR, NOT, &&, ||).

x  =  y;

 

 

3.4.1    The Unary Mathematical Operators

1.  2 unary mathematical operators (++ and --) and

2.  5 binary mathematical operators (discussed later).

Operator

Symbol

Action

Examples

Increment

++

Increment operand by one

++xx++

Decrement

--

Decrement operand by one

--x, x--

 

Table 3.1

++x        same as                  x = x  + 1

--y          same as                  y = y  + 1

Postfix mode:

 

x  =  10;

y  =  x++;

Prefix mode:

 

y  =  10;

y  =  ++x;

// demonstrates the unary operators prefix and postfix modes

#include <stdio.h>

 

int  main()

{

       int    a, b;

       // set a and b both equal to 5

       a  =  b  =  5;

       // print them, decrementing each time

       // use prefix mode for b, postfix mode for a

       printf("postfix mode and prefix mode example\n");

       printf("initial value, a = b = 5\n");

       printf("\npostfix mode, a-- = %d  prefix mode, --b = %d", a--, --b);

       printf("\npostfix mode, a-- = %d  prefix mode, --b = %d", a--, --b);

       printf("\npostfix mode, a-- = %d  prefix mode, --b = %d", a--, --b);

       printf("\npostfix mode, a-- = %d  prefix mode, --b = %d", a--, --b);

       printf("\npostfix mode, a-- = %d  prefix mode, --b = %d", a--, --b);

       printf("\n");

 

       return 0;

  }   

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

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

 

C C++ postfix and prefix operators output snapshot

 

#include <stdio.h>

 

int main()

{

      int j = 0, k = 10;

 

      printf("j = %d, k = %d\n", j, k);

      j = ++k;

      printf("j = ++k ----> j = %d, k = %d\n", j, k);

      j = k++;

      printf("j = k++ ----> j = %d, k = %d\n", j, k);

      j = --k;

      printf("j = --k ----> j = %d, k = %d\n", j, k);

      j = k--;

      printf("j = k-- ----> j = %d, k = %d\n", j, k);

 

      // equivalent to

      j = 0;

      k = 10;

 

      printf("\nj = %d, k = %d\n", j, k);

      k = k + 1;

      j = k;

      printf("j = %d, k = %d\n", j, k);

      j = k;

      k = k + 1;

      printf("j = %d, k = %d\n", j, k);

      k = k - 1;

      j = k;

      printf("j = %d, k = %d\n", j, k);

      j = k;

      k = k - 1;

      printf("j = %d, k = %d\n", j, k);

 

      return 0;

}

 

A sample output:

 

C postincrement, postdecrement, preincrement and predecrement program example

3.4.2    Format specifiers

Format specifier

Description

%d

Is to print decimal integers.

%s

Is to print character strings.

%c

Is to print character.

%f

Is to print floating-point number.

%.2f

Prints numbers with fractions with up to two decimal places.

%u

Prints unsigned integer

 

Table 3.2

// format specifier example

#include <stdio.h>

 

int main()

{

   printf("My name is %s and I am %d  years old.\n", "John", 25);

   printf("Examples of the decimal points %f\t%.3f\t%.2f\t\n",1.7885,1.7885,1.7885);

   printf("Examples of characters\n");

   printf(" %c \n %c \n %c\n", 'A', 'B', 'a');

   return 0;

}

 

Output:

 

C C++ format specifier output snapshot

 

3.4.3    The Binary Mathematical Operators

Operator

Symbol

Action

Example

Addition

+

Adds its two operands

x  +  y

Subtraction

-

Subtracts the second operand from the first operand

x  -  y

Multiplication

*

Multiplies its two operands

x  *  y

Division

/

Divides the first operand by the second operand

x  /  y

Modulus

%

Gives the remainder when the first operand is divided by the second operand

x  %  y

 

Table 3.3

C/C++ Modulus operator output snapshot

C/C++ Modulus operator output snapshot

#include <stdio.h>

 

int main()

{

      int modres1, modres2, modres3, modres4, modres5, modres6, modres7;

     

      modres1 = 6 % 4;

      printf("6 %% 4 = %d\n", modres1);

      modres2 = 4 % 6;

      printf("4 %% 6 = %d\n", modres2);

      modres3 = 6 % 3;

      printf("6 %% 3 = %d\n", modres3);

      modres4 = 3 % 6;

      printf("3 %% 6 = %d\n", modres4);

      modres5 = 1 % 3;

      printf("1 %% 3 = %d\n", modres5);

      modres6 = 3 % 1;

      printf("3 %% 1 = %d\n", modres6);

      modres7 = 0 % 3;

      printf("0 %% 3 = %d\n", modres7);

     

      return 0;

}

 

A sample output:

 

C modulus operator program example

#include <stdio.h>

#include <math.h>

 

int main()

{

      int intnumber, condition, remainder, x;

      // counter to store the number of digit entered by user

      int counter = 0;

 

      // prompt user for input

      printf("Enter an integer number: ");

      // read and store input in intnumber

      // scanf("%d", &intnumber);

      scanf_s("%d", &intnumber, sizeof(int));

      // set the condition sentinel value to intnumber

      condition = intnumber;

 

      // we need to determine the number of digit

      // entered by user and store it in counter

      while (condition > 0)

      {

         condition  = condition /10;

         counter = counter + 1;

      }

 

      // well, we already know the number of digit entered by user,

      // start with number of digits less 1, because we need to discard

      // the last one, pow(10.0,1)

      counter = counter - 1;

      printf("The individual digits: \n");

      while (counter >= 0)

      {

         // extract each of the decimal digits, need to cast to int

         // to discard the fraction part

         // pow(10, counter) used to determine the ...,10000, 1000, 100, 10, 1

         // because initially we don't know how many digits user entered...

               x = (int)pow(10.0, counter);

         remainder = intnumber % x;

         intnumber = intnumber / x;

         printf("%d  ", intnumber);

         intnumber = remainder;

         counter = counter - 1;

        }

 

        printf("\n");

        return 0;  

}

 

A sample output:

 

Using C modulus operator to separate integer digits individually

// modulus operator example in C version.

// inputs a number of seconds, and converts to hours, minutes and seconds.

#include <stdio.h>

// #define preprocessor directive, define constants,

// every occurrence of the SEC_PER_MIN token

// in the program will be replaced with 60

#define  SECS_PER_MIN     60

#define  SECS_PER_HOUR    3600

 

int main()

{

    unsigned seconds, minutes, hours, secs_left, mins_left;

    // prompting user to input the number of seconds

    printf("Enter number of seconds  < 65000 :  ");

    // read and store the data input by user

    scanf("%d", &seconds);

    // do the modulus operation

    hours     =  seconds  /  SECS_PER_HOUR;

    minutes   =  seconds  /  SECS_PER_MIN;

    mins_left =  minutes  %  SECS_PER_MIN;

    secs_left =  seconds % SECS_PER_MIN;

    // display the result

    printf("%u seconds is equal to  ", seconds);

    printf("%u hours, %u minutes, and %u seconds\n", hours, mins_left, secs_left);

    return 0;

}

 

Output:

 

C/C++ time and date

// modulus operator example.

// inputs a number of seconds, and converts to hours, minutes and seconds.

#include   <iostream>

using namespace std;

 

// define constants

#define  SECS_PER_MIN     60

#define  SECS_PER_HOUR    3600

 

void main()

{

       unsigned int seconds, minutes, hours, secs_left, mins_left;

       // prompting user to input the number of seconds

       cout<<"Enter number of seconds  < 65000 :  ";

       cin>>seconds;

       hours     =  seconds  /  SECS_PER_HOUR;

       minutes   =  seconds  /  SECS_PER_MIN;

       mins_left =  minutes  %  SECS_PER_MIN;

       secs_left =  seconds % SECS_PER_MIN;

       cout<<seconds<<" seconds is equal to  "<<hours<<" hours, "<<mins_left<<" minutes, "<<secs_left<<" seconds"<<endl;

}

 

Output:

 

time

 

3.5    Precedence And Parentheses

x  =  4  +  5  * 3;

 

If the addition is performed first, x is assigned the value 27 as follow:

 

x  =  9 * 3;

 

If the multiplication is performed first, x is assigned the value of 19 as follows:

 

x  =  4  +  15;

Operators

Relative precedence

Rank

++, --

1

Highest

     

Lowest

*, /, %

2

+, -

3

Highest Lowest

 

Table 3.4 : Operator precedence

C C++ operator precedence

x    =  (4 + 5) * 3

     =  9 * 3

     =  27

C c++ operator precedence parentheses

 

1.        The innermost, 8 / 2 is evaluated first.

 

8 / 2 = 4

 

25 – (2 * (10 + 4))

 

2.        Moving outward, 10 + 4 = 14

 

25 – (2 * 14)

 

3.        The outer most, 2 * 14  = 28

 

25 – 28

 

4.        The final expression, 25 – 28

 

25 – 28 = -3

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C and C++ reading and digging:

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

  2. The source code for this Module is: Module 3 C/C++ source codes. and the related worksheet for your practice is: C lab worksheets.

 

 

 

 

|< C/C++ Data Types 3 | Main | C/C++ Statements, Expressions & Operators 2 >| Site Index | Download |


C and C++ Statements, Expressions & Operators:  Part 1 | Part 2 | Part 3 |