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.
| Able to understand and use:
3.1 Statements
x = 2 + 3; or
x=2+3; or
x = 2 + 3;
|
#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;}
Or something like this:
#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;}
Or like this:
#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;}
The most important thing here is the semicolon that defines a statement and codes such as preprocessor directive and comments that cannot be in the same line with other codes. See also how the white spaces have been ignored and how the compiler read the codes.
But there is an exception: For Literal string constants, white space such as tabs and spaces are considered part of the string.
A string is a series of characters or combination of more than one character.
Literal string constants are strings that are enclosed within double quotes and interpreted literally by the compiler, space by space.
above is legal but,
To break a literal string constant line, use the backslash character ( \ ) just before the break, like this:
printf("Hello,\
World");
Or use double quotation pair,
printf("Hello,"
"World");
For C++ you can use the double quotation pair, " " for each literal string for each line, so can break more than one line easily.
For example:
cout<<"\nNow I'm in FunctTwo()!\nmay do some work here..."
<<"\nReceives nothing but return something"
<<"\nto the calling function..."<<endl;
For a character, we use single quotation mark (''). So, you can see that for one character only, the using " " and '' should provide the same result isn’t it? For example:
"A"and 'a' both are same.
Is a group of more than one C/C++ statements enclosed in curly braces. For example:
is same as:
{ printf("Hello,");
printf("world! "); }
Note:
Bracket / square bracket - [ ]
Parentheses - ( )
Curly braces/braces - { }
Angled brackets - < >
Is anything whose evaluation yields a numerical value is called expression.
For example:
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.
More complex expression use operators (combining the simple expressions).
For example:
1.25 / 8 + 5 * rate + rate * rate / cost;
x = 2 + 8;
x = a + 10;
The last one evaluates the expression a + 10 and assigns the result to variable x.
So, the general form of expression and variables, evaluated from the right to left, is:
variable = any_expression;
|
For example:
y = x = a + 10;
x = 6 + (y = 4 + 5);
Is a symbol that instructs C / C++ to perform some operation, or action, on one or more operands.
Operand is something that an operator acts on.
For example:
x = 2 + 3;
+ and = are operators.
2 and 3 are operands.
x is variable.
In C/C++, all operands are expressions; and operators fall into several categories as follow:
1. The assignment operator (= ).
2. Mathematical operators (+,-, /,*, %).
3. Relational operators (>,<, >=,<=, ==,!=).
4. Logical operators (AND,OR, NOT,&&, ||).
An example of the assignment operator:
x = y;
Assign the value of y to variable x and this is called assignment statement.
Left side (lvalue) must be a variable name.
Right side (rvalue) can be any expression.
The evaluation from right to left.
Mathematical operators perform mathematical operations such as +, -, *, % and /.
C / C++ has:
1. 2 unary mathematical operators (++ and --) and
2. 5 binary mathematical operators (discussed later).
Called unary because they take a single operand as shown in table 3.1.
Operator | Symbol | Action | Examples |
Increment | ++ | Increment operand by one | ++x, x++ |
Decrement | -- | Decrement operand by one | --x, x-- |
Table 3.1 |
These operators can be used only with variables not with constants.
To add 1 or to subtract 1 from the operand.
++x same as x = x + 1
--y same as y = y + 1
++x and --y are called prefix mode, that means the increment or decrement operators modify their operand before it is used.
x++ and y-- are called postfix mode, the increment or decrement operators modify their operand after it is used. Remember the before used and after used words.
For example:
Postfix mode:
x = 10;
y = x++;
After these statements are executed, x = 11, y has the value of 10, the value of x was assigned to y, and then x was incremented.
Prefix mode:
y = 10;
y = ++x;
Both y and x having the value of 11, x is incremented, and then its value is assigned to y.
Try the following program and study the output and the source code.
// 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;
}
--------------------------------------------------------------------------------------
Change all the -- operator to ++ operator and re-run the program, notice the different.
If ++k or --k occurs in an expression, k is incremented or decremented before its value is used in the rest of the expression. If k++ or k-- occurs in an expression, k is incremented or decremented after its value is used in the rest of the expression.
Expression | Operation | Interpretation |
j = ++k | Preincrement | k = k + 1; j = k; |
j = k++ | Postincrement | j = k; k = k + 1; |
j = --k | Predecrement | k = k -1; j = k; |
j = k-- | Postdecrement | j = k; k = k - 1 |
Try another example.
#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:
Is used withprintf() and scanf() function and other input/output functions to determine the format of the standard output (screen) and standard input (keyboard).
The frequently used format specifiers are listed in Table 3.2. Other format specifiers and their usage will be discussed in formatted input/output Module in more detail.
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 |
Try the following program example and study the output and the source code.
// 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;
}
C / C++ binary mathematical operators take two operands as listed in Table 3.3.
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 |
Modulus example:
Modulus operation example.
#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:
Another example, finding and separating the digits in an integer.
#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:
Try the following program example and study the output and the source code.
// 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;
}
C++ version program example:
// 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;
}
Expression that contains more than one operator, the order in which operation are performed can be confusing.
For example:
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;
So, need some rules to define the order in which operations are performed. This is called operator precedence.
Operator with higher precedence is performed first.
Precedence examples:
Operators | Relative precedence | Rank |
++, -- | 1 | Highest ↓ Lowest |
*, /, % | 2 | |
+, - | 3 | |
Highest→ Lowest | ||
Table 3.4 : Operator precedence |
If the operators are in the same level, then, the operators are performed from left to right order, referring to table 3.4.
For example:
But a sub expression enclosed in the parentheses, ( ), is evaluated first, without regard to the operator precedence because parentheses have the highest precedence.
For example:
x = (4 + 5) * 3
= 9 * 3
= 27
For nested parentheses (more than one parentheses), evaluation proceeds from the innermost expression outward.
For example:
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
Use parentheses in expressions for clarity and readability, and must always be in pairs.
The source code for this Module is: Module 3 C/C++ source codes. and the related worksheet for your practice is: C lab worksheets.