0% found this document useful (0 votes)
2 views40 pages

Reference Notes for c Programming

The document provides an overview of tokens in the C programming language, categorizing them into six types: keywords, identifiers, constants, strings, special symbols, and operators. It explains the significance and rules for each type, including examples of usage and specific operators such as arithmetic, relational, and logical operators. Additionally, it covers formatted input and output, as well as control structures like if statements and nested if-else statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views40 pages

Reference Notes for c Programming

The document provides an overview of tokens in the C programming language, categorizing them into six types: keywords, identifiers, constants, strings, special symbols, and operators. It explains the significance and rules for each type, including examples of usage and specific operators such as arithmetic, relational, and logical operators. Additionally, it covers formatted input and output, as well as control structures like if statements and nested if-else statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Unit - I

TOKENS
A token in C can be defined as the smallest individual element of the C programming language that is
meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords
 The keywords are pre-defined or reserved words in a programming language.
 Each keyword is meant to perform a specific function in a program.
 Since keywords are referred names for a compiler, they can’t be used as variable names
C language supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
2. Identifiers
 Identifiers are used as the general terminology for the naming of variables, functions, and arrays.
 These are user-defined names consisting of an arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as a first character.
 Identifier names must differ in spelling and case from any keywords.

Rules for Naming Identifiers

Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.
For example,
 main: method name.
 a: variable name.
3. Constants
 The constants refer to the variables with fixed values.
 They are like normal variables but with the difference that their values can not be modified in the
program once they are defined.
 Constants may belong to any of the data types.

Examples of Constants in C

const int c_var = 20;


const int* const ptr = &c_var;
4. Strings
 Strings are nothing but an array of characters ended with a null character (‘\0’).
 Strings are always enclosed in double quotes. Whereas, a character is enclosed in single quotes
in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’,
‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
5. Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be used for
some other purpose. Some of these are listed below:
 Brackets[]: Opening and closing brackets are used as array element references. These indicate
single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
 Comma (, ): It is used to separate more than one statement like for separating parameters in
function calls.
 Colon(:): It is an operator that essentially invokes something called an initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s
why each individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
 Assignment operator(=): It is used to assign values and for logical operation validation.
 Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
 Period (.): Used to access members of a structure or union.
 Tilde(~): Used as a destructor to free some space from memory.

6. Operators
 Operators are symbols that trigger an action when applied to C variables and other objects.
 The data items on which operators act are called operands.
 Depending on the number of operands that an operator can act upon, operators can be classified
as follows:
1. Unary Operators: Those operators that require only a single operand to act upon are known as
unary operators.For Example increment and decrement operators
2. Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
a. Arithmetic operators
b. Relational Operators
c. Logical Operators
d. Assignment Operators
e. Bitwise Operator
3. Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator.

1. Arithmetic Operations in C
These operators are used to perform arithmetic/mathematical operations on operands. Examples: (+, -,
*, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For example: Increment(++)
and Decrement(–) Operators
int val = 5;
cout<<++val; // 6
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example: Addition(+),
Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators in C
These are used for the comparison of the values of two operands. For example, checking if one operand
is equal to the other operand or not, whether an operand is greater than the other operand or not, etc.
Some of the relational operators are (==, >= , <= )
int a = 3;
int b = 5;
cout<<(a < b);
// operator to check if a is smaller than b
3. Logical Operator in C
Logical Operators are used to combining two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. The result of the operation of a logical operator is a
Boolean value either true or false.
For example, the logical AND represented as the ‘&&’ operator in C returns true when both the
conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b returns true
when both a and b are true
cout<<((4 != 5) && (4 < 5)); // true
4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands. The operators are first
converted to bit-level and then the calculation is performed on the operands. Mathematical operations
such as addition, subtraction, multiplication, etc. can be performed at the bit level for faster processing.
For example, the bitwise AND operator represented as ‘&’ in C takes two numbers as operands and
does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value on the
right side must be of the same data type as the variable on the left side otherwise the compiler will raise
an error.
Different types of assignment operators are shown below:
a) “=”
This is the simplest assignment operator. This operator is used to assign the value on the right to the
variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds the current value of
the variable on left to the value on the right and then assigns the result to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right
from the current value of the variable on left and then assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the current value
of the variable on left to the value on the right and then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the current value of
the variable on left by the value on the right and then assigns the result to the variable on the left.

Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators
Apart from the above operators, there are some other operators available in C used to perform some
specific tasks. Some of them are discussed here:
i. sizeof operator
 sizeof is much used in the C programming language.
 It is a compile-time unary operator which can be used to compute the size of its operand.
 The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
 Basically, the sizeof the operator is used to compute the size of the variable.

ii. Comma Operator


 The comma operator (represented by the token) is a binary operator that evaluates its first operand
and discards the result, it then evaluates the second operand and returns this value (and type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator.

iii. Conditional Operator


 The conditional operator is of the form Expression1? Expression2: Expression3
 Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will
execute and return the result of Expression2 otherwise if the condition(Expression1) is false then we
will execute and return the result of Expression3.
 We may replace the use of if..else statements with conditional operators.
Operator precedence determines the grouping of terms in an expression and decides how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has a higher precedence than the addition operator.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Associativ
Category Operator
ity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


Formatted input and output

The I/O procedure is known as "formatted I/O". It enables you to read or write data in a
certain format. Printf() and scanf() are two examples of C routines that handle formatted
I/O. The type and format of the data to be read or written are specified by format strings,
which are used by these operations. The program's execution replaces the placeholders for
the data found in the format strings with the actual data.

Syntax:

Formatted output syntax for the printf() function:

1. printf(format string, argument list);

Here, the argument list comprises the variables or values to be printed, and the format
string determines the output format.

Formatted input syntax for the scanf() function:

Here, the argument list comprises the variables that will receive the input, and the format
string describes the format of the input.

Example:

Let's examine an illustration of formatted I/O in C:

1. #include <stdio.h>
2. int main() {
3. char name[20];
4. int age;
5. printf("Enter your name: ");
6. scanf("%s", name);
7. printf("Enter your age: ");
8. scanf("%d", &age);
9. printf("Your name is %s and your age is %d\n", name, age);
10.return 0;
11.}

Output:

Enter your name: Avi


Enter your age: 22
Your name is Avi and your age is 22
Symbol of Meaning of Specifier
Specifier

/t Used by a program for tab space (it is equivalent to a total of 8


spaces)

/n Used by a program for a new line (it is also known as a linefeed


return)

Unit – II

The if Statement

Use the if statement to specify a block of code to be executed if a condition is true.

Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Example
if (20 > 18) {
printf("20 is greater than 18");
}

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is
true
} else {
// block of code to be executed if the condition1 is false and condition2 is
false
}

Example
int time = 22;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."

Nested if else statement in C

In more complex scenarios, nested if-else statements can be used to make more
sophisticated decisions.

Syntax:

A nested if-else statement is an if statement inside another if statement. The general


syntax of nested if-else statement in C is as follows:

1. if (condition1) {
2. /* code to be executed if condition1 is true */
3. if (condition2) {
4. /* code to be executed if condition2 is true */
5. } else {
6. /* code to be executed if condition2 is false */
7. }
8. } else {
9. /* code to be executed if condition1 is false */
10.}

Else...if ladder

if else if ladder in C programming is used to test a series of conditions sequentially. Furthermore, if a


condition is tested only when all previous if conditions in the if-else ladder are false. If any of the
conditional expressions evaluate to be true, the appropriate code block will be executed, and the entire
if-else ladder will be terminated.
Syntax:
// any if-else ladder starts with an if statement only
if(condition) {
}
else if(condition) {
// this else if will be executed when condition in if is false and
// the condition of this else if is true
}
.... // once if-else ladder can have multiple else if
else { // at the end we put else
}
Working Flow of the if-else-if ladder:
1. The flow of the program falls into the if block.
2. The flow jumps to 1st Condition
3. 1st Condition is tested respectively:
 If the following Condition yields true, go to Step 4.
 If the following Condition yields false, go to Step 5.
4. The present block is executed. Goto Step 7.
5. The flow jumps to Condition 2.
 If the following Condition yields true, go to step 4.
 If the following Condition yields false, go to Step 6.
6. The flow jumps to Condition 3.
 If the following Condition yields true, go to step 4.
 If the following Condition yields false, execute the else block. Goto Step 7.
7. Exits the if-else-if ladder.

if else if ladder flowchart in C

Note: A if-else ladder can exclude else block.

Example 1: Check whether a number is positive, negative or 0


C

// C Program to check whether


// a number is positive, negative
// or 0 using if else if ladder
#include <stdio.h>
int main()
{
int n = 0;
// all Positive numbers will make this
// condition true
if (n > 0) {
printf("Positive");
}
// all Negative numbers will make this
// condition true
else if (n < 0) {
printf("Negative");
}
// if a number is neither Positive nor Negative
else {
printf("Zero");
}
return 0;
}

Output
Zero

Switch Statement

Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break statement breaks out of the switch block and stops the execution
 The default statement is optional, and specifies some code to run if there is no case
match

The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;

switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}

// Outputs "Thursday" (day 4)

goto statement

The goto statement is known as jump statement in C. As the name suggests, goto is used to
transfer the program control to a predefined label. The goto statment can be used to repeat
some part of the code for a particular condition. It can also be used to break the multiple
loops which can't be done by using a single break statement.

Syntax:

1. label:
2. //some part of the code;
3. goto label;

example

Let's see a simple example to use goto statement in C language.

1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12.}
Output:Backward Skip 10sPlay VideoForward Skip 10s

Enter the number whose table you want to print?10


10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100
Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax
while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long as a variable
(i) is less than 5:

Example
int i = 0;

while (i < 5) {
printf("%d\n", i);
i++;
}

The Do-While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.

Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:

Example
int i = 0;

do {
printf("%d\n", i);
i++;
}
while (i < 5);

For Loop

When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
int i;

for (i = 0; i < 5; i++) {


printf("%d\n", i);
}

Break and Continue


Break

The break statement can also be used to jump out of a loop.

This example jumps out of the for loop when i is equal to 4:

Example
int i;

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


{
if (i == 4)
{
break;
}
printf("%d\n", i);
}

Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 4:

Example
int i;

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


{
if (i == 4)
{
continue;
}
printf("%d\n", i);
}

Unit – III
C Array

An array is defined as the collection of similar type of data items stored at contiguous
memory locations.

Arrays are the derived data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc.

The array is the simplest data structure where each data element can be randomly accessed
by using its index number.

By using the array, we can access the elements easily. Only a few lines of code are required
to access the elements of the array.

Properties of Array

The array contains the following properties.ard Skip 10s

o Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.

o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.

o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data
element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit.

One dimensional array in C

Arrays are a fundamental concept in programming, and they come in different


dimensions. One-dimensional arrays, also known as single arrays, are arrays with only one
dimension or a single row.

Syntax of One-Dimensional Array in C

The syntax of a one-dimensional array in C programming language is as follows:

1. dataType arrayName[arraySize];

o dataType specifies the data type of the array. It can be any valid data type in C
programming language, such as int, float, char, double, etc.

o arrayName is the name of the array, which is used to refer to the array in the
program.

o arraySize specifies the number of elements in the array. It must be a positive


integer value.

Example of One-Dimensional Array in C

Let's take a simple example of a one-dimensional array in C programming language to


understand its syntax and usage.

1. #include <stdio.h>
2. int main() {
3. int numbers[5] = {10, 20, 30, 40, 50};
4. for(int i=0; i<5; i++) {
5. printf("numbers[%d] = %d\n", i, numbers[i]);
6. }
7. return 0;
8. }

Output:

numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Explanation:

In the above example, we have declared a one-dimensional array of integers


named numbers. The array contains five elements, and each element is initialized with a
value.

We have used a for loop to iterate over the elements of the array and print their values using
the printf function.

Accessing Elements of One-Dimensional Array in C

In a one-dimensional array, each element is identified by its index or position in the array.
The index of the first element in the array is 0, and the index of the last element is arraySize
- 1.

To access an element of a one-dimensional array in C programming language, we use the


following syntax:

1. arrayName[index]

o arrayName is the name of the array.

o index is the index of the element we want to access.

Example of Accessing Elements of One-Dimensional Array in C

Let's take an example to understand how to access elements of a one-dimensional array in C


programming language.

1. #include <stdio.h>
2. int main() {
3. int numbers[5] = {10, 20, 30, 40, 50};
4. printf("The first element of the array is: %d\n", numbers[0]);
5. printf("The third element of the array is: %d\n", numbers[2]);
6.
7. return 0;
8. }

Output:

The first element of the array is: 10


The third element of the array is: 30

Explanation:

In the above example, we have declared a one-dimensional array of integers


named numbers. We have accessed the first element of the array using the index 0 and the
third element of the array using the index 2.
Accessing Elements of One-Dimensional Arrays

We can access individual elements of a one-dimensional array using their index, which is an
integer value that represents the position of the element in the array. The index of the first
element in the array is 0, and the index of the last element is arraySize-1.

The syntax to access an element of a one-dimensional array in C is as follows:

1. arrayName[index]

o arrayName is the name of the array.

o index is the index of the element we want to access.

Example of Accessing Elements of One-Dimensional Array in C

1. #include <stdio.h>
2. int main() {
3. int numbers[5] = {10, 20, 30, 40, 50};
4. printf("The third element of the array is %d\n", numbers[2]);
5. return 0;
6. }

Output:

The third element of the array is 30

Explanation:

In the above example, we have declared a one-dimensional array of integers


named numbers and initialized it with the values {10, 20, 30, 40, 50}. We have used
the printf function to print the third element of the array, which is accessed using the index
2.

Two Dimensional Array in C

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays
are created to implement a relational database lookalike data structure. It provides ease of
holding the bulk of data at once which can be passed to any number of functions wherever
required.

Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];

Consider the following example.

1. int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.


Initialization of 2D Array in C

In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays. We
will have to define at least the second dimension of the array. The two-dimensional array can
be declared and defined in the following way.

1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two-dimensional array example in C

1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10.}//end of i
11.return 0;
12.}

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

C 2D array example: Storing elements in a matrix and printing it.

1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22.}

Output

Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78

Strings
 The string can be defined as the one-dimensional array of characters terminated by a
null ('\0').
 The character array or the string is used to manipulate text such as word or sentences.
 Each character in the array occupies one byte of memory, and the last character must
always be 0.
 The termination character ('\0') is important in a string since it is the only way to
identify where the string ends.
 When we define a string as char s[10], the character s[10] is implicitly initialized with
the null in the memory.
There are two ways to declare a string in c language.

1. By char array

2. By string literal

Let's see the example of declaring string by char array in C language.


1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

As we know, array index starts from 0, so it will be represented as in the figure given below.

While declaring string, size is not mandatory. So we can write the above code as given below:

1. char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

We can also define the string by the string literal in C language. For example:

1. char ch[]="javatpoint";

In such case, '\0' will be appended at the end of the string by the compiler.

Difference between char array and string literal

There are two main differences between char array and literal.

o We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the character array.

o The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.

String Example in C

Let's see a simple example where a string is declared and being printed. The '%s' is used as a
format specifier for the string in c language.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[11]="javatpoint";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10.}

Output

Char Array Value is: javatpoint


String Literal Value is: javatpoint
String-handling Functions

There are many important string functions defined in "string.h" library.

No Function Description
.

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, copies the contents of source string to


source) destination string.

3) strcat(first_string, concats or joins first string with second string.


second_string) The result of the string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If


second_string) both strings are same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

Unit – IV
User-Defined Function in C
A user-defined function is a type of function in C language that is defined by the user himself to
perform some specific task. It provides code reusability and modularity to our program. User-defined
functions are different from built-in functions as their working is specified by the user and no header file
is required for their usage.
How to use User-Defined Functions in C?
To use a user-defined function, we first have to understand the different parts of its syntax. The user-
defined function in C can be divided into three parts:
1. Function Prototype
2. Function Definition
3. Function Call

C Function Prototype
A function prototype is also known as a function declaration which specifies the function’s name,
function parameters, and return type. The function prototype does not contain the body of the
function. It is basically used to inform the compiler about the existence of the user-defined function
which can be used in the later part of the program.

Syntax

return_type function_name (type1 arg1, type2 arg2, ... typeN argN);


We can also skip the name of the arguments in the function prototype. So,
return_type function_name (type1 , type2 , ... typeN);

C Function Definition
Once the function has been called, the function definition contains the actual statements that will be
executed. All the statements of the function definition are enclosed within { } braces.

Syntax

return_type function_name (type1 arg1, type2 arg2 .... typeN argN) {

// actual statements to be executed


// return value if any
}
Note: If the function call is present after the function definition, we can skip the function prototype part
and directly define the function.

C Function Call
In order to transfer control to a user-defined function, we need to call it. Functions are called using their
names followed by round brackets. Their arguments are passed inside the brackets.
Syntax
function_name(arg1, arg2, ... argN);
Example of User-Defined Function
The following C program illustrates how to use user-defined functions in our program.

// C Program to illustrate the use of user-defined function


#include <stdio.h>

// Function prototype
int sum(int, int);

// Function definition
int sum(int x, int y)
{
int sum;
sum = x + y;
return x + y;
}

// Driver code
int main()
{
int x = 10, y = 11;
// Function call
int result = sum(x, y);
printf("Sum of %d and %d = %d ", x, y, result);

return 0;
}

Output
Sum of 10 and 11 = 21
Components of Function Definition
There are three components of the function definition:
1. Function Parameters
2. Function Body
3. Return Value

1. Function Parameters

Function parameters (also known as arguments) are the values that are passed to the called function by
the caller. We can pass none or any number of function parameters to the function.
We have to define the function name and its type in the function definition and we can only pass the
same number and type of parameters in the function call.
Example
int foo (int a, int b);
Here, a and b are function parameters.
Note: C language provides a method using which we can pass variable number of arguments to the
function. Such functions are called variadic function.

2. Function Body

The function body is the set of statements that are enclosed within { } braces. They are the statements
that are executed when the function is called.
Example
int foo (int a, int b) {
int sum = a + b;
return sum;
}
Here, the statements between { and } is function body.

3. Return Value

The return value is the value returned by the function to its caller. A function can only return a single
value and it is optional. If no value is to be returned, the return type is defined as void.
The return keyword is used to return the value from a function.
Syntax
return (expression);
Example
int foo (int a, int b) {
return a + b;
}
Note: We can use pointers or structures to return multiple values from a function in C .

Passing Parameters to User-Defined Functions


We can pass parameters to a function in C using two methods:
1. Call by Value
2. Call by Reference

1. Call by value

In call by value, a copy of the value is passed to the function and changes that are made to the function
are not reflected back to the values. Actual and formal arguments are created in different memory
locations.
Example

// C program to show use of


// call by value
#include <stdio.h>
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(x, y);
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}

Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 10, 20
Note: Values aren’t changed in the call by value since they aren’t passed by reference.

2. Call by Reference

In a call by Reference, the address of the argument is passed to the function, and changes that are
made to the function are reflected back to the values. We use the pointers of the required type to
receive the address in the function.
Example

// C program to implement
// Call by Reference
#include <stdio.h>

void swap(int* a, int* b)


{
int temp = *a;
*a = *b;
*b = temp;
}
// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(&x, &y);
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}

Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 20, 10
Advantages of User-Defined Functions
The advantages of using functions in the program are as follows:
 One can avoid duplication of code in the programs by using functions. Code can be written more
quickly and be more readable as a result.
 Code can be divided and conquered using functions. This process is known as Divide and Conquer.
It is difficult to write large amounts of code within the main function, as well as testing and
debugging. Our one task can be divided into several smaller sub-tasks by using functions, thus
reducing the overall complexity.
 For example, when using pow, sqrt, etc. in C without knowing how it is implemented, one can hide
implementation details with functions.
 With little to no modifications, functions developed in one program can be used in another, reducing
the development time.

C - Recursion

Recursion is the process of repeating items in a self-similar way. In programming languages, if


a program allows you to call a function inside the same function, then it is called a recursive
call of the function.

void recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion();
}

The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating
the factorial of a number, generating Fibonacci series, etc.

Passing Array to Function in C

In C, there are various general problems which requires passing more than one variable of the
same type to a function. For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed as the actual parameters
from the main function. Here, instead of declaring 10 different numbers and then passing into
the function, we can declare and initialize an array and pass that into the function. This will
resolve all the complexity since the function will now work for any number of values.
As we know that the array_name contains the address of the first element. Here, we must
notice that we need to pass only the name of the array in the function which is intended to
accept an array. The array defined as the formal parameter will automatically refer to the
array specified by the array name defined as an actual parameter.

Consider the following syntax to pass an array to the function.

1. functionname(arrayname);//passing array

Methods to declare a function that receives an array as an argument

There are 3 ways to declare the function which is intended to receive an array as an
argument.rward Skip 10s

First way:

1. return_type function(type arrayname[])

Declaring blank subscript notation [] is the widely used technique.

Second way:

1. return_type function(type arrayname[SIZE])

Optionally, we can define size in subscript notation [].

Third way:

1. return_type function(type *arrayname)

You can also use the concept of a pointer. In pointer chapter, we will learn about it.

C language passing an array to function example

1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10.return min;
11.}//end of function
12.
13.int main(){
14.int i=0,min=0;
15.int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17.min=minarray(numbers,6);//passing array with size
18.printf("minimum number is %d \n",min);
19.return 0;
20.}

Output

minimum number is 3

Passing String to function


A string can be passed to the function using pointers as below,

void Strfun(char *ptr)

Here,

 void is the returns type of the function i.e. it will return nothing.
 Strfun is the name of the function.
 char *ptr is the character pointer that will store the base address of the character
array (string) which is going to be passed through main() function.

Function calling statement,

Strfun(buff);

Here,

1. buff is the character array (string).

Program to pass string to a function and print in C

/*
C program to pass a string to a function
*/

#include <stdio.h>

void Strfun(char *ptr)


{
printf("The String is : %s",ptr);
}

// main function
int main()
{
// Declare a buffer of type "char"
char buff[20]="Hello Function";

// Passing string to Function


Strfun(buff);
return 0;
}

Output

The String is : Hello Function

Scope, Visibility and Lifetime of a Variable in C


What is scope and lifetime?

The scope of a variable refers that to which different parts of a program have access to the
variable in other words, where the variable is visible. When speaking about scope, the term
variable refers to all C data types: simple variables, arrays, structure, pointers, and so forth. It
also refers to symbolic constants defined with the const keyword.

The life time of variable refers that how long the variable persists in memory, or when the
variable's storage is allocated and de-allocated. Depending upon the scope and lifetime of
variable, C has its four storage classes for variables used in any functions.

1. Automatic variables
2. External variables
3. Static variables
4. Register variables

The variables may broadly categorized , depending upon the place of their declaration as:
internal(local) or External(global).

 The internal(local) variables are those which are declared inside the function.
 The external(global) variables are those which are declared outside the function.

Overview of Structures and Unions in C

Structures and unions are two of many user defined data types in C. Both are similar to each
other but there are quite some significant differences.

STRUCTURES:

A structure simply can be defined as a user-defined data type which groups logically related
items under one single unit. We can use all the different data items by accessing that single
unit.

All the data item are stored in contiguous memory locations. It is not only permitted to one
single data type items. It can store items of different data items. It has to be defined before
using.

Structure definition syntax:

1. struct_structure_name
2. {
3. data_type_variable_name;
4. data_type_variable_name;
5. ........
6. data_type_variable_name;
7. };

Example:

Suppose we need to store the details of an employee. It includes ID, name, age, salary,
designation and several other factors which belong to different data types.

1. struct Empl
2. {
3. int emp_id;
4. float salary;
5. char designation[20];
6. int depart_no;
7. int age_of_emp;
8. };

Memory space allocation:

Let's assume we stored id . It is stores somewhere say in address 8000, it needs 2 memory
units as it belongs to int data type. Now, the next item, name is stored after the id at 8002. In
the same way, all the items are stores contiguously.

8000 -> emp_id (2 bytes)

8002 -> name[20] (20*1 = 20 bytes)

8022 -> salary (4 bytes)

8026 -> designation[50] (50*1 = 50 bytes)

8076 ->dept_no (2 bytes)

8078 -> age (2 bytes)

Example program:

1. //To show the memory allocation


2. #include<stdio.h>
3. struct student
4. {
5. int rollno;
6. int marks;
7. char name[10];
8. };
9. int main()
10. {
11. int size;
12. struct student s; //Declaring a structure variable
13. size = sizeof(s);
14. printf("\nSize of the Structure : %d", size);
15. return 0;
16.}

Output:

Size of the structure: 14

Point to understand:

Here,

Size of Structure 'S' = sizeof(roll) + sizeof(name) + sizeof(mark)

= 2 + 10 + 2 = 14

Accessing the members of a structure:

We cannot initialize the structure in the definition and we cannot just access the members by
using the names. After defining the structure, we need to define a variable of that structure
data type.

Now, we use this variable to access the items of the structure using the special operator (.).
Here is an example;

1. struct Emp e1;

e1 is the structure variable now.

To access the data items in the structure:

o name

o salary

o emp_id

o address

o dept_no

Here is another example:

1. struct employee e1;


2. e1.id = 111;
3. e1.name = "Ravi"
4. e1.salary = 56,000
Another way:

1. struct employee e1 = {111,"Ravi",56,000};

Example programs:

1. //To store the details of a student


2. #include<stdio.h>
3. struct student1
4. {
5. int rollno;
6. char name[10];
7. int marks;
8. };
9. void main()
10. {
11. int size;
12. struct student1 s={110,"Sarika",568};
13. printf("Roll no : %d\n", s.roll);
14. printf("Name : %s\n", s.name);
15. printf("Marks : %d\n", s.marks);
16.}

Output:

Roll no : 110
Name : Sarika
Marks : 568

Assigning one structure to another:

We can assign one whole structure to another. If we do this, we can access the members of
one structure using the other structure's variable and vice versa.

Let us assume e1 and e2 are the variables of two structures Emp1 and Emp2 respectively. If
we assign e2 to e1:

1. e1 = e2;

Now, the values of every member of the structure Emp2 is assigned to the corresponding
members of Emp1.

Array of structures:

It is used to store large number of similar info altogether. Here, we give an array as a
structure variable rather than a normal variable. Now, we can store more info.

Syntax:
1. struct_struct_name_array_name_value;

Implementation:

1. #include<stdio.h>
2. struct Employee
3. {
4. int Id;
5. int Age;
6. char Name[25];
7. long Salary;
8. };
9. void main()
10. {
11. int i;
12. struct Employee E[ 3 ];
13. for(i=0;i<3;i++)
14. {
15. printf("\nEnter detailsof the Employee",i+1);
16. printf("\n\tEnter Employee Id : ");
17. scanf("%d",&E[i].Id);
18. printf("\n\tEnter Employee Name : ");
19. scanf("%s",&E[i].Name);
20. printf("\n\tEnter Employee Age : ");
21. scanf("%d",&E[i].Age);
22. printf("\n\tEnter Employee Salary : ");
23. scanf("%ld",&E[i].Salary);
24. }
25.printf("\nDetails of Employees");
26.for(i=0;i<3;i++)
27.{
28.printf("\n%d\t%s\t%d\t%ld",E[i].Id,E[i].Name,E[i].Age,E[i].Salary);
29.}
30.}

Output:

Enter details of the Employee


Enter Employee Id : 1
Enter Employee Name : Ravi
Enter Employee Age : 21
Enter Employee Salary : 23000
Enter details of the Employee
Enter Employee Id : 2
Enter Employee Name : Rajesh
Enter Employee Age : 32
Enter Employee Salary : 67890

Enter details of the Employee


Enter Employee Id : 3
Enter Employee Name : Kiran
Enter Employee Age : 34
Enter Employee Salary : 23435
Details of Employees
1 Ravi 21 23000
2 Rajesh 32 67890
3 Kiran 34 23435

UNION:

Just like a structure, a union is also a user-defined data type that groups together logically
related variables into a single unit.

Almost all the properties and syntaxes are same, except some of the factors.

Syntax:

1. union union_name
2. {
3. data_type variable_name;
4. data_type variable_name;
5. ........
6. data_type variable_name;
7. };

Example:

1. union Emp
2. {
3. char address[50];
4. int dept_no;
5. int age;
6. };

Memory allocation in a union:


In a structure, the memory occupied by it is simply the sum of the memory occupied by all its
members as they are organized contiguously and every member has its own memory.

But, in a union, data items are organized one on another. So, the total memory space required
to store a union is the memory required to store the largest memory required element in it.

Another major attachment here is that in a structure, we can access any number of items
anytime. But, in a union, only one item can be accessed at a time.

Here is a table to differentiate all the factors between a structure and a union:

Structures Unions

The keyword "struct" is used to The keyword "union" is used to define a


define a structure. structure.

A unique memory location is given One single memory location is shared by


to every member of a structure all its members

Modifying the value of one item Modifying one single data item affects
won't affect the other items or the other members of the union thus
structure at all. affecting the whole unit.

We initialize several members at We can initialize only the first member of


once. union.

The total size of the structure is the The total size of the union is the size of
sum of the size of every data the largest data member
member

It is mainly used for storing various It is mainly used for storing one of the
data types many data types that are available.

It occupies space for each and every It occupies space for a member having
member written in inner parameters the highest size written in inner
parameters

We can retrieve any member at any We can only access one member at a
time time in the union.
Unit - V
C Pointers

In the scanf statement ‘&’(address of) used to store the value from the user and it also can
get the memory address of a variable with the same operator ‘&’ when it is used in printf:

Example
int myAge = 43; // an int variable

printf("%d", myAge); // Outputs the value of myAge (43)


printf("%p", &myAge); // Outputs the memory address of myAge (0x7ffe5367e044)

A pointer is a variable that stores the memory address of another variable as its value.

A pointer variable points to a data type (like int) of the same type, and is created with
the * operator.

The address of the variable you are working with is assigned to the pointer:

Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the
address of myAge

// Output the value of myAge (43)


printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)


printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)


printf("%p\n", ptr);

Example explained

Create a pointer variable with the name ptr, that points to an int variable (myAge). Note
that the type of the pointer has to match the type of the variable you're working with (int in
our example).

Use the & operator to store the memory address of the myAge variable, and assign it to the
pointer.

Now, ptr holds the value of myAge's memory address.

Dereference

In the example above, we used the pointer variable to get the memory address of a variable
(used together with the & reference operator).

You can also get the value of the variable the pointer points to, by using the * operator
(the dereference operator):
Example
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration

// Reference: Output the memory address of myAge with the pointer


(0x7ffe5367e044)
printf("%p\n", ptr);

// Dereference: Output the value of myAge with the pointer (43)


printf("%d\n", *ptr);

File Handling in C

In programming, we may require some specific input data to be generated several numbers of
times. Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover the programmatically
generated data again and again. However, if we need to do so, we may store it onto the local
file system which is volatile and can be accessed every time. Here, comes the need of file
handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local
file system through our C program. The following operations can be performed on a file.

o Creation of the new file

o Opening an existing file

o Reading from the file

o Writing to the file

o Deleting the file

Functions for file handling

There are many functions in the C library to open, read, write, search and close the file. A list
of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position


8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.rd Skip 10s

1. FILE *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".

o The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode


The fopen function works in the following way.

o Firstly, It searches the file to be opened.

o Then, it loads the file from the disk and place it into the buffer. The buffer is used to
provide efficiency for the read operations.

o It sets up a character pointer which points to the first character of the file.

Consider the following example which opens a file in write mode.

1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10.if ( ch == EOF )
11.break ;
12.printf("%c",ch) ;
13.}
14.fclose (fp ) ;
15.}

Output

The content of the file will be printed.

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the
character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:

1. int fclose( FILE *fp );

Relevant external links:


https://www.javatpoint.com/multidimensional-array-in-c
https://www.scaler.com/topics/c/scope-visibility-lifetime-of-variable-in-c/
https://www.geeksforgeeks.org/type-conversion-c/?ref=lbp

Type conversion in C is the process of converting one data type to another. The type conversion is only
performed to those data types where conversion is possible. Type conversion is performed by a
compiler. In type conversion, the destination data type can’t be smaller than the source data type. Type
conversion is done at compile time and it is also called widening conversion because the destination
data type can’t be smaller than the source data type. There are two types of Conversion:
1. Implicit Type Conversion

Also known as ‘automatic type conversion’.


A. Done by the compiler on its own, without any external trigger from the user.
B. Generally takes place when in an expression more than one data type is present. In such conditions
type conversion (type promotion) takes place to avoid loss of data.
C. All the data types of the variables are upgraded to the data type of the variable with the largest data
type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
D. It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly
converted to unsigned), and overflow can occur (when long is implicitly converted to float).

#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}

You might also like