Anda di halaman 1dari 195

TURBO C AND C++ FUNCTIONS

Group Number 1
Leader:
Bryan M. Bejec
Members:
Asaytono, Marick John S.
Cano, Aldrin
Dizon, Ezekiel
Atienza, Aimee
Vanessa, Laxa
Miranda, Mailalyn Ann
Ms. Robell H. Samson
Teacher in Programming
TURBO C
C Programming Keywords and Identifiers

Character set

Character set is a set of alphabets, letters and some special characters that are valid in C
language.

Alphabets

Uppercase: A B C ................................... X Y Z

Lowercase: a b c ...................................... x y z

C accepts both lowercase and uppercase alphabets as variables and functions.

Digits

0123456789

Special Characters

Special Characters in C Programming

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "

^ ! * / |

- \ ~ +

White space Characters

blank space, new line, horizontal tab, carriage return and form feed
C Keywords

Keywords are predefined, reserved words used in programming that have special meanings to the
compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:

int money;

Here, int is a keyword that indicates 'money' is a variable of type integer.

As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all
keywords allowed in ANSI C.

List of all Keywords in C Language

Keywords in C Programming

auto break case char

const continue default do

double else enum extern

float for goto if

int long register return

short signed sizeof static

struct switch typedef union

unsigned void volatile while


Description of all Keywords in C
auto

The auto keyword declares automatic variables. For example:

auto int var1;

This statement suggests that var1 is a variable of storage class auto and type int.

Variables declared within function bodies are automatic by default. They are recreated each time
a function is executed.

C Programming break and continue Statement

It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.

In such cases, break and continue statements are used.

break Statement

The break statement terminates the loop (for, while and do...while loop) immediately when it is
encountered. The break statement is used with decision making statement such as if...else.

Syntax of break statement

break;

The simple code above is the syntax for break statement.


Flowchart of break statement
How break statement works?

Example #1: break statement


// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number

# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;

for(i=1; i <= 10; ++i)


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is terminated


if(number < 0.0)
{
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a n1: 2.4


Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30

This program calculates the sum of maximum of 10 numbers. It's because, when the user enters
negative number, the break statement is executed and loop is terminated.

In C programming, break statement is also used with switch...case statement.


continue Statement

The continue statement skips some statements inside the loop. The continue statement is used
with decision making statement such as if...else.

Syntax of continue Statement

continue;

Flowchart of continue Statement


How continue statement works?

Example #2: continue statement


// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation

# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is terminated


if(number < 0.0)
{
continue;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a n1: 1.1

Enter a n2: 2.2

Enter a n3: 5.5

Enter a n4: 4.4

Enter a n5: -3.4

Enter a n6: -45.5

Enter a n7: 34.5


Enter a n8: -4.2

Enter a n9: -1000

Enter a n10: 12

Sum = 59.70

In the program, when the user enters positive number, the sum is calculated using sum +=
number; statement.

When the user enters negative number, the continue statement is executed and skips the negative
number from calculation.

C switch...case Statement

The if..else..if ladder allows you to execute a block code among many alternatives. If you are
checking on the value of a single variable in if...else...if, it is better to use switchstatement.

The switch statement is often faster than nested if...else (not always). Also, the syntax of switch
statement is cleaner and easy to understand.

Syntax of switch...case

switch (n)

case constant1:

// code to be executed if n is equal to constant1;

break;

case constant2:
// code to be executed if n is equal to constant2;

break;

default:

// code to be executed if n doesn't match any constant

When a case constant is found that matches the switch expression, control of the program passes
to the block of code associated with that case.

In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute
the block of code associate with the case statement until the end of switch block, or until the
break statement is encountered.

The break statement is used to prevent the code running into the next case.
switch Statement Flowchart

Example: switch Statement

// Program to create a simple calculator


// Performs addition, subtraction, multiplication or division depending the input from user

# include <stdio.h>

int main() {

char operator;

double firstNumber,secondNumber;

printf("Enter an operator (+, -, *, /): ");

scanf("%c", &operator);

printf("Enter two operands: ");

scanf("%lf %lf",&firstNumber, &secondNumber);

switch(operator)

case '+':

printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber,


firstNumber+secondNumber);

break;

case '-':

printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-


secondNumber);

break;

case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);

break;

case '/':

printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber,


firstNumber/firstNumber);

break;

// operator is doesn't match any case constant (+, -, *, /)

default:

printf("Error! operator is not correct");

return 0;
Output

Enter an operator (+, -, *,): -

Enter two operands: 32.5

12.4

32.5 - 12.4 = 20.1

The - operator entered by the user is stored in operator variable. And, two operands 32.5 and
12.4 are stored in variables firstNumber and secondNumber respectively.

Then, control of the program jumps to

printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);


Finally, the break statement ends the switch statement.

If break statement is not used, all cases after the correct case is executed.

Char

The char keyword declares a character variable. For example:

char alphabet;

Here, alphabet is a character type variable.

const

An identifier can be declared constant by using const keyword.

const int a = 5;

C Programming while and do...while Loop

Loops are used in programming to repeat a specific block until some end condition is met. There
are three loops in C programming:

1. for loop
2. while loop
3. do...while loop

while loop

The syntax of a while loop is:

while (testExpression)

//codes
}

where, testExpression checks the condition is true or false before each loop.

How while loop works?

The while loop evaluates the test expression.

If the test expression is true (nonzero), codes inside the body of while loop are exectued. The test
expression is evaluated again. The process goes on until the test expression is false.

When the test expression is false, the while loop is terminated.

Flowchart of while loop

Example #1: while loop

// Program to find factorial of a number

// For a positive integer n, factorial = 1*2*3...n


#include <stdio.h>

int main()

int number;

long long factorial;

printf("Enter an integer: ");

scanf("%d",&number);

factorial = 1;

// loop terminates when number is less than or equal to 0

while (number > 0)

factorial *= number; // factorial = factorial*number;

--number;

printf("Factorial= %lld", factorial);

return 0;
}

Output
Enter an integer: 5

Factorial = 120

do...while loop

The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.

do...while loop Syntax

do
{
// codes
}
while (testExpression);

How do...while loop works?

The code block (loop body) inside the braces is executed once.

Then, the test expression is evaluated. If the test expression is true, the loop body is executed
again. This process goes on until the test expression is evaluated to 0 (false).

When the test expression is false (nonzero), the do...while loop is terminated.
Example #2: do...while loop
// Program to add numbers until user enters zero

#include <stdio.h>
int main()
{
double number, sum = 0;

// loop body is executed at least once


do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a number: 1.5

Enter a number: 2.4

Enter a number: -3.4

Enter a number: 4.2

Enter a number: 0

Sum = 4.70

double and float

Keywords double and float are used for declaring floating type variables. For example:

float number;

double longNumber;

Here, number is single precision floating type variable whereas, longNumber is a double
precision floating type variable.

C if, if...else and Nested if...else Statement

C if statement
if (testExpression)
{
// statements
}

The if statement evaluates the test expression inside the parenthesis.

If the test expression is evaluated to true (nonzero), statements inside the body of if is executed.

If the test expression is evaluated to false (0), statements inside the body of if is skipped from
execution.

To learn more on when test expression is evaluated to nonzero (true) and 0 (false), check
out relational and logical operators.

Flowchart of if statement
Example #1: C if statement
// Program to display a number if user enters negative number
// If user enters positive number, that number won't be displayed

#include <stdio.h>
int main()
{
int number;

printf("Enter an integer: ");


scanf("%d", &number);

// Test expression is true if number is less than 0


if (number < 0)
{
printf("You entered %d.\n", number);
}

printf("The if statement is easy.");

return 0;
}

Output 1

Enter an integer: -2

You entered -2.

The if statement is easy.

When user enters -2, the test expression (number < 0) becomes true. Hence, You entered -2 is
displayed on the screen.

Output 2

Enter an integer: 5

The if statement in C programming is easy.

When user enters 5, the test expression (number < 0) becomes false and the statement inside the
body of if is skipped.

C if...else statement

The if...else statement executes some code if the test expression is true (nonzero) and some other
code if the test expression is false (0).

Syntax of if...else
if (testExpression)
{
// codes inside the body of if
}
else
{
// codes inside the body of else
}

If test expression is true, codes inside the body of if statement is executed and, codes inside the
body of else statement is skipped.

If test expression is false, codes inside the body of else statement is executed and, codes inside
the body of if statement is skipped.

Flowchart of if...else statement


Example #2: C if...else statement
// Program to check whether an integer entered by the user is odd or even

#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);

// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}

Output

Enter an integer: 7

7 is an odd integer.

When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the
statement inside the body of else statement printf("%d is an odd integer"); is executed and the
statement inside the body of if is skipped.

Nested if...else statement (if...elseif....else Statement)

The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.
Syntax of nested if...else statement.

if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3
is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}

Example #3: C Nested if...else statement


// Program to relate two integers using =, > or <

#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}

return 0;
}

Output

Enter two integers: 12

23

Result: 12 < 23

enum

Enumeration types are declared in C programming using keyword enum. For example:

enum suit

hearts;

spades;

clubs;
diamonds;

};

Here, a enumerated variable suit is created having tags: hearts, spades, clubs and diamonds.

extern

The extern keyword declares that a variable or a function has external linkage outside of the file
it is declared.

C Programming for Loop

Loops are used in programming to repeat a specific block until some end condition is met. There
are three loops in C programming:

1. for loop
2. while loop
3. do...while loop

for Loop

The syntax of for loop is:

for (initializationStatement; testExpression; updateStatement)

// codes

How for loop works?

The initialization statement is executed only once.

Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated.
But if the test expression is true (nonzero), codes inside the body of for loop is executed and the
update expression is updated.
This process repeats until the test expression is false.

The for loop is commonly used when the number of iterations is known.

To learn more on test expression (when test expression is evaluated to nonzero (true) and 0
(false)), check out relational and logical operators.

for loop Flowchart

Example: for loop

// Program to calculate the sum of first n natural numbers

// Positive integers 1,2,3...n are known as natural numbers


#include <stdio.h>

int main()

int num, count, sum = 0;

printf("Enter a positive integer: ");

scanf("%d", &num);

// for loop terminates when n is less than count

for(count = 1; count <= num; ++count)

sum += count;

printf("Sum = %d", sum);

return 0;

Output

Enter a positive integer: 10

Sum = 55

The value entered by the user is stored in variable num. Suppose, the user entered 10.

The count is initialized to 1 and the test expression is evaluated. Since, the test expression count
<= num (1 less than or equal to 10) is true, the body of for loop is executed and the value
of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2. Again, the test
expression is evaluated. Since, 2 is also less than 10, the test expression is evaluated to true and
the body of for loop is executed. Now, the sum will equal 3.

This process goes on and the sum is calculated until the count reaches 11.

When the count is 11 the test expression is evaluated to 0 (false) as 11 is not less than or equal to
10. Therefore, the loop terminates and next, the total sum is printed.

C goto Statement

The goto statement is used to alter the normal sequence of a C program.

Syntax of goto statement

goto label;

... .. ...

... .. ...

... .. ...

label:

statement;

The label is an identifier. When goto statement is encountered, control of the program jumps
to label: and starts executing the code.
Example: goto Statement

// Program to calculate the sum and average of maximum of 5 numbers

// If user enters negative number, the sum and average of previously entered positive
number is displayed

# include <stdio.h>

int main()

const int maxInput = 5;

int i;

double number, average, sum=0.0;

for(i=1; i<=maxInput; ++i)

printf("%d. Enter a number: ", i);

scanf("%lf",&number);

// If user enters negative number, flow of program moves to label jump

if(number < 0.0)

goto jump;

sum += number; // sum = sum+number;


}

jump:

average=sum/(i-1);

printf("Sum = %.2f\n", sum);

printf("Average = %.2f", average);

return 0;

Output

1. Enter a number: 3

2. Enter a number: 4.3

3. Enter a number: 9.3

4. Enter a number: -2.9

Sum = 16.60

Reasons to avoid goto statement

The use of goto statement may lead to code that is buggy and hard to follow. For example:

one:

for (i = 0; i < number; ++i)

{
test += i;

goto two;

two:

if (test > 5) {

goto three;

... .. ...

Also, goto statement allows you to do bad stuff such as jump out of scope.

That being said, goto statement can be useful sometimes. For example: to break from nested
loops.

Should I or shouldn't I use goto statement?

If you think the use of goto statement simplifies your program. By all means use it. The goal here
is to create code that your fellow programmers can understand easily.

int

The int keyword declares integer type variable. For example:

int count;

Here, count is an integer variable.


short, long, signed and unsigned

The short, long, signed and unsigned keywodrs are type modifiers that alters the meaning of a
base data type to yield a new type.

short int smallInteger;

long int bigInteger;

signed int normalInteger;

unsigned int positiveInteger;

Range of int type data types

Data types Range

short int -32768 to 32767

long int -2147483648 to 214743648

signed int -32768 to 32767

unsigned int 0 to 65535

return

The return keyword terminates the function and returns the value.

int func()

int b = 5;
return b;

This function func() returns 5 to the calling function.

sizeof

The sizeof keyword evaluates the size of data (a variable or a constant).

#include <stdio.h>

int main()

printf("%u bytes.",sizeof(char));

Output

1 bytes.

register

The register keyword creates register variables which are much faster than normal variables.

register int var1;


static

The static keyword creates static variable. The value of the static variables persists until the end
of the program. For example:

static int var;

struct

The struct keyword is used for declaring a structure. A structure can hold variables of different
types under a single name.

struct student{

char name[80];

float marks;

int age;

}s1, s2;

typedef

The typedef keyword is used to explicitly associate a type with an identifier.

typedef float kg;

kg bear, tiger;
union

A Union is used for grouping different types of variable under a single name.

union student

char name[80];

float marks;

int age;

void

The void keyword indicates that a function doesn't return any value.

void testFunction(int a)

.....

Here, function testFunction( ) cannot return a value because the return type is void.

volatile

The volatile keyword is used for creating volatile objects. A volatile object can be modified in an
unspecified way by the hardware.

const volatile number


Here, number is a volatile object.

Since, number is a constant variable, the program cannot change it. However, hardware can
change it since it is a volatile object.

C Identifiers

Identifier refers to name given to entities such as variables, functions, structures etc.

Identifier must be unique. They are created to give unique name to a entity to identify it during
the execution of the program. For example:

int money;

double accountBalance;

Here, money and accountBalance are identifiers.

Also remember, identifier names must be different from keywords. You cannot use int as an
identifier because int is a keyword.

Rules for writing an identifier

1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
2. The first letter of an identifier should be either a letter or an underscore. However, it is
discouraged to start an identifier name with an underscore.
3. There is no rule on length of an identifier. However, the first 31 characters of identifiers
are discriminated by the compiler.

C Programming Constants and Variables

Variables

In programming, a variable is a container (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location. For example:

int playerScore = 95;

Here, playerScore is a variable of integer type. The variable is assigned value: 95.

The value of a variable can be changed, hence the name 'variable'.


In C programming, you have to declare a variable before you can use it.

Rules for naming a variable in C

1. A variable name can have letters (both uppercase and lowercase letters), digits and
underscore only.
2. The first letter of a variable should be either a letter or an underscore. However, it is
discouraged to start variable name with an underscore. It is because variable name that
starts with an underscore can conflict with system name and may cause error.
3. There is no rule on how long a variable can be. However, only the first 31 characters of a
variable are checked by the compiler. So, the first 31 letters of two variables in a program
should be different.

C is a strongly typed language. What this means it that, the type of a variable cannot be changed.

Constants/Literals

A constant is a value or an identifier whose value cannot be altered in a program. For example: 1,
2.5, "C programming is easy", etc.

As mentioned, an identifier also can be defined as a constant.

const double PI = 3.14

Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.

Below are the different types of constants you can use in C.


1. Integer constants

An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:

decimal constant(base 10)


octal constant(base 8)
hexadecimal constant(base 16)

For example:

Decimal constants: 0, -9, 22 etc

Octal constants: 021, 077, 033 etc

Hexadecimal constants: 0x7f, 0x2a, 0x521 etc


In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.

2. Floating-point constants

A floating point constant is a numeric constant that has either a fractional form or an exponent
form. For example:

-2.0

0.0000234

-0.22E-5

Note: E-5 = 10-5

3. Character constants

A character constant is a constant which uses single quotation around characters. For example:
'a', 'l', 'm', 'F'

4. Escape Sequences

Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C
programming. For example: newline(enter), tab, question mark etc. In order to use these
characters, escape sequence is used.

For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the
characters are interpreted by the compiler.

Escape Sequences

Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return

\t Horizontal tab

\v Vertical tab
Escape Sequences

Escape Sequences Character

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? Question mark

\0 Null character

5. String constants

String constants are the constants which are enclosed in a pair of double-quote marks. For
example:

"good" //string constant

"" //null string constant

" " //string constant of six white space

"x" //string constant having single character.

"Earth is round\n" //prints string with newline

6. Enumeration constants

Keyword enum is used to define enumeration types. For example:

enum color {yellow, green, black, white};

Here, color is a variable and yellow, green, black and white are the enumeration constants having
value 0, 1, 2 and 3 respectively.
C Programming Enumeration

An enumeration is a user-defined data type that consists of integral constants. To define an


enumeration, keyword enum is used.

enum flag { const1, const2, ..., constN };

Here, name of the enumeration is flag.

And, const1, const2,...., constN are values of type flag.

By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements
during declaration (if necessary).

// Changing default values of enum

enum suit {

club = 0,

diamonds = 10,

hearts = 20,

spades = 3,

};

Enumerated Type Declaration

When you create an enumerated type, only blueprint for the variable is created. Here's how you
can create variables of enum type.

enum boolean { false, true };

enum boolean check;

Here, a variable check of type enum boolean is created.


Here is another way to declare same check variable using different syntax.

enum boolean

false, true

} check;

Example: Enumeration Type


#include <stdio.h>

enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;
}

Output

Day 4

Why enums are used in C programming?

Enum variable takes only one value out of many possible values. Example to demonstrate it,

#include <stdio.h>

enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;

int main()
{
card = club;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}

Output

Size of enum variable = 4 bytes

It's because the size of an integer is 4 bytes.

This makes enum a good choice to work with flags.

You can accomplish the same task using structures. However, working with enums gives you
efficiency along with flexibility.
How to use enums for flags?

Let us take an example,

enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
} button;

Suppose you are designing a button for Windows application. You can set
flags ITALICS, BOLD and UNDERLINE to work with text.

There is a reason why all the integral constants are power of 2 in above pseudocode.

// In binary
ITALICS = 00000001

BOLD = 00000010

UNDERLINE = 00000100

Since, the integral constants are power of 2, you can combine two or more flags at once without
overlapping using bitwise OR | operator. This allows you to choose two or more flags at once.
For example,

#include <stdio.h>

enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};

int main() {
int myDesign = BOLD | UNDERLINE;

// 00000001
// | 00000100
// ___________
// 00000101

printf("%d", myDesign);
return 0;
}

Output

When the output is 5, you always know that bold and underline is used.
Also, you can add flag to your requirements.

if (myDesign & ITALICS) {


// code for italics
}

Here, we have added italics to our design. Note, only code for italics is written inside if
statement.

C Programming Data Types

In C programming, variables or memory locations should be declared before it can be used.


Similarly, a function also needs to be declared before use.

Data types simply refers to the type and size of data associated with variables and functions.

Data types in C

1. Fundamental Data Types


o Integer types

Integer

Integers is the set of numbers that include all the whole numbers and their negative values.

The set of integers can be represented as - .... -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5.....

In programming, integer is a data type used to represent integer values. We can declare a variable
as an integer type or define the result of a function or expression as of integer type.

A variable declared as an integer type occupies a specified amount of memory space in


computer. The amount of space occupied depends on the computer system you are using -
typicall ranging from 4 bytes to over 64 bytes.

A variable defined as an integer type cannot store any other types of data such as character like
a,b,c or floating-point numbers like 5.43, -0.43.

In C++, an integer variable is declared as

int a = 5;

In JavaScript, the type is inferred by the interpreter so we just write

var a = 5;
o Floating type

Floating-point

Floating-point are numbers with floating decimal points.

Floating-point, as the name implies, are numbers that contain decimal points that can float left or
right.

In programming, floating-point is used to represent fractions. Numbers such as 1/2, 5/7, -100/3
can be represented in floating-point as 0.5, 0.71428, -33.33.

Often the keyword 'float' is used to declare a variable that stores floating-point numbers.

For example, in C and Java

float pi = 3.14;

However, in other programming languages such as Javascript, Python we do need to specify the
datatype. Instead, we can just write,

var pi = 3.14; (in Javascript)


pi = 3.14 (in Python)

o Character type

Character

Character is a symbol in programming language that has meaning.

A character can be any letter, number, punctuation marks, symbols or whitespace. For example,
the word "character" consists of eight characters, and the phrase "Hello World!" consists of 12
characters including the whitespace and exclamation mark.

In programming character is a datatype. We can declare a variable as of a character type and


store characters in the variable. For example, in C and Java, we write,

char first = 'a';

Characters when storing in a variable must be inserted between single quotes.

String is another datatype in programming, which is a modified version of character datatype.


Strings are used to store more than one characters. For example,

string sentence = "Hello World!";

2. Derived Data Types


o Arrays

C Programming Arrays

An array is a collection of data that holds fixed number of values of same type. For example: if
you want to store marks of 100 students, you can create an array for it.

float marks[100];

The size and type of arrays cannot be changed after its declaration.

Arrays are of two types:

1. One-dimensional arrays
2. Multidimensional arrays (will be discussed in next chapter)

How to declare an array in C?

data_type array_name[array_size];

For example,

float mark[5];

Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5
floating-point values.

Elements of an Array and How to access them?

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], second element
is mark[1] and so on.
Few key notes:

Arrays have 0 as the first index not 1. In this example, mark[0]


If the size of an array is n, to access the last element, (n-1) index is used. In this
example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be
2124d, address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.

How to initialize an array in C programming?

It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int mark[] = {19, 10, 8, 17, 9};

Here,

mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element


mark[3] = 9;

// take input from the user and insert in third element

scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element

scanf("%d", &mark[i]);

// print first element of an array

printf("%d", mark[0]);

// print ith element of an array

printf("%d", mark[i-1]);

Example: C Arrays

Output

Enter n: 5

Enter number1: 45

Enter number2: 35

Enter number3: 38

Enter number4: 31
Enter number5: 49

Average = 39

Important thing to remember when working with C arrays

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can use the array members from testArray[0] to testArray[9].

If you try to access array elements outside of its bound, let's say testArray[12], the compiler may
not show any error. However, this may cause unexpected output (undefined behavior).

o Pointers

C Programming Pointers

Pointers are powerful features of C and (C++) programming that differentiates it from other
popular programming languages like: Java and Python.

Pointers are used in C program to access the memory and manipulate the address.

Address in C

Before you get into the concept of pointers, let's first get familiar with address in C.

If you have a variable var in your program, &var will give you its address in the memory,
where & is commonly called the reference operator.

You must have seen this notation while using scanf() function. It was used in the function to
store the user inputted value in the address of var.

scanf("%d", &var);

/* Example to demonstrate use of reference operator in C programming. */


#include <stdio.h>
int main()
{
int var = 5;
printf("Value: %d\n", var);
printf("Address: %u", &var); //Notice, the ampersand(&) before var.
return 0;
}

Output

Value: 5

Address: 2686778

Note: You may obtain different value of address while using this code.

In above source code, value 5 is stored in the memory location 2686778. var is just the name
given to that location.

Pointer variables

In C, there is a special variable that stores just the address of another variable. It is called Pointer
variable or, simply, a pointer.

Declaration of Pointer

data_type* pointer_variable_name;

int* p;

Above statement defines, p as pointer variable of type int.

Reference operator (&) and Dereference operator (*)

As discussed, & is called reference operator. It gives you the address of a variable.

Likewise, there is another operator that gets you the value from the address, it is called a
dereference operator (*).

Below example clearly demonstrates the use of pointers, reference operator and dereference
operator.
Note: The * sign when declaring a pointer is not a dereference operator. It is just a similar
notation that creates a pointer.

Example to Demonstrate Working of Pointers


/* Source code to demonstrate, handling of pointers in C program */
#include <stdio.h>
int main(){
int* pc;
int c;
c=22;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
c=11;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
*pc=2;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
return 0;
}

Output

Address of c: 2686784

Value of c: 22

Address of pointer pc: 2686784

Content of pointer pc: 22


Address of pointer pc: 2686784

Content of pointer pc: 11

Address of c: 2686784

Value of c: 2

Explanation of program and figure

1. int* pc; creates a pointer pc and int c; creates a normal variable c.


Since pc and c are both not initialized, pointer pc points to either no address or a random
address. Likewise, variable c is assigned an address but contains a random/garbage value.
2. c=22; assigns 22 to the variable c, i.e.,22 is stored in the memory location of variable c.
Note that, when printing &c (address of c), we use %u rather than %d since address is
usually expressed as an unsigned integer (always positive).
3. pc=&c; assigns the address of variable to c to the pointer pc.
When printing, you see value of pc is the same as the address of c and the content
of pc (*pc) is 22 as well.
4. c=11; assigns 11 to variable c.
We assign a new value to c to see its effect on pointer pc.
5. Since, pointer pc points to the same address as c, value pointed by pointer pc is 11 as
well.
Printing the address and content of pc shows the updated content as 11.
6. *pc=2; changes the contents of the memory location pointed by pointer pc to 2.
Since the address of pointer pc is same as address of c, value of c also changes to 2.

Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c. Then,

int c, *pc;

// Wrong! pc is address whereas, c is not an address.


pc = c;

// Wrong! *pc is the value pointed by address whereas, %amp;c is an address.


*pc = &c;

// Correct! pc is an address and, %amp;pc is also an address.


pc = &c;

// Correct! *pc is the value pointed by address and, c is also a value.


*pc = c;

In both cases, pointer pc is not pointing to the address of c.

o Structures

C Programming Structure

Structure is a collection of variables of different types under a single name.

For example: You want to store some information about a person: his/her name, citizenship
number and salary. You can easily create different variables name, citNo, salary to store this
information separately.

However, in the future, you would want to store information about multiple persons. Now, you'd
need to create different variables for each information per person: name1, citNo1, salary1,
name2, citNo2, salary2

You can easily visualize how big and messy the code would look. Also, since no relation
between the variables (information) would exist, it's going to be a daunting task.

A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner, readable and
efficient as well.

This collection of all related information under a single name Person is a structure.

Structure Definition in C

Keyword struct is used for creating a structure.


Syntax of structure

struct structure_name

data_type member1;

data_type member2;

data_type memeber;

};

Note: Don't forget the semicolon }; in the ending line.

We can create the structure for a person as mentioned above as:

struct person

char name[50];

int citNo;

float salary;

};

This declaration above creates the derived data type struct person.
Structure variable declaration

When a structure is defined, it creates a user-defined type but, no storage or memory is allocated.

For the above structure of a person, variable can be declared as:

struct person

char name[50];

int citNo;

float salary;

};

int main()

struct person person1, person2, person3[20];

return 0;

Another way of creating a structure variable is:

struct person

char name[50];

int citNo;
float salary;

} person1, person2, person3[20];

In both cases, two variables person1, person2 and an array person3 having 20 elements of
type struct person are created.

Accessing members of a structure

There are two types of operators used for accessing members of a structure.

1. Member operator(.)
2. Structure pointer operator(->) (is discussed in structure and pointers tutorial)

Any member of a structure can be accessed as:

structure_variable_name.member_name

Suppose, we want to access salary for variable person2. Then, it can be accessed as:

person2.salary

Example of structure

Write a C program to add two distances entered by user. Measurement of distance should
be in inch and feet. (Note: 12 inches = 1 foot)

Output

1st distance

Enter feet: 12

Enter inch: 7.9

2nd distance

Enter feet: 2
Enter inch: 9.8

Sum of distances = 15'-5.7"

Keyword typedef while using structure

Writing struct structure_name variable_name; to declare a structure variable isn't intuitive as to


what it signifies, and takes some considerable amount of development time.

So, developers generally use typedef to name the structure as a whole. For example:

typedef struct complex

int imag;

float real;

} comp;

int main()

comp comp1, comp2;

Here, typedef keyword is used in creating a type comp (which is of type as struct complex).

Then, two structure variables comp1 and comp2 are created by this comp type.

Structures within structures

Structures can be nested within other structures in C programming.


struct complex

int imag_value;

float real_value;

};

struct number

struct complex comp;

int real;

} num1, num2;

Suppose, you want to access imag_value for num2 structure variable then, following structure
member is used.

num2.comp.imag_value

Passing structures to a function

There are mainly two ways to pass structures to a function:

1. Passing by value
2. Passing by reference

o Enumeration
int - Integer data types

Integers are whole numbers that can have both positive and negative values but no decimal
values. Example: 0, -5, 10

In C programming, keyword int is used for declaring integer variable. For example:

int id;

Here, id is a variable of type integer.

You can declare multiple variable at once in C programming. For example:

int id, age;

The size of int is either 2 bytes(In older PC's) or 4 bytes. If you consider an integer having size of
4 byte( equal to 32 bits), it can take 232 distinct states as: -231,-231+1, ...,-2, -1, 0, 1, 2, ..., 231-2,
231-1. If you try to store larger number than 231-1, i.e,+2147483647 and smaller number than -
231, i.e, -2147483648, program will not run correctly.

Similarly, int of 2 bytes, it can take 216 distinct states from -215 to 215-1.

float - Floating types

Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc. You can declare a
floating point variable in C by using either float or double keyword. For example:

float accountBalance;

double bookPrice;

Here, both accountBalance and bookPrice are floating type variables.

In C, floating values can be represented in exponential form as well. For example:

float normalizationFactor = 22.442e2;


Difference between float and double

The size of float (single precision float data type) is 4 bytes. And the size of double (double
precision float data type) is 8 bytes. Floating point variables has a precision of 6 digits whereas
the precision of double is 14 digits.

char - Character types

Keyword char is used for declaring character type variables. For example:

char test = 'h';

Here, test is a character variable. The value of test is 'h'.

The size of character variable is 1 byte.

C Qualifiers

Qualifiers alters the meaning of base data types to yield a new data type.

Size qualifiers

Size qualifiers alters the size of a basic type. There are two size qualifiers, long and short. For
example:

long double i;

The size of double is 8 bytes. However, when long keyword is used, that variable becomes 10
bytes.

There is another keyword short which can be used if you previously know the value of a variable
will always be a small number.

Sign qualifiers

Integers and floating point variables can hold both negative and positive values. However, if a
variable needs to hold positive value only, unsigned data types are used. For example:

// unsigned variables cannot hold negative value

unsigned int positiveInteger;


There is another qualifier signed which can hold both negative and positive only. However, it is
not necessary to define variable signed since a variable is signed by default.

An integer variable of 4 bytes can hold data from -231 to 231-1. However, if the variable is
defined as unsigned, it can hold data from 0 to 232-1.

It is important to note that, sign qualifiers can be applied to int and char types only.

Constant qualifiers

An identifier can be declared as a constant. To do so const keyword is used.

const int cost = 20;

The value of cost cannot be changed in the program.

Volatile qualifiers

A variable should be declared volatile whenever its value can be changed by some external
sources outside the program. Keyword volatile is used for creating volatile variables.

C Input Output (I/O)

C programming has several in-built library functions to perform input and output tasks.

Two commonly used functions for I/O (Input/Output) are printf() and scanf().

The scanf() function reads formatted input from standard input (keyboard) whereas
the printf() function sends formatted output to the standard output (screen).

Example #1: C Output


#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}

Output

C Programming
How this program works?

All valid C program must contain the main() function. The code execution begins from
the start of main() function.
The printf() is a library function to send formatted output to the screen.
The printf()function is declared in "stdio.h" header file.
Here, stdio.h is a header file (standard input output header file) and #include is a
preprocessor directive to paste the code from the header file when necessary. When the
compiler encounters printf() function and doesn't find stdio.h header file, compiler shows
error.
The return 0; statement is the "Exit status" of the program. In simple terms, program
ends.

Example #2: C Integer Output


#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}

Output

Number = 5

Inside the quotation of printf() function, there is a format string "%d" (for integer). If the format
string matches the argument (testInteger in this case), it is displayed on the screen.

Example #3: C Integer Input/Output


#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d",&testInteger);
printf("Number = %d",testInteger);
return 0;
}
Output

Enter an integer: 4

Number = 4

The scanf() function reads formatted input from the keyboard. When user enters an integer, it is
stored in variable testInteger.

Note the '&' sign before testInteger; &testInteger gets the address of testInteger and the value is
stored in that address.

Example #3: C Floats Input/Output


#include <stdio.h>
int main()
{
float f;
printf("Enter a number: ");
// %f format string is used in case of floats
scanf("%f",&f);
printf("Value = %f", f);
return 0;
}

Output

Enter a number: 23.45

Value = 23.450000

The format string "%f" is used to read and display formatted in case of floats.

Example #4: C Character I/O


#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.",chr);
return 0;
}

Output

Enter a character: g

You entered g.

Format string %c is used in case of character types.

Little bit on ASCII code

When a character is entered in the above program, the character itself is not stored. Instead, a
numeric value(ASCII value) is stored.

And when we displayed that value using "%c" text format, the entered character is displayed.

Example #5: C ASCII Code


#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);

// When %c text format is used, character is displayed in case of character types


printf("You entered %c.\n",chr);

// When %d text format is used, integer is displayed in case of character types


printf("ASCII value of %c is %d.", chr, chr);
return 0;
}
Output

Enter a character: g

You entered g.

ASCII value of g is 103.

The ASCII value of character 'g' is 103. When, 'g' is entered, 103 is stored in variable var1
instead of g.

You can display a character if you know ASCII code of that character. This is shown by
following example.

Example #6: C ASCII Code


#include <stdio.h>
int main()
{
int chr = 69;
printf("Character having ASCII value 69 is %c.",chr);
return 0;
}

Output

Character having ASCII value 69 is E.

More on Input/Output of floats and Integers

Integer and floats can be displayed in different formats in C programming.

Example #7: I/O of Floats and Integers


#include <stdio.h>
int main()
{

int integer = 9876;


float decimal = 987.6543;

// Prints the number right justified within 6 columns


printf("4 digit integer right justified to 6 column: %6d\n", integer);

// Tries to print number right justified to 3 digits but the number is not right adjusted because
there are only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);

// Rounds to two digit places


printf("Floating point number rounded to 2 digits: %.2f\n",decimal);

// Rounds to 0 digit places


printf("Floating point number rounded to 0 digits: %.f\n",987.6543);

// Prints the number in exponential notation(scientific notation)


printf("Floating point number in exponential form: %e\n",987.6543);
return 0;
}

Output

4 digit integer right justified to 6 column: 9876

4 digit integer right justified to 3 column: 9876

Floating point number rounded to 2 digits: 987.65

Floating point number rounded to 0 digits: 988

Floating point number in exponential form: 9.876543e+02

C Programming Operators
An operator is a symbol which operates on a value or a variable. For example: + is an operator to
perform addition.

C programming has wide range of operators to perform various operations. For better
understanding of operators, these operators can be classified as:

Operators in C programming

Arithmetic Operators

Increment and Decrement Operators

Assignment Operators

Relational Operators

Logical Operators

Conditional Operators

Bitwise Operators

Special Operators

C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition, subtraction and


multiplication on numerical values (constants and variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division
Operator Meaning of Operator

% remainder after division( modulo division)

Example #1: Arithmetic Operators


// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);

c = a-b;
printf("a-b = %d \n",c);

c = a*b;
printf("a*b = %d \n",c);

c=a/b;
printf("a/b = %d \n",c);

c=a%b;
printf("Remainder when a divided by b = %d \n",c);

return 0;
}

Output

a+b = 13

a-b = 5
a*b = 36

a/b = 2

Remainder when a divided by b=1

The operators +, - and * computes addition, subtraction and multiplication respectively as you
might have expected.

In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.

It is because both variables a and b are integers. Hence, the output is also an integer. The
compiler neglects the term after decimal point and shows answer 2 instead of 2.25.

The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder
is 1. The % operator can only be used with integers.

Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,

a/b = 2.5 // Because both operands are floating-point variables

a/d = 2.5 // Because one operand is floating-point variable

c/b = 2.5 // Because one operand is floating-point variable

c/d = 2 // Because both operands are integers

Increment and decrement operators

C programming has two operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.

Example #2: Increment and Decrement Operators


// C Program to demonstrate the working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);

printf("--b = %d \n", --b);

printf("++c = %f \n", ++c);

printf("--d = %f \n", --d);

return 0;
}

Output

++a = 11

--b = 99

++c = 11.500000

++d = 99.500000

Here, the operators ++ and -- are used as prefix. These two operators can also be used as postfix
like a++ and a--. Visit this page to learn more on how increment and decrement operators work
when used as postfix.

C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =
Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Example #3: Assignment Operators


// C Program to demonstrate the working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;

c = a;
printf("c = %d \n", c);

c += a; // c = c+a
printf("c = %d \n", c);

c -= a; // c = c-a
printf("c = %d \n", c);

c *= a; // c = c*a
printf("c = %d \n", c);

c /= a; // c = c/a
printf("c = %d \n", c);

c %= a; // c = c%a
printf("c = %d \n", c);

return 0;
}

Output

c=5

c = 10

c=5

c = 25

c=5

c=0

C Relational Operators

A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1

< Less than 5 < 3 returns 0


Operator Meaning of Operator Example

!= Not equal to 5 != 3 returns 1

>= Greater than or equal to 5 >= 3 returns 1

<= Less than or equal to 5 <= 3 return 0

Example #4: Relational Operators


// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d = %d \n", a, b, a == b); // true


printf("%d == %d = %d \n", a, c, a == c); // false

printf("%d > %d = %d \n", a, b, a > b); //false


printf("%d > %d = %d \n", a, c, a > c); //false

printf("%d < %d = %d \n", a, b, a < b); //false


printf("%d < %d = %d \n", a, c, a < c); //true

printf("%d != %d = %d \n", a, b, a != b); //false


printf("%d != %d = %d \n", a, c, a != c); //true

printf("%d >= %d = %d \n", a, b, a >= b); //true


printf("%d >= %d = %d \n", a, c, a >= c); //false
printf("%d <= %d = %d \n", a, b, a <= b); //true
printf("%d <= %d = %d \n", a, c, a <= c); //true

return 0;

Output

5 == 5 = 1

5 == 10 = 0

5>5=0

5 > 10 = 0

5<5=0

5 < 10 = 1

5 != 5 = 0

5 != 10 = 1

5 >= 5 = 1

5 >= 10 = 0

5 <= 5 = 1

5 <= 10 = 1

C Logical Operators

An expression containing logical operator returns either 0 or 1 depending upon whether


expression results true or false. Logical operators are commonly used in decision making in C
programming.
Operator Meaning of Operator Example

Logial AND. True only if all If c = 5 and d = 2 then, expression ((c == 5)


&&
operands are true && (d > 5)) equals to 0.

Logical OR. True only if either If c = 5 and d = 2 then, expression ((c == 5) ||


||
one operand is true (d > 5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression ! (c == 5) equals to


!
operand is 0 0.

Example #5: Logical Operators


// C Program to demonstrate the working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) equals to %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) equals to %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) equals to %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) equals to %d \n", result);

result = !(a != b);


printf("!(a == b) equals to %d \n", result);

result = !(a == b);


printf("!(a == b) equals to %d \n", result);

return 0;
}

Output

(a == b) && (c > b) equals to 1

(a == b) && (c < b) equals to 0

(a == b) || (c < b) equals to 1

(a != b) || (c < b) equals to 0

!(a != b) equals to 1

!(a == b) equals to 0

Explanation of logical operator program

(a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).


(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

Bitwise Operators

During computation, mathematical operations like: addition, subtraction, addition and division
are converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR
Operators Meaning of operators

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Other Operators
Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

The sizeof operator

The sizeof is an unary operator which returns the size of data (constant, variables, array, structure
etc).

Example #6: sizeof Operator


#include <stdio.h>
int main()
{
int a, e[10];
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
printf("Size of integer type array having 10 elements = %lu bytes\n", sizeof(e));
return 0;
}

Output

Size of int = 4 bytes

Size of float = 4 bytes

Size of double = 8 bytes

Size of char = 1 byte

Size of integer type array having 10 elements = 40 bytes

C Ternary Operator (?:)

A conditional operator is a ternary operator, that is, it works on 3 operands.

Conditional Operator Syntax

conditionalExpression ? expression1 : expression2

The conditional operator works as follows:

The first expression conditionalExpression is evaluated first. This expression evaluates to


1 if it's true and evaluates to 0 if it's false.
If conditionalExpression is true, expression1 is evaluated.
If conditionalExpression is false, expression2 is evaluated.

Example #7: C conditional Operator


#include <stdio.h>
int main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);

// If test condition (February == 'l') is true, days equal to 29.


// If test condition (February =='l') is false, days equal to 28.
days = (February == '1') ? 29 : 28;

printf("Number of days in February = %d",days);


return 0;
}

Output

If this year is leap year, enter 1. If not enter any integer: 1

Number of days in February = 29

C Programming Functions

A function is a block of code that performs a specific task.

Suppose, a program related to graphics needs to create a circle and color it depending upon the
radius and color from the user. You can create two functions to solve this problem:

create a circle function


color function

Dividing complex problem into small components makes program easy to understand and use.

Types of functions in C programming

Depending on whether a function is defined by the user or already included in C compilers, there
are two types of functions in C programming

There are two types of functions in C programming:

Standard library functions


User defined functions

Standard library functions

The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling etc.

These functions are defined in the header file. When you include the header file, these functions
are available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display output
on the screen). This function is defined in "stdio.h" header file.

There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions
are available for use.

Visit this page to learn more about standard library functions in C programming.

User-defined functions

As mentioned earlier, C allow programmers to define functions. Such functions created by the
user are called user-defined functions.

Depending upon the complexity and requirement of the program, you can create as many user-
defined functions as you want.

How user-defined function works?

#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}

int main()
{
... .. ...
... .. ...

functionName();

... .. ...
... .. ...
}

The execution of a C program begins from the main() function.

When the compiler encounters functionName(); inside the main function, control of the program
jumps to

void functionName()

And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside
the function definition are executed.

Remember, function name is an identifier and should be unique.

This is just an overview on user-defined function. Visit these pages to learn more on:

User-defined Function in C programming


Types of user-defined Functions

Advantages of user-defined function

1. The program will be easier to understand, maintain and debug.


2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.

C Programming User-defined functions


A function is a block of code that performs a specific task.

C allows you to define functions according to your need. These functions are known as user-
defined functions. For example:

Suppose, you need to create a circle and color it depending upon the radius and color. You can
create two functions to solve this problem:

createCircle() function
color() function

Example: User-defined function

Here is a example to add two integers. To perform this task, a user-defined


function addNumbers() is defined.

#include <stdio.h>

int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call

printf("sum = %d",sum);

return 0;
}

int addNumbers(int a,int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

Function prototype

A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body.

A function prototype gives information to the compiler that the function may later be used in the
program.

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2,...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:

1. name of the function is addNumbers()


2. return type of the function is int
3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before
the main() function.

Calling a function

Control of the program is transferred to the user-defined function by calling it

Syntax of function call

functionName(argument1, argument2, ...);

In the above example, function call is made using addNumbers(n1,n2); statement inside
the main().

Function definition

Function definition contains the block of code to perform a specific task i.e. in this case, adding
two numbers and returning it.

Syntax of function definition

returnType functionName(type1 argument1, type2 argument2, ...)


{

//body of the function

When a function is called, the control of the program is transferred to the function definition.
And, the compiler starts executing the codes inside the body of a function.
Passing arguments to a function

In programming, argument refers to the variable passed to the function. In the above example,
two variables n1 and n2 are passed during function call.

The parameters a and b accepts the passed arguments in the function definition. These arguments
are called formal parameters of the function.

The type of arguments passed to a function and the formal parameters must match, otherwise the
compiler throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be
of float type.

A function can also be called without passing an argument.

Return Statement

The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after return statement.

In the above example, the value of variable result is returned to the variable sum in
the main() function.

Syntax of return statement

return (expression);
For example,

return a;

return (a+b);

The type of value returned from the function and the return type specified in function prototype
and function definition must match.

Types of User-defined Functions in C Programming

For better understanding of arguments and return value from the function, user-defined
functions can be categorized as:

Function with no arguments and no return value


Function with no arguments and a return value
Function with arguments and no return value
Function with arguments and a return value.

The 4 programs below check whether an integer entered by the user is a prime number or not.
And, all these programs generate the same output.

Example #1: No arguments passed and no return Value


#include <stdio.h>

void checkPrimeNumber();

int main()
{
checkPrimeNumber(); // no argument is passed to prime()
return 0;
}

// return type of the function is void becuase no value is returned from the function
void checkPrimeNumber()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}

The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not and displays it on the screen.

The empty parentheses in checkPrimeNumber(); statement inside the main() function indicates
that no argument is passed to the function.

The return type of the function is void. Hence, no value is returned from the function.

Example #2: No arguments passed but a return value


#include <stdio.h>
int getInteger();

int main()
{
int n, i, flag = 0;

// no argument is passed to the function


// the value returned from the function is assigned to n
n = getInteger();
for(i=2; i<=n/2; ++i)
{
if(n%i==0){
flag = 1;
break;
}
}

if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);

return 0;
}

// getInteger() function returns integer entered by the user


int getInteger()
{
int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

return n;
}

The empty parentheses in n = getInteger(); statement indicates that no argument is passed to the
function. And, the value returned from the function is assigned to n.

Here, the getInteger() function takes input from the user and returns it. The code to check
whether a number is prime or not is inside the main() function.

Example #3: Argument passed but no return value


#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main()
{
int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the function


checkPrimeAndDisplay(n);

return 0;
}

// void indicates that no value is returned from the function


void checkPrimeAndDisplay(int n)
{
int i, flag = 0;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}

The integer value entered by the user is passed to checkPrimeAndDisplay() function.

Here, the checkPrimeAndDisplay() function checks whether the argument passed is a prime
number or not and displays the appropriate message.

Example #4: Argument passed and a return value


#include <stdio.h>
int checkPrimeNumber(int n);

int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);

// n is passed to the checkPrimeNumber() function


// the value returned from the function is assigned to flag variable
flag = checkPrimeNumber(n);

if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);

return 0;
}

// integer is returned from the function


int checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */
int i;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
return 1;
}

return 0;
}

The input from the user is passed to checkPrimeNumber() function.

The checkPrimeNumber() function checks whether the passed argument is prime or not. If the
passed argument is a prime number, the function returns 0. If the passed argument is a non-prime
number, the function returns 1. The return value is assigned to flag variable.
Then, the appropriate message is displayed from the main() function.

Which approach is better?

Well, it depends on the problem you are trying to solve. In case of this problem, the last
approach is better.

A function should perform a specific task. The checkPrimeNumber() function doesn't take input
from the user nor it displays the appropriate message. It only checks whether a number is prime
or not, which makes code modular, easy to understand and debug.

C Programming Recursion

A function that calls itself is known as a recursive function. And, this technique is known as
recursion.

How recursion works?

void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}
The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and other doesn't.

Example: Sum of Natural Numbers Using Recursion


Input

#include <stdio.h>

int sum(int n);

int main()

int number, result;

printf("Enter a positive integer: ");

scanf("%d", &number);

result = sum(number);
printf("sum=%d", result);

int sum(int num)

if (num!=0)

return num + sum(num-1); // sum() function calls itself

else

return num;
}

Output

Enter a positive integer:

Initially, the sum() is called from the main() function with number passed as an argument.

Suppose, the value of num is 3 initially. During next function call, 2 is passed to
the sum()function. This process continues until num is equal to 0.

When num is equal to 0, the if condition fails and the else part is executed returning the sum of
integers to the main() function.
Advantages and Disadvantages of Recursion

Recursion makes program elegant and cleaner. All algorithms can be defined recursively which
makes it easier to visualize and prove.

If the speed of the program is vital then, you should avoid using recursion. Recursions use more
memory and are generally slow. Instead, you can use loop.
TURBO C++

C++ Functions

In programming, function refers to a segment that groups code to perform a specific task.

Depending on whether a function is predefined or created by programmer; there are two types of
function:

1. Library Function
2. User-defined Function

Library Function

Library functions are the built-in function in C++ programming.

Programmer can use library function by invoking function directly; they don't need to write it
themselves.

Example 1: Library Function

#include <iostream>

#include <cmath>

using namespace std;

int main()

double number, squareRoot;

cout << "Enter a number: ";

cin >> number;

// sqrt() is a library function to calculate square root

squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;

return 0;

Output

Enter a number: 26

Square root of 26 = 5.09902

In the example above, sqrt() library function is invoked to calculate the square root of a number.

Notice code #include <cmath> in the above program. Here, cmath is a header file. The function
definition of sqrt()(body of that function) is present in the cmath header file.

You can use all functions defined in cmath when you include the content of file cmath in this
program using #include <cmath> .

Every valid C++ program has at least one function, that is, main() function.

User-defined Function

C++ allows programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code is given a
name(identifier).

When the function is invoked from any part of program, it all executes the codes defined in the
body of function.

How user-defined function works in C Programming?


Consider the figure above.

When a program begins running, the system calls the main() function, that is, the system starts
executing codes from main() function.

When control of the program reaches to function_name() inside main(), it moves to void
function_name() and all codes inside void function_name() is executed.

Then, control of the program moves back to the main function where the code after the call to
the function_name() is executed as shown in figure above.

Example 2: User Defined Function

C++ program to add two integers. Make a function add() to add integers and display sum
in main() function.

#include <iostream>

using namespace std;

// Function prototype (declaration)

int add(int, int);

int main()

int num1, num2, sum;


cout<<"Enters two numbers to add: ";

cin >> num1 >> num2;

// Function call

sum = add(num1, num2);

cout << "Sum = " << sum;

return 0;

// Function definition

int add(int a, int b)

int add;

add = a + b;

// Return statement

return add;

Output

Enters two integers: 8

-4

Sum = 4
Function prototype (declaration)

If a user-defined function is defined after main() function, compiler will show error. It is because
compiler is unaware of user-defined function, types of argument passed to function and return
type.

In C++, function prototype is a declaration of function without its body to give compiler
information about user-defined function. Function prototype in the above example is:

int add(int, int);

You can see that, there is no body of function in prototype. Also, there are only return type of
arguments but no arguments. You can also declare function prototype as below but it's not
necessary to write arguments.

int add(int a, int b);

Note: It is not necessary to define prototype if user-defined function exists


before main()function.

Function Call

To execute the codes of function body, the user-defined function needs to be invoked(called).

In the above program, add(num1,num2); inside main() function calls the user-defined function.

The function returns an integer which is stored in variable add.

Function Definition

The function itself is referred as function definition. Function definition in the above program is:

// Function definition

int add(int a,int b)

{
int add;

add = a + b;

return add;

When the function is called, control is transferred to the first statement of the function body.

Then, other statements in function body are executed sequentially.

When all codes inside function definition is executed, control of program moves to the calling
program.

Passing Arguments to Function

In programming, argument (parameter) refers to the data which is passed to a function (function
definition) while calling it.

In the above example, two variables, num1 and num2 are passed to function during function call.
These arguments are known as actual arguments.

The value of num1 and num2 are initialized to variables a and b respectively. These
arguments a and b are called formal arguments.

This is demonstrated in figure below:


Notes on passing arguments

The numbers of actual arguments and formals argument should be the same.
(Exception: Function Overloading)
The type of first actual argument should match the type of first formal argument.
Similarly, type of second actual argument should match the type of second formal
argument and so on.
You may call function a without passing any argument. The number(s) of argument
passed to a function depends on how programmer want to solve the problem.
You may assign default values to the argument. These arguments are known as default
arguments.
In the above program, both arguments are of int type. But it's not necessary to have both
arguments of same type.

Return Statement

A function can return a single value to the calling program using return statement.

In the above program, the value of add is returned from user-defined function to the calling
program using statement below:

return add;

The figure below demonstrates the working of return statement.


In the above program, the value of add inside user-defined function is returned to the calling
function. The value is then stored to a variable sum.

Notice that the variable returned, i.e., add is of type int and sum is also of int type.

Also, notice that the return type of a function is defined in function declarator int add(int a, int
b). The int before add(int a, int b) means the function should return a value of type int.

If no value is returned to the calling function then, void should be used.

Types of User-defined Functions in C++

For better understanding of arguments and return in functions, user-defined functions can be
categorised as:

Function with no argument and no return value


Function with no argument but return value
Function with argument but no return value
Function with argument and return value

Consider a situation in which you have to check prime number. This problem is solved below by
making user-defined function in 4 different ways as mentioned above.

Example 1: No arguments passed and no return value


# include <iostream>
using namespace std;

void prime();
int main()
{
// No argument is passed to prime()
prime();
return 0;
}

// Return type of function is void because value is not returned.


void prime()
{

int num, i, flag = 0;

cout << "Enter a positive integer enter to check: ";


cin >> num;

for(i = 2; i <= num/2; ++i)


{
if(num % i == 0)
{
flag = 1;
break;
}
}

if (flag == 1)
{
cout << num << " is not a prime number.";
}
else
{
cout << num << " is a prime number.";
}
}

In the above program, prime() is called from the main() with no arguments.

prime() takes the positive number from the user and checks whether the number is a prime
number or not.

Since, return type of prime() is void, no value is returned from the function.

Example 2: No arguments passed but a return value


#include <iostream>
using namespace std;

int prime();

int main()
{
int num, i, flag = 0;

// No argument is passed to prime()


num = prime();
for (i = 2; i <= num/2; ++i)
{
if (num%i == 0)
{
flag = 1;
break;
}
}

if (flag == 1)
{
cout<<num<<" is not a prime number.";
}
else
{
cout<<num<<" is a prime number.";
}
return 0;
}

// Return type of function is int


int prime()
{
int n;

printf("Enter a positive integer to check: ");


cin >> n;

return n;
}

In the above program, prime() function is called from the main() with no arguments.

prime() takes a positive integer from the user. Since, return type of the function is an int, it
returns the inputted number from the user back to the calling main() function.

Then, whether the number is prime or not is checked in the main() itself and printed onto the
screen.

Example 3: Arguments passed but no return value


#include <iostream>
using namespace std;

void prime(int n);

int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;

// Argument num is passed to the function prime()


prime(num);
return 0;
}

// There is no return value to calling function. Hence, return type of function is void. */
void prime(int n)
{
int i, flag = 0;
for (i = 2; i <= n/2; ++i)
{
if (n%i == 0)
{
flag = 1;
break;
}
}

if (flag == 1)
{
cout << n << " is not a prime number.";
}
else {
cout << n << " is a prime number.";
}
}

In the above program, positive number is first asked from the user which is stored in the
variable num.
Then, num is passed to the prime() function where, whether the number is prime or not is
checked and printed.

Since, the return type of prime() is a void, no value is returned from the function.

Example 4: Arguments passed and a return value.


#include <iostream>
using namespace std;

int prime(int n);

int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;

// Argument num is passed to check() function


flag = prime(num);

if(flag == 1)
cout << num << " is not a prime number.";
else
cout<< num << " is a prime number.";
return 0;
}

/* This function returns integer value. */


int prime(int n)
{
int i;
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0)
return 1;
}

return 0;
}

In the above program, a positive integer is asked from the user and stored in the variable num.

Then, num is passed to the function prime() where, whether the number is prime or not is
checked.

Since, the return type of prime() is an int, 1 or 0 is returned to the main() calling function. If the
number is a prime number, 1 is returned. If not, 0 is returned.

Back in the main() function, the returned 1 or 0 is stored in the variable flag, and the
corresponding text is printed onto the screen.

C++ Function Overloading

Function refers to a segment that groups code to perform a specific task.

In C++ programming, two functions can have same name if number and/or type of arguments
passed are different.

These functions having different number or type (or both) of parameters are known as
overloaded functions. For example:

int test() { }

int test(int a) { }

float test(double a) { }

int test(int a, double b) { }

Here, all 4 functions are overloaded functions because argument(s) passed to these functions are
different.

Notice that, the return type of all these 4 functions are not same. Overloaded functions may or
may not have different return type but it should have different argument(s).
// Error code

int test(int a) { }

double test(int b){ }

The number and type of arguments passed to these two functions are same even though the
return type is different. Hence, the compiler will throw error.

Example 1: Function Overloading


#include <iostream>
using namespace std;

void display(int);
void display(float);
void display(int, float);

int main() {

int a = 5;
float b = 5.5;

display(a);
display(b);
display(a, b);

return 0;
}

void display(int var) {


cout << "Integer number: " << var << endl;
}
void display(float var) {
cout << "Float number: " << var << endl;
}

void display(int var1, float var2) {


cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}

Output

Integer number: 5

Float number: 5.5

Integer number: 5 and float number: 5.5

Here, the display() function is called three times with different type or number of arguments.

The return type of all these functions are same but it's not necessary.

Example 2: Function Overloading


// Program to compute absolute value
// Works both for integer and float

#include <iostream>
using namespace std;

int absolute(int);
float absolute(float);

int main() {
int a = -5;
float b = 5.5;
cout << "Absolute value of " << a << " = " << absolute(a) << endl;
cout << "Absolute value of " << b << " = " << absolute(b);
return 0;
}

int absolute(int var) {


if (var < 0)
var = -var;
return var;
}

float absolute(float var){


if (var < 0.0)
var = -var;
return var;
}

Output

Absolute value of -5 = 5

Absolute value of 5.5 = 5.5

In the above example, two functions absolute() are overloaded.

Both functions take single argument. However, one function takes integer as an argument and
other takes float as an argument.

When absolute() function is called with integer as an argument, this function is called:

int absolute(int var) {


if (var < 0)
var = -var;
return var;
}
When absolute() function is called with float as an argument, this function is called:

float absolute(float var){


if (var < 0.0)
var = -var;
return var;

C++ Programming Default Arguments (Parameters)

In C++ programming, you can provide default values for function parameters.

The idea behind default argument is simple. If a function is called by passing argument/s, those
arguments are used by the function.

But if the argument/s are not passed while invoking a function then, the default values are used.

Default value/s are passed to argument/s in the function prototype.

Working of default arguments


Example: Default Argument

// C++ Program to demonstrate working of default argument

#include <iostream>

using namespace std;

void display(char = '*', int = 1);

int main()

cout << "No argument passed:\n";

display();

cout << "\nFirst argument passed:\n";

display('#');
cout << "\nBoth argument passed:\n";

display('$', 5);

return 0;

void display(char c, int n)

for(int i = 1; i <= n; ++i)

cout << c;

cout << endl;

Output

No argument passed:

First argument passed:

Both argument passed:


$$$$$

In the above program, you can see the default value assigned to the arguments void display(char
= '*', int = 1);.

At first, display() function is called without passing any arguments. In this


case, display()function used both default arguments c = * and n = 1.

Then, only the first argument is passed using the function second time. In this case, function does
not use first default value passed. It uses the actual parameter passed as the first argument c =
# and takes default value n = 1 as its second argument.

When display() is invoked for the third time passing both arguments, default arguments are not
used. So, the value of c = $ and n = 5.

Common mistakes when using Default argument

1. void add(int a, int b = 3, int c, int d = 4);

The above function will not compile. You cannot miss a default argument in between two
arguments.
In this case, c should also be assigned a default value.

2. void add(int a, int b = 3, int c, int d);

The above function will not compile as well. You must provide default values for each
argument after b.
In this case, c and d should also be assigned default values.
If you want a single default argument, make sure the argument is the last one. void
add(int a, int b, int c, int d = 4);

3. No matter how you use default arguments, a function should always be written so that it
serves only one purpose.
If your function does more than one thing or the logic seems too complicated, you can
use Function overloading to separate the logic better.

C++ Storage Class

Every variable in C++ has two features: type and storage class.

Type specifies the type of data that can be stored in a variable. For example: int, float, char etc.

And, storage class controls two different properties of a variable: lifetime (determines how long
a variable can exist) and scope (determines which part of the program can access it).
Depending upon the storage class of a variable, it can be divided into 4 major types:

Local variable
Global variable
Static local variable
Register Variable
Thread Local Storage

Local Variable

A variable defined inside a function (defined inside function body between braces) is called a
local variable or automatic variable.

Its scope is only limited to the function where it is defined. In simple terms, local variable exists
and can be accessed only inside a function.

The life of a local variable ends (It is destroyed) when the function exits.

Example 1: Local variable


#include <iostream>
using namespace std;

void test();

int main()
{
// local variable to main()
int var = 5;

test();

// illegal: var1 not declared inside main()


var1 = 9;
}

void test()
{
// local variable to test()
int var1;
var1 = 6;

// illegal: var not declared inside test()


cout << var;
}

The variable var cannot be used inside test() and var1 cannot be used inside main()function.

Keyword auto was also used for defining local variables before as: auto int var;

But, after C++11 auto has a different meaning and should not be used for defining local
variables.

Global Variable

If a variable is defined outside all functions, then it is called a global variable.

The scope of a global variable is the whole program. This means, It can be used and changed at
any part of the program after its declaration.

Likewise, its life ends only when the program ends.

Example 2: Global variable


#include <iostream>
using namespace std;

// Global variable declaration


int c = 12;

void test();

int main()
{
++c;

// Outputs 13
cout << c <<endl;
test();

return 0;
}

void test()
{
++c;

// Outputs 14
cout << c;
}

Output

13

14

In the above program, c is a global variable.

This variable is visible to both functions main() and test() in the above program.

Static Local variable

Keyword static is used for specifying a static variable. For example:

... .. ...

int main()
{

static float a;

... .. ...

A static local variable exists only inside a function where it is declared (similar to a local
variable) but its lifetime starts when the function is called and ends only when the program ends.

The main difference between local variable and static variable is that, the value of static variable
persists the end of the program.

Example 3: Static local variable


#include <iostream>
using namespace std;

void test()
{
// var is a static variable
static int var = 0;
++var;

cout << var << endl;


}

int main()
{

test();
test();

return 0;
}

Output

In the above program, test() function is invoked 2 times.

During the first call, variable var is declared as static variable and initialized to 0. Then 1 is
added to var which is displayed in the screen.

When the function test() returns, variable var still exists because it is a static variable.

During second function call, no new variable var is created. The same var is increased by 1 and
then displayed to the screen.

Output of above program if var was not specified as static variable

Register Variable (Deprecated in C++11)

Keyword register is used for specifying register variables.

Register variables are similar to automatic variables and exists inside a particular function only.
It is supposed to be faster than the local variables.

If a program encounters a register variable, it stores the variable in processor's register rather
than memory if available. This makes it faster than the local variables.

However, this keyword was deprecated in C++11 and should not be used.
Thread Local Storage

Thread-local storage is a mechanism by which variables are allocated such that there is one
instance of the variable per extant thread.

Keyword thread_local is used for this purpose.

Global data, while usually considered poor design, nevertheless often is a useful means to
preserve state between related function calls. When it comes to using threads, the issue
unfortuantely is complicated by the fact that some access synchronisation is needed, to avoid that
more than one thread will modify the data.

There are times when you will want to have a globally visible object, while still having the data
content accessible only to the calling thread, without holding off other threads that contend for
the "same" global object. This is where thread local storage (TLS) comes in. TLS is something
the operating system / threading subsystem provides, and by its very nature is rather low level.

From a globally visible object (in C++) you expect that its constructors are getting called before
you enter "main", and that it is disposed properly, after you exit from "main". Consequently one
would expect a thread local "global" object beeing constructed, when a thread starts up, and
beeing destroyed when the thread exits. But this is not the case! Using the native API one can
only have TLS that needs neither code to construct nor code to destruct.

While at first glance this is somewhat disappointing, there are reasons, not to automatically
instantiate all these objects on every thread creation. A clean solution to this problem is
presented e.g. in the "boost" library. Also the standard "pthread" C library addresses this problem
properly. But when you need to use the native windows threading API, or need to write a library
that, while making use of TLS, has no control over the threading API the client code is using,
you are apparently lost.

Fortunately this is not true, and this is the topic of this article. The Windows Portable Executable
(PE) format provides for support of TLS-Callbacks. Altough the documentation is hard to read,
it can be done with current compilers i.e. MSVC 6.0,7.1,... Since noone else seemingly was using
this feature before, and not even the C runtime library (CRT) is making use of it, you should be a
little careful and watch out for undesired behaviour. Having said, that the CRT does not use it,
does not mean it does not implement it. Unfortunately there is a small bug present in the MSVC
6.0 implementation, that is also worked-around by my code.

If it turns out, that the concepts, presented in this article, prove to be workable in "real life", I
would be glad if this article has helped to remove some dust from this topic and make it usable
for a broader range of applications. I could e.g. think of a generalized atexit_thread function that
makes use of the concepts presented here.

Before going to explain the gory details, I want to mention Aaron W. LaFramboise who made
me aware of the existence of the TLS-Callback mechanism.

If you are using the precompiled binaries, you simply will need to copy the *.lib files to a
convenient directory where your compiler usually will find libraries. So you will copy the files
from the include directory to a directory where your compiler searches for includes.
Alternatively you may simply copy the files to your project directory.
The following is a simple demonstration of usage, to get you started.

#include <process.h>
// first include the header file
#include <tls.h>

// this is your class


struct A {
A() : n(42) {
}
~A() {
}
int the_answer_is() {
int m = n;
n = 0;
return m;
}
int n;
};

// now define a tls wrapper of class A


tls_ptr<A> pA;

// this is the threaded procedure


void run(void*)
{
// instantiate a new "A"
pA.reset(new A);

// access the tls-object


ans = pA->the_answer_is();

// note, that we do not need to deallocate


// the object. This is getting done automagically
// when the thread exits.
}

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


{
// the main thread also gets a local copy of the tls.
pA.reset(new A);

// start the thread


_beginthread(&run, 0, 0);

// call into the main threads version


pA->the_answer_is();

// the "run" thread should have ended when we


// are exiting.
Sleep(10000);
// again we do not need to free our tls object.
// this is comparable in behaviour to objects
// at global scope.
return 0;
}

While at first glance it might appear natural that the tls-objects should not be wrapped as
pointers, in fact it is not. While the objects are globally visible, they are still "delegates" that
forward to a thread local copy. The natural way in C++ to express delegation is a pointer object.
(The technical reason of course is, that you cannot overload the "." operator but "->" can be
overloaded.)

You can use this mechanism when building a "*.exe" file of course, but you also can use it when
building a "*.dll" image. However when you are planning to load your DLL
by LoadLibary() you should define the macro TLS_ALLOC when building your DLL. This is
not necessary when using your DLL by means of an import library. A similar restriction applies
when delay-loading your DLL. Please consult your compiler documentation when you are
interested in the reasons for this. (Defining TLS_ALLOC forces the use of the TlsAlloc() family
functions from the Win32 API.)

The complete API is kept very simple:

tls_ptr<A> pA; // declare an object of class A


pA.reset(new A); // create a tls of class A when needed
pA.reset(new A(45)); // create a tls of class A with a custom constructor
// note, that this also deletes any prior objects
// that might have been allocated to pA
pA.release(); // same as pA.reset(0), releases the thread local <BR> // object
A& refA = *pA; // get a temporary reference to the contained object<BR> //
for faster access
pA->the_answer_is(); // access the object

Please again note, that it is not necessary to explicitely call the destructors of your class
(or release()). This is very handy, when you are writing a piece of code, that has no control over
the calling threads, but must still be multithread safe. One caveat however: The destructors of
your class are called _after_ the CRT code has ended the thread. Consequently when you are
doing something fancy in your destructors, which causes the CRT to reallocate its internal thread
local storage pointers, you will be left with a small memory leak of the CRT. This is comparable
in effect to the case when you are using the native Win32 API functions to create a thread,
instead of _beginthread().

In principle that is all you need. But wait! I mentioned a small bug in the version 6 of the
compiler. Luckily it is easy to work around. I provided an include file tlsfix.h which you will
need to include into your program. You need to make sure it is getting included
before windows.h. To be more precise: the TLS library must be searched before the default CRT
library. So you alternatively may specify the library on the command line on the first place, and
omit the inclusion of tlsfix.h.

Background
I will not discuss the user interface in this place. It suffices to say, that it essentialy is the same as
in the boost library. However I omitted the feature of beeing able to specify arbitrary deleter
functions, since this would have raised the need to include the boost library in my code. I wanted
to keep it small and just demonstrate the principles. However, my implementation also deviates
from boost insofar as I am featuring native compiler support for TLS variables, thus gaining an
almost 4 times speed improvement. No need to say, that my implementation of course is
Windows specific.

When thinking about TLS for C++ the main question is how to run the constructors and
destructors. A careful study of the PE format (e.g. in the MSDN library) reveals, that it almost
ever provided for TLS support. (Thanks again to Aaron W. LaFramboise who read it carefully
enough.) Of special interest is the section about TLS-Callback:

The program can provide one or more TLS callback functions (though Microsoft
compilers do not currently use this feature) to support additional
initialization and termination for TLS data objects. A typical reason to use
such a callback function would be to call constructors and destructors for
objects.

Well it is true, that the compilers do not use the feature, but there is nothing that prevents user
code to use it though. One somehow must convince the compiler (to be honest it is the linker) to
place your callback in a manner, so the operating system will call it. It turns out, that this is
surprisingly simple (omitting the deatils for a moment).

// declare your callback


void NTAPI on_tls_callback(PVOID h, DWORD dwReason, PVOID pv)
{
if( DLL_THREAD_DETACH == dwReason )
basic_tls::thread_term();
}

// put a pointer in a special segment


#pragma data_seg(".CRT$XLB")
PIMAGE_TLS_CALLBACK p_thread_callback = on_tls_callback;
#pragma data_seg()

You can even add more callbacks, by appending pointers to the ".CRT$XLB" segment. The
fancy definitions are available from the windows.h and winnt.h include files in turn.

Now about the details: You will find at times, that your callbacks are not getting called. The
reason for this is when the linker does not correctly wire up your segments. It turns out, that this
coincides with when you are not using any __declspec(thread) in your code. A further study of
the PE format description reveals:

The Microsoft run-time library facilitates this process by defining a memory image of the TLS
Directory and giving it the special name __tls_used (Intel x86 platforms) or _tls_used
(other platforms). The linker looks for this memory image and uses the data there to create the
TLS Directory. Other compilers that support TLS and work with the Microsoft linker must use
this same technique.
C++ Recursion

A function that calls itself is known as recursive function. And, this technique is known as
recursion.

How recursion works in C++?

void recurse()

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();

... .. ...

The figure below shows how recursion works by calling itself over and over again.
The recursion continues until some condition is met.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and other doesn't.

Example 1: Factorial of a Number Using Recursion

// Factorial of n = 1*2*3*...*n

#include <iostream>

using namespace std;

int factorial(int);

int main()

{
int n;

cout<<"Enter a number to find factorial: ";

cin >> n;

cout << "Factorial of " << n <<" = " << factorial(n);

return 0;

int factorial(int n)

if (n > 1)

return n*factorial(n-1);

else

return 1;

Output

Enter a number to find factorial: 4

Factorial of 4 = 24
Explanation: How this example works?

Suppose the user entered 4, which is passed to the factorial() function.

1. In the first factorial() function, test expression inside if statement is true. The return
num*factorial(num-1); statement is executed, which calls the second factorial() function
and argument passed is num-1which is 3.

2. In the second factorial() function, test expression inside if statement is true. The return
num*factorial(num-1); statement is executed, which calls the third factorial()function and
argument passed is num-1 which is 2.

3. In the third factorial() function, test expression inside if statement is true. The return
num*factorial(num-1); statement is executed, which calls the fourth factorial() function
and argument passed is num-1 which is 1.

4. In the fourth factorial() function, test expression inside if statement is false. The return
1; statement is executed, which returns 1 to third factorial() function.
5. The third factorial() function returns 2 to the second factorial() function.

6. The second factorial() function returns 6 to the first factorial() function.

7. Finally, the first factorial() function returns 24 to the main() function, which is displayed
on the screen.

C++ Structures

Structure is a collection of variables of different data types under a single name. It is similar to
a class in that, both holds a collecion of data of different data types.

For example: You want to store some information about a person: his/her name, citizenship
number and salary. You can easily create different variables name, citNo, salary to store these
information separately.

However, in the future, you would want to store information about multiple persons. Now, you'd
need to create different variables for each information per person: name1, citNo1, salary1,
name2, citNo2, salary2

You can easily visualize how big and messy the code would look. Also, since no relation
between the variables (information) would exist, it's going to be a daunting task.

A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner, readable and
efficient as well.

This collection of all related information under a single name Person is a structure.

How to declare a structure in C++ programming?

The struct keyword defines a structure type followed by an identifier (name of the structure).

Then inside the curly braces, you can declare one or more members (declare variables inside
curly braces) of that structure. For example:

struct Person

char name[50];

int age;
float salary;

};

Here a structure person is defined which has three members: name, age and salary.

When a structure is created, no memory is allocated.

The structure definition is only the blueprint for the creating of variables. You can imagine it as a
datatype. When you define an integer as below:

int foo;

The int specifies that, variable foo can hold integer element only. Similarly, structure definition
only specifies that, what property a structure variable holds when it is defined.

Note: Remember to end the declaration with a semicolon (;)

How to define a structure variable?

Once you declare a structure person as above. You can define a structure variable as:

Person bill;

Here, a structure variable bill is defined which is of type structure Person.

When structure variable is defined, only then the required memory is allocated by the compiler.

Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes, memory
of int is 4 bytes and memory of char is 1 byte.

Hence, 58 bytes of memory is allocated for structure variable bill.

How to access members of a structure?

The members of structure variable is accessed using a dot (.) operator.


Suppose, you want to access age of structure variable bill and assign it 50 to it. You can perform
this task by using following code below:

bill.age = 50;

Example: C++ Structure

C++ Program to assign data to members of a structure variable and display it.

#include <iostream>
using namespace std;

struct Person
{
char name[50];
int age;
float salary;
};

int main()
{
Person p1;

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}

Output

Enter Full name: Magdalena Dankova

Enter age: 27

Enter salary: 1024.4

Displaying Information.

Name: Magdalena Dankova

Age: 27

Salary: 1024.4

Here a structure Person is declared which has three members name, age and salary.

Inside main() function, a structure variable p1 is defined. Then, the user is asked to enter
information and data entered by user is displayed.

C++ Structure and Function

Structure variables can be passed to a function and returned in a similar way as normal
arguments.

Passing structure to function in C++

A structure variable can be passed to a function in similar way as normal argument. Consider this
example:
Example 1: C++ Structure and Function

#include <iostream>

using namespace std;

struct Person

char name[50];

int age;

float salary;

};

void displayData(Person); // Function declaration

int main()

Person p;

cout << "Enter Full name: ";

cin.get(p.name, 50);

cout << "Enter age: ";

cin >> p.age;

cout << "Enter salary: ";

cin >> p.salary;

// Function call with structure variable as an argument

displayData(p);
return 0;

void displayData(Person p)

cout << "\nDisplaying Information." << endl;

cout << "Name: " << p.name << endl;

cout <<"Age: " << p.age << endl;

cout << "Salary: " << p.salary;

Output

Enter Full name: Bill Jobs

Enter age: 55

Enter salary: 34233.4

Displaying Information.

Name: Bill Jobs

Age: 55

Salary: 34233.4

In this program, user is asked to enter the name, age and salary of a Person
inside main()function.

Then, the structure variable p is to passed to a function using.


displayData(p);

The return type of displayData() is void and a single argument of type structure Person is passed.

Then the members of structure p is displayed from this function.

Example 2: Returning structure from function in C++

#include <iostream>

using namespace std;

struct Person {

char name[50];

int age;

float salary;

};

Person getData(Person);

void displayData(Person);

int main()

Person p;

p = getData(p);

displayData(p);
return 0;

Person getData(Person p) {

cout << "Enter Full name: ";

cin.get(p.name, 50);

cout << "Enter age: ";

cin >> p.age;

cout << "Enter salary: ";

cin >> p.salary;

return p;

void displayData(Person p)

cout << "\nDisplaying Information." << endl;

cout << "Name: " << p.name << endl;

cout <<"Age: " << p.age << endl;

cout << "Salary: " << p.salary;

The output of this program is same as program above.

In this program, the structure variable p of type structure Person is defined under main()function.
The structure variable p is passed to getData() function which takes input from user which is then
returned to main function.

p = getData(p);

Note: The value of all members of a structure variable can be assigned to another structure using
assignment operator = if both structure variables are of same type. You don't need to manually
assign each members.

Then the structure variable p is passed to displayData() function, which displays the information.

C++ Enumeration

An enumeration is a user-defined data type that consists of integral constants. To define an


enumeration, keyword enum is used.

enum season { spring, summer, autumn, winter };

Here, the name of the enumeration is season.

And, spring, summer and winter are values of type season.

By default, spring is 0, summer is 1 and so on. You can change the default value of an enum
element during declaration (if necessary).

enum season

{ spring = 0,

summer = 4,

autumn = 8,

winter = 12

};
Enumerated Type Declaration

When you create an enumerated type, only blueprint for the variable is created. Here's how you
can create variables of enum type.

enum boolean { false, true };

// inside function

enum boolean check;

Here, a variable check of type enum boolean is created.

Here is another way to declare same check variable using different syntax.

enum boolean

false, true

} check;

Example 1: Enumeration Type


#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}

Output

Day 4

Example2: Changing Default Value of Enums


#include <iostream>
using namespace std;

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {

seasons s;

s = summer;
cout << "Summer = " << s << endl;

return 0;
}

Output

Summer = 4

Why enums are used in C++ programming?


An enum variable takes only one value out of many possible values. Example to demonstrate it,

#include <iostream>
using namespace std;

enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;

int main()
{
card = club;
cout << "Size of enum variable " << sizeof(card) << " bytes.";
return 0;
}

Output

Size of enum variable 4 bytes.

It's because the size of an integer is 4 bytes.;

This makes enum a good choice to work with flags.

You can accomplish the same task using C++ structures. However, working with enums gives
you efficiency along with flexibility.

How to use enums for flags?

Let us take an example,

enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
} button;

Suppose you are designing a button for Windows application. You can set
flags ITALICS, BOLD and UNDERLINE to work with text.

There is a reason why all the integral constants are power of 2 in above pseudocode.

// In binary

ITALICS = 00000001

BOLD = 00000010

UNDERLINE = 00000100

Since, the integral constants are power of 2, you can combine two or more flags at once without
overlapping using bitwise OR | operator. This allows you to choose two or more flags at once.
For example,

#include <iostream>
using namespace std;

enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};

int main()
{
int myDesign = BOLD | UNDERLINE;

// 00000001
// | 00000100
// ___________
// 00000101

cout << myDesign;

return 0;
}

Output

When the output is 5, you always know that bold and underline is used.

Also, you can add flag to your requirements.

if (myDesign & ITALICS) {

// code for italics

Here, we have added italics to our design. Note, only code for italics is written inside the if
statement.

You can accomplish almost anything in C++ programming without using enumerations.
However, they can be pretty handy in certain situations. That's what differentiates good
programmers from great programmers.

C++ if, if...else and Nested if...else


Contents

if Statement

if...else Statement

Nested if...else Statement

Conditional Operator

C++ if Statement

if (testExpression)

// statements

The if statement evaluates the test expression inside parenthesis.

If test expression is evaluated to true, statements inside the body of if is executed.

If test expression is evaluated to false, statements inside the body of if is skipped.

How if statement works?


Flowchart of if Statement

Above figure describes the working of an if statement.

Example 1: C++ if Statement


// Program to print positive number entered by the user

// If user enters negative number, it is skipped

#include <iostream>

using namespace std;

int main()

int number;

cout << "Enter an integer: ";

cin >> number;

// checks if the number is positive

if ( number > 0)

cout << "You entered a positive integer: " << number << endl;

cout << "This statement is always executed.";

return 0;

Output 1

Enter an integer: 5

You entered a positive number: 5


This statement is always executed.

Output 2

Enter a number: -5

This statement is always executed.

C++ if...else

The if else executes the codes inside the body of if statement if the test expression is true and
skips the codes inside the body of else.

If the test expression is false, it executes the codes inside the body of else statement and skips the
codes inside the body of if.

How if...else statement works?

Flowchart of if...else
Example 2: C++ if...else Statement
// Program to check whether an integer is positive or negative

// This program considers 0 as positive number

#include <iostream>

using namespace std;

int main()

int number;

cout << "Enter an integer: ";

cin >> number;


if ( number >= 0)

cout << "You entered a positive integer: " << number << endl;

else

cout << "You entered a negative integer: " << number << endl;

cout << "This line is always printed.";

return 0;

Output

Enter an integer: -4

You entered a negative integer: -4.

This line is always printed.

C++ Nested if...else

The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.
Syntax of Nested if...else

if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3
is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}

Example 3: C++ Nested if...else


// Program to check whether an integer is positive, negative or zero

#include <iostream>
using namespace std;

int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;

if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0)
{
cout<<"You entered a negative integer: " << number << endl;
}
else
{
cout << "You entered 0." << endl;
}

cout << "This line is always printed.";


return 0;
}

Output

Enter an integer: 0

You entered 0.

This line is always printed.

Conditional/Ternary Operator ?:

A ternary operator operates on 3 operands which can be used instead of a if...elsestatement.

Consider this code:

if ( a < b ) {

a = b;

else {

a = -b;

You can replace the above code with:

a = (a < b) ? b : -b;

The ternary operator is more readable than a if...else statement for short conditions.

C++ for Loop


Loops are used in programming to repeat a specific block until some end condition is met. There
are three type of loops in C++ programming:

1. for loop
2. while loop
3. do...while loop

C++ for Loop Syntax

for(initializationStatement; testExpression; updateStatement) {

// codes

where, only testExpression is mandatory.

How for loop works?

1. The initialization statement is executed only once at the beginning.


2. Then, the test expression is evaluated.
3. If the test expression is false, for loop is terminated. But if the test expression is true,
codes inside body of for loop is executed and update expression is updated.
4. Again, the test expression is evaluated and this process repeats until the test expression is
false.

Flowchart of for Loop in C++


Example 1: C++ for Loop
// C++ Program to find factorial of a number

// Factorial on n = 1*2*3*...*n

#include <iostream>

using namespace std;

int main()

int i, n, factorial = 1;
cout << "Enter a positive integer: ";

cin >> n;

for (i = 1; i <= n; ++i) {

factorial *= i; // factorial = factorial * i;

cout<< "Factorial of "<<n<<" = "<<factorial;

return 0;

Output

Enter a positive integer: 5

Factorial of 5 = 120

In the program, user is asked to enter a positive integer which is stored in variable n(suppose user
entered 5). Here is the working of for loop:

1. Initially, i is equal to 1, test expression is true, factorial becomes 1.


2. i is updated to 2, test expression is true, factorial becomes 2.
3. i is updated to 3, test expression is true, factorial becomes 6.
4. i is updated to 4, test expression is true, factorial becomes 24.
5. i is updated to 5, test expression is true, factorial becomes 120.
6. i is updated to 6, test expression is false, for loop is terminated.

In the above program, variable i is not used outside of the for loop. In such cases, it is better to
declare the variable in for loop (at initialization statement).
#include <iostream>

using namespace std;

int main()

int n, factorial = 1;

cout << "Enter a positive integer: ";

cin >> n;

for (int i = 1; i <= n; ++i) {

factorial *= i; // factorial = factorial * i;

cout<< "Factorial of "<<n<<" = "<<factorial;

return 0;

}
C++ while and do...while Loop

In computer programming, loop repeats a certain block of code until some end condition is met.

There are 3 type of loops in C++ Programming:

for Loop
while Loop
do...while Loop

C++ while Loop

The syntax of a while loop is:

while (testExpression)

// codes

where, testExpression is checked on each entry of the while loop.

How while loop works?

The while loop evaluates the test expression.


If the test expression is true, codes inside the body of while loop is evaluated.
Then, the test expression is evaluated again. This process goes on until the test expression
is false.
When the test expression is false, while loop is terminated.

Flowchart of while Loop


Example 1: C++ while Loop

// C++ Program to compute factorial of a number

// Factorial of n = 1*2*3...*n

#include <iostream>

using namespace std;

int main()

int number, i = 1, factorial = 1;

cout << "Enter a positive integer: ";

cin >> number;


while ( i <= number) {

factorial *= i; //factorial = factorial * i;

++i;

cout<<"Factorial of "<< number <<" = "<< factorial;

return 0;

Output

Enter a positive integer: 4

Factorial of 4 = 24

In this program, user is asked to enter a positive integer which is stored in variable number. Let's
suppose, user entered 4.

Then, the while loop starts executing the code. Here's how while loop works:

1. Initially, i = 1, test expression i <= number is true and factorial becomes 1.


2. Variable i is updated to 2, test expression is true, factorial becomes 2.
3. Variable i is updated to 3, test expression is true, factorial becomes 6.
4. Variable i is updated to 4, test expression is true, factorial becomes 24.
5. Variable i is updated to 5, test expression is false and while loop is terminated.

C++ do...while Loop

The do...while loop is a variant of the while loop with one important difference. The body of
do...while loop is executed once before the test expression is checked.

The syntax of do..while loop is:

do {
// codes;

while (testExpression);

How do...while loop works?

The codes inside the body of loop is executed at least once. Then, only the test expression
is checked.
If the test expression is true, the body of loop is executed. This process continues until the
test expression becomes false.
When the test expression is false, do...while loop is terminated.

Flowchart of do...while Loop

Example 2: C++ do...while Loop


// C++ program to add numbers until user enters 0

#include <iostream>

using namespace std;

int main()

float number, sum = 0.0;

do {

cout<<"Enter a number: ";

cin>>number;

sum += number;

while(number != 0.0);

cout<<"Total sum = "<<sum;

return 0;

Output

Enter a number: 2

Enter a number: 3

Enter a number: 4

Enter a number: -4

Enter a number: 2

Enter a number: 4.4


Enter a number: 2

Enter a number: 0

C++ break and continue Statement

In C++, there are two statements break; and continue; specifically to alter the normal flow of a
program.

Sometimes, it is desirable to skip the execution of a loop for a certain test condition or terminate
it immediately without checking the condition.

For example: You want to loop through data of all aged people except people aged 65. Or, you
want to find the first person aged 20.

In scenarios like these, continue; or a break; statement is used.

C++ break Statement

The break; statement terminates a loop (for, while and do..while loop) and a switch
statementimmediately when it appears.

Syntax of break

break;

In real practice, break statement is almost always used inside the body of conditional statement
(if...else) inside the loop.

How break statement works?


Example 1: C++ break

C++ program to add all number entered by user until user enters 0.

// C++ Program to demonstrate working of break statement

#include <iostream>

using namespace std;

int main() {

float number, sum = 0.0;

// test expression is always true

while (true)

cout << "Enter a number: ";


cin >> number;

if (number != 0.0)

sum += number;

else

// terminates the loop if number equals 0.0

break;

cout << "Sum = " << sum;

return 0;

Output

Enter a number: 4

Enter a number: 3.4

Enter a number: 6.7

Enter a number: -4.5

Enter a number: 0
Sum = 9.6

In the above program, the test expression is always true.

The user is asked to enter a number which is stored in the variable number. If the user enters any
number other than 0, the number is added to sum and stored to it.

Again, the user is asked to enter another number. When user enters 0, the test expression
inside if statement is false and body of else is executed which terminates the loop.

Finally, the sum is displayed.

C++ continue Statement

It is sometimes necessary to skip a certain test condition within a loop. In such


case, continue; statement is used in C++ programming.

Syntax of continue

continue;

In practice, continue; statement is almost always used inside a conditional statement.


Working of continue Statement

Example 2: C++ continue

C++ program to display integer from 1 to 10 except 6 and 9.

#include <iostream>

using namespace std;

int main()

for (int i = 1; i <= 10; ++i)

if ( i == 6 || i == 9)

{
continue;

cout << i << "\t";

return 0;

Output

1 2 3 4 5 7 8 10

In above program, when i is 6 or 9, execution of statement cout << i << "\t"; is skipped inside the
loop using continue; statement.

C++ switch..case Statement

The ladder if..else..if statement allows you to execute a block code among many alternatives. If
you are checking on the value of a single variable in ladder if..else..if, it is better to
use switch statement.

The switch statement is often faster than if...else (not always). Also, the syntax of switch
statement is cleaner and easier to understand.

C++ switch...case syntax

switch (n)

case constant1:

// code to be executed if n is equal to constant1;

break;
case constant2:

// code to be executed if n is equal to constant2;

break;

default:

// code to be executed if n doesn't match any constant

When a case constant is found that matches the switch expression, control of the program passes
to the block of code associated with that case.

In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute
the block of code associated with the case statement until the end of switch block, or until
the break statement is encountered.

The break statement is used to prevent the code running into the next case.
Flowchart of switch Statement

The above figure shows how a switch statement works and conditions are checked within the
switch case clause.

Example: C++ switch Statement

// Program to built a simple calculator using switch Statement


#include <iostream>

using namespace std;

int main()

char o;

float num1, num2;

cout << "Enter an operator (+, -, *, /): ";

cin >> o;

cout << "Enter two operands: ";

cin >> num1 >> num2;

switch (o)

case '+':

cout << num1 << " + " << num2 << " = " << num1+num2;

break;

case '-':

cout << num1 << " - " << num2 << " = " << num1-num2;

break;

case '*':

cout << num1 << " * " << num2 << " = " << num1*num2;

break;

case '/':
cout << num1 << " / " << num2 << " = " << num1/num2;

break;

default:

// operator is doesn't match any case constant (+, -, *, /)

cout << "Error! operator is not correct";

break;

return 0;

Output

Enter an operator (+, -, *, /): +

Enter two operands: 2.3

4.5

2.3 - 4.5 = -2.2

The - operator entered by the user is stored in o variable. And, two operands 2.3 and 4.5 are
stored in variables num1 and num2 respectively.

Then, the control of the program jumps to

cout << num1 << " - " << num2 << " = " << num1-num2;

Finally, the break statement ends the switch statement.

If break statement is not used, all cases after the correct case is executed.
C++ goto Statement

In C++ programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.

Syntax of goto Statement

goto label;

... .. ...

... .. ...

... .. ...

label:

statement;

... .. ...

In the syntax above, label is an identifier. When goto label; is encountered, the control of
program jumps to label: and executes the code below it.

Example: goto Statement

// This program calculates the average of numbers entered by user.

// If user enters negative number, it ignores the number and

// calculates the average of number entered before it.


# include <iostream>

using namespace std;

int main()

float num, average, sum = 0.0;

int i, n;

cout << "Maximum number of inputs: ";

cin >> n;

for(i = 1; i <= n; ++i)

cout << "Enter n" << i << ": ";

cin >> num;

if(num < 0.0)

// Control of the program move to jump:

goto jump;

sum += num;

jump:

average = sum / (i - 1);


cout << "\nAverage = " << average;

return 0;

Output

Maximum number of inputs: 10

Enter n1: 2.3

Enter n2: 5.6

Enter n3: -5.6

Average = 3.95

You can write any C++ program without the use of goto statement and is generally considered a
good idea not to use them.

Reason to Avoid goto Statement

The goto statement gives power to jump to any part of program but, makes the logic of the
program complex and tangled.

In modern programming, goto statement is considered a harmful construct and a bad


programming practice.

The goto statement can be replaced in most of C++ program with the use of break and continue
statements.

C++ Arrays

In programming, one of the frequently arising problem is to handle numerous data of same type.

Consider this situation, you are taking a survey of 100 people and you have to store their age. To
solve this problem in C++, you can create an integer array having 100 elements.
An array is a collection of data that holds fixed number of values of same type. For example:

int age[100];

Here, the age array can hold maximum of 100 elements of integer type.

The size and type of arrays cannot be changed after its declaration.

How to declare an array in C++?

dataType arrayName[arraySize];

For example,

float mark[5];

Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5
floating-point values.

Elements of an Array and How to access them?

You can access elements of an array by using indices.

Suppose you declared an array mark as above. The first element is mark[0], second element
is mark[1] and so on.

Few key notes:

Arrays have 0 as the first index not 1. In this example, mark[0] is the first element.
If the size of an array is n, to access the last element, (n-1) index is used. In this
example, mark[4] is the last element.
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be
2124d, address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.

How to initialize an array in C++ programming?

It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int mark[] = {19, 10, 8, 17, 9};

Here,

mark[0] is equal to 19

mark[1] is equal to 10

mark[2] is equal to 8

mark[3] is equal to 17

mark[4] is equal to 9

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}


// insert different value to third element

mark[3] = 9;

// take input from the user and insert in third element

cin >> mark[2];

// take input from the user and insert in (i+1)th element

cin >> mark[i];

// print first element of an array

cout << mark[0];

// print ith element of an array

cin >> mark[i-1];

Example: C++ Array

C++ program to store and calculate the sum of 5 numbers entered by the user using arrays.

#include <iostream>

using namespace std;

int main()

int numbers[5], sum = 0;

cout << "Enter 5 numbers: ";


// Storing 5 number entered by user in an array

// Finding the sum of numbers entered

for (int i = 0; i < 5; ++i)

cin >> numbers[i];

sum += numbers[i];

cout << "Sum = " << sum << endl;

return 0;

Output

Enter 5 numbers: 3

Sum = 18

Things to remember when working with arrays in C++

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];
You can use the array members from testArray[0] to testArray[9].

If you try to access array elements outside of its bound, let's say testArray[14], the compiler may
not show any error. However, this may cause unexpected output (undefined behavior).

C++ Multidimensional Arrays

In C++, you can create an array of an array known as multi-dimensional array. For example:

int x[3][4];

Here, x is a two dimensional array. It can hold a maximum of 12 elements.

You can think this array as table with 3 rows and each row has 4 columns as shown below.

Three dimensional array also works in a similar way. For example:

float x[2][4][3];

This array x can hold a maximum of 24 elements. You can think this example as: Each of the 2
elements can hold 4 elements, which makes 8 elements and each of those 8 elements can hold 3
elements. Hence, total number of elements this array can hold is 24.

Multidimensional Array Initialisation

You can initialise a multidimensional array in more than one way.


Initialisation of two dimensional array

int test[2][3] = {2, 4, -5, 9, 0, 9};

Better way to initialise this array with same array elements as above.

int test[2][3] = { {2, 4, 5}, {9, 0 0}};

Initialisation of three dimensional array

int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23,

2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

Better way to initialise this array with same elements as above.

int test[2][3][4] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }

};

Example 1: Two Dimensional Array

C++ Program to display all elements of an initialised two dimensional array.

#include <iostream>

using namespace std;

int main()

{
int test[3][2] =

{2, -5},

{4, 0},

{9, 1}

};

// Accessing two dimensional array using

// nested for loops

for(int i = 0; i < 3; ++i)

for(int j = 0; j < 2; ++j)

cou t<< "test[" << i << "][" << j << "] = " << test[i][j] << endl;

return 0;

Output

test[0][0] = 2

test[0][1] = -5

test[1][0] = 4

test[1][1] = 0
test[2][0] = 9

test[2][1] = 1

Example 2: Two Dimensional Array

C++ Program to store temperature of two different cities for a week and display it.

#include <iostream>

using namespace std;

const int CITY = 2;

const int WEEK = 7;

int main()

int temperature[CITY][WEEK];

cout << "Enter all temperature for a week of first city and then second city. \n";

// Inserting the values into the temperature array

for (int i = 0; i < CITY; ++i)

for(int j = 0; j < WEEK; ++j)

cout << "City " << i + 1 << ", Day " << j + 1 << " : ";

cin >> temperature[i][j];


}

cout << "\n\nDisplaying Values:\n";

// Accessing the values from the temperature array

for (int i = 0; i < CITY; ++i)

for(int j = 0; j < WEEK; ++j)

cout << "City " << i + 1 << ", Day " << j + 1 << " = " << temperature[i][j] << endl;

return 0;

Output

Enter all temperature for a week of first city and then second city.

City 1, Day 1 : 32

City 1, Day 2 : 33

City 1, Day 3 : 32

City 1, Day 4 : 34

City 1, Day 5 : 35

City 1, Day 6 : 36
City 1, Day 7 : 38

City 2, Day 1 : 23

City 2, Day 2 : 24

City 2, Day 3 : 26

City 2, Day 4 : 22

City 2, Day 5 : 29

City 2, Day 6 : 27

City 2, Day 7 : 23

Displaying Values:

City 1, Day 1 = 32

City 1, Day 2 = 33

City 1, Day 3 = 32

City 1, Day 4 = 34

City 1, Day 5 = 35

City 1, Day 6 = 36

City 1, Day 7 = 38

City 2, Day 1 = 23

City 2, Day 2 = 24
City 2, Day 3 = 26

City 2, Day 4 = 22

City 2, Day 5 = 29

City 2, Day 6 = 27

City 2, Day 7 = 23

Example 3: Three Dimensional Array

C++ Program to Store value entered by user in three dimensional array and display it.

#include <iostream>

using namespace std;

int main()

// This array can store upto 12 elements (2x3x2)

int test[2][3][2];

cout << "Enter 12 values: \n";

// Inserting the values into the test array

// using 3 nested for loops.

for(int i = 0; i < 2; ++i)

for (int j = 0; j < 3; ++j)

for(int k = 0; k < 2; ++k )


{

cin >> test[i][j][k];

cout<<"\nDisplaying Value stored:"<<endl;

// Displaying the values with proper index.

for(int i = 0; i < 2; ++i)

for (int j = 0; j < 3; ++j)

for(int k = 0; k < 2; ++k)

cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;

return 0;

Output

Enter 12 values:

1
2

10

11

12

Displaying Value stored:

test[0][0][0] = 1

test[0][0][1] = 2

test[0][1][0] = 3

test[0][1][1] = 4

test[0][2][0] = 5

test[0][2][1] = 6

test[1][0][0] = 7
test[1][0][1] = 8

test[1][1][0] = 9

test[1][1][1] = 10

test[1][2][0] = 11

test[1][2][1] = 12

As the number of dimension increases, the complexity also increases tremendously although the
concept is quite similar.

Passing Array to a Function in C++ Programming

Arrays can be passed to a function as an argument. Consider this example to pass one-
dimensional array to a function:

Example 1: Passing One-dimensional Array to a Function

C++ Program to display marks of 5 students by passing one-dimensional array to a


function.

#include <iostream>

using namespace std;

void display(int marks[5]);

int main()

int marks[5] = {88, 76, 90, 61, 69};

display(marks);

return 0;

void display(int m[5])


{

cout << "Displaying marks: "<< endl;

for (int i = 0; i < 5; ++i)

cout << "Student "<< i + 1 <<": "<< m[i] << endl;

Output

Displaying marks:

Student 1: 88

Student 2: 76

Student 3: 90

Student 4: 61

Student 5: 69

When an array is passed as an argument to a function, only the name of an array is used as
argument.

display(marks);

Also notice the difference while passing array as an argument rather than a variable.

void display(int m[5]);

The argument marks in the above code represents the memory address of first element of
array marks[5].
And the formal argument int m[5] in function declaration converts to int* m;. This pointer points
to the same address pointed by the array marks.

That's the reason, although the function is manipulated in the user-defined function with different
array name m[5], the original array marks is manipulated.

C++ handles passing an array to a function in this way to save memory and time.

Passing Multidimensional Array to a Function

Multidimensional array can be passed in similar way as one-dimensional array. Consider this
example to pass two dimensional array to a function:

Example 2: Passing Multidimensional Array to a Function

C++ Program to display the elements of two dimensional array by passing it to a function.

#include <iostream>

using namespace std;

void display(int n[3][2]);

int main()

int num[3][2] = {

{3, 4},

{9, 5},

{7, 1}

};

display(num);

return 0;

}
void display(int n[3][2])

cout << "Displaying Values: " << endl;

for(int i = 0; i < 3; ++i)

for(int j = 0; j < 2; ++j)

cout << n[i][j] << " ";

Output

Displaying Values:

349571

In the above program, the multi-dimensional array num is passed to the function display().

Inside, display() function, the array n (num) is traversed using a nested for loop.

The program uses 2 for loops to iterate over the elements inside a 2-dimensional array. If it were
a 3-dimensional array, you should use 3 for loops. Finally, all elements are printed onto the
screen.

Note: Multidimensional array with dimension more than 2 can be passed in similar way as two
dimensional array.

References

Turbo C

https://www.programiz.com/c-programming/c-functions
https://www.cprogramming.com/tutorial/lesson1.htm1

Turbo C++

https://www.programiz.com/cpp-programming/function

https://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way

Anda mungkin juga menyukai