Reference Notes for c Programming
Reference Notes for c Programming
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.
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
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.
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
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:
Here, the argument list comprises the variables or values to be printed, and the format
string determines the output format.
Here, the argument list comprises the variables that will receive the input, and the format
string describes the format of the input.
Example:
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:
Unit – II
The if Statement
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Example
if (20 > 18) {
printf("20 is greater than 18");
}
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."
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."
In more complex scenarios, nested if-else statements can be used to make more
sophisticated decisions.
Syntax:
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
Output
Zero
Switch Statement
Instead of writing many if..else statements, you can use the switch statement.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
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;
}
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
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
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 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 3 is executed (every time) after the code block has been executed.
Example
int i;
Example
int 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.
Example
int 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
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.
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.
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:
We have used a for loop to iterate over the elements of the array and print their values using
the printf function.
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.
1. arrayName[index]
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:
Explanation:
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.
1. arrayName[index]
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:
Explanation:
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.
1. data_type array_name[rows][columns];
1. int twodimen[4][3];
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}};
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
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
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
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.
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
No Function Description
.
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
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
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.
// 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 .
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
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>
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
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.
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.
1. functionname(arrayname);//passing array
There are 3 ways to declare the function which is intended to receive an array as an
argument.rward Skip 10s
First way:
Second way:
Third way:
You can also use the concept of a pointer. In pointer chapter, we will learn about it.
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
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.
Strfun(buff);
Here,
/*
C program to pass a string to a function
*/
#include <stdio.h>
// main function
int main()
{
// Declare a buffer of type "char"
char buff[20]="Hello Function";
Output
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.
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.
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. };
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.
Example program:
Output:
Point to understand:
Here,
= 2 + 10 + 2 = 14
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;
o name
o salary
o emp_id
o address
o dept_no
Example programs:
Output:
Roll no : 110
Name : Sarika
Marks : 568
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:
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. };
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
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.
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
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
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.
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
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.
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:
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
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".
Mode Description
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.
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
#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 );
}
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
#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;
}