Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

C Unit2

Uploaded by

velluraju11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

C Unit2

Uploaded by

velluraju11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

BASICS OF PROGRAMMING- C++

UNIT II: Definitions & Functions


Proto-types- Passing arguments - Recursions. Storage Classes - Automatic, External, Static, Register
Variables- Multi-file programs. Arrays - Defining and Processing - Passing arrays to functions – multi-
dimension arrays- Arrays and String. Structures - User defined data types- Passing structures to functions -
Self-referential structures – Unions - Bit wise operations. Pointers- Declarations - Passing pointers to
Functions - Operation in Pointers - Pointer and Arrays - Arrays of Pointers - Structures and Pointers - Files:
Creating, Processing, Opening and Closing a data file.
Functions:
❖ A function is a block of code that performs a particular task.
❖ C language provides an approach in which you need to declare and define a group of statements once
and that can be called and used whenever required.
❖ This saves both time and space.
C functions can be classified into two categories,
1. Library functions
2. User-defined functions
1. Library functions are those functions which are defined by C library, example printf(), scanf(), strcat()
etc. You just need to include appropriate header files to use these functions. These are already declared and
defined in C libraries.
2. User-defined functions are those functions which are defined by the user at the time of writing program.
Functions are made for code reusability and for saving time and space.
Function declaration
Syntax:
return-typefunction-name (parameter-list) ;
✓ A function must also be declared before its called.
✓ A function declaration tells the compiler about a function name and how to call the function.
A function declaration consist of 4 parts.
❖ return-type
❖ function name
❖ parameter list
❖ terminating semicolon
Function definition Syntax
return-typefunction-name (parameter-list)
{
function-body ;
}
The first line return-typefunction-name(parameter) is known as function header and the statement within
curly braces is called function body.
return-type
return type specifies the type of value(int,float,char,double) that function is expected to return to the program
calling the function.
function-name
function name specifies the name of the function.
Parameter-list
The parameter list declares the variables that will receive the data sent by calling program. They often
referred to as formal parameters. These parameters are also used to send values to calling program.
Function-body
The function body contains the declarations and the statement(algorithm) necessary for performing the
required task. The body is enclosed within curly braces { } and consists of three parts.
❖ local variable declaration.
❖ function statement that performs the tasks of the function.
❖ A return statement that return the value evaluated by the function.
Parameters in C Function
A c function may have 0 or more parameters. You can have any type of parameter in C program such as int,
float, char etc. The parameters are also known as formal arguments.
Calling a function in C
If a function returns any value, you need to call function to get the value returned from the function. The
syntax of calling a function in c programming is given below:
variable=function_name(arguments...);
variable: The variable is not mandatory. If function return type is void, you must not provide the variable
because void functions doesn't return any value.
function_name: The function_name is name of the function to be called.
arguments: You need to provide arguments while calling the C function. It is also known as actual
arguments.
Example:
#include <stdio.h>
#include <conio.h>
int cube(int n) //defining function
{
return n*n*n;
}
void main()
{
int result1=0,result2=0;
clrscr();
result1=cube(2); //calling function
result2=cube(3);
printf("%d \n",result1);
printf("%d \n",result2);
getch();
}
Output
8
27

RECURSION
The function which calls the same function, is known as recursive function.
Syntax:
recursionfunction()
{
recursionfunction();//calling self function
}
Example:
#include <stdio.h>
int sum(int n);
int main() {
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
Output:
Enter a positive integer: 10
sum = 55
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
STORAGE CLASSES
C storage classes define the scope (visibility) and lifetime of variables and/or functions within a C Program.
C storage classes define the scope (visibility) and lifetime of variables and/or functions within a C Program.
They precede the type that they modify.
We have four different storage classes in a C program −
• auto
• register
• static
• extern
auto:
The auto is a default storage class for all variables that are declared inside a function or a block. The
keyword "auto", which is optional, can be used to define local variables.
The scope and lifetime of auto variables are within the same block in which they are declared.
Example of auto Storage Class
{
int mark;
auto int total;
}
Register:
The register storage class is used to define local variables that should be stored in a register instead of RAM.
The register should only be used for variables that require quick access such as counters.
Static:
Static variables have the property of preserving their value even after they are out of their scope.They are
initialized only once and exist till the termination of the program.
The value of a static variable persists until the end of the program.
A static variable is declared using the static keyword.
static int i;
Ex:
#include <stdio.h>
void display();

int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}
Output:
6
11
extern:
The extern storage class is used to give a reference of a global variable that is visible to all program files.
Variables that are declared outside of all functions are known as external or global variables. They are
accessible from any function inside the program.
#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
++n;
display();
return 0;
}
void display()
{
++n;
printf("n = %d", n);
}
Output:
n=7
ARRAYS
An array is a collection of similar data elemetns. These elements have the same data type.
Elements are stored in consecutive memory locations and are referenced by an index (also known as
subscript).
Array Declaration:
To create an array, define the data type and specify the name of the array followed by square brackets [].
Syntax:
data_type array_name [size];
Array initialization:
We initialize the array along with its declaration. To insert values to it, use a comma-separated list, inside
curly braces.
Syntax:
data_type array_name [size] = {value1, value2, ... valueN};
ex:
int a[4 ] = {34, 56, 25, 67}
int a[ ] = {35, 67, 78, 34, 78};
we created an array variable holding 4 integer values.
Access the Elements of an Array
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Ex:
int a[ ] = {35, 67, 78, 34};
printf(“%d”, a[0]); //35
Update Array Element
We can update the value of an element at the given index by using the array subscript operator [ ] and
assignment operator =.
Syntax:
array_name[i] = new_value;
C Array Traversal
Traversal is the process in which we visit every element of the data structure. For C array traversal, we use
loops to iterate through each element of the array.
Array Traversal using for Loop
for (int i = 0; i < N; i++)
{
array_name[i];
}
Example:
// Program to take values of the array from the user and print the array
#include <stdio.h>
int main()
{
int a[5];
printf("Enter the values of an integer array:\n ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
scanf("%d", &a[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", a[i]);
}
return 0;
}
Enter the values of an integer array:
56
67
88
23
96
Displaying integers:
56
67
88
23
96

PASSING ARRAYS TO FUNCTIONS


We can pass an array to a function using below syntax:
1. return_type function(type arrayname[]) (OR)
2. return_type function(type arrayname[size])
example:

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>

float sum(float num[]);

int main() {

float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

result = sum(num);

printf("Result = %.2f", result);

return 0;

float sum(float num[])

float sum = 0.0;

for (int i = 0; i < 6; ++i)

sum += num[i];

return sum;

Output:
162.50
MULTIDIMENSIONAL ARRAY
A multidimensional array is basically an array of arrays.
Arrays can have any number of dimensions.
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
To create a 2D array of integers,
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
The first dimension represents the number of rows [2], while the second dimension represents the number of
columns [3]. The values are placed in row-order, and can be visualized like this:

Access the Elements of a 2D Array


To access an element of a two-dimensional array, you must specify the index number of both the row and
column.
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
printf("%d", matrix[0][2]); // 2
Change Elements in a 2D Array
To change the value of an element, refer to the index number of the element in each of the dimensions.
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead of 1


Loop Through a 2D Array
To loop through a multi-dimensional array, you need one loop for each of the array's dimensions.
The following example outputs all elements in the matrix array:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
output:
1
4
2
3
6
8
STRUCTURES
Structure in c is a user-defined data type that enables us to store the collection of different data types.
Each element of a structure is called a member.
Structures can store various information
The struct keyword is used to define the structure
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
.
data_type memberN;
};

Example:
struct employee
{
int id;
char name[20];
float salary;
};
Here,
struct is the keyword; employee is the name of the structure;
id, name, and salary are the members or fields of the structure.
Declaring structure variable
We can declare a variable for the structure so that we can access the member of the structure easily. There are
two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
1st way:
Example to declare the structure variable by struct keyword.
It should be declared within the main function.
struct employee
{ int id;
char name[50];
float salary;
};
Then write the following code within the main() function
struct employee e1, e2;
2nd way:
Another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Accessing members of the structure
There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)
Let's see the code to access the id member of p1 variable by. (member) operator.
p1.id
C Structure example
#include<stdio.h>
#include<conio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
void main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Raja");//copying string into char array
e1.salary=56000;
//store second employee information
e2.id=102;
strcpy(e2.name, "Rahim");
e2.salary=126000;
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);
//printing second employee information
printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
getch();
}
Output:
employee 1 id : 101
employee 1 name : Raja
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : Rahim
employee 2 salary : 126000.000000
Passing structures to functions
The passing of structure to the function can be done in two ways:
• By passing all the elements to the function individually.
• By passing the entire structure to the function.
Example:
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
return 0;
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
UNIONS
Like structure, Union in c language is a user-defined data type that is used to store the different type of
elements.
At once, only one member of the union can occupy the memory. In other words, we can say that the size of the
union in any instance is equal to the size of its largest element.

Defining union
The union keyword is used to define the union. Let's see the syntax to define union in c.
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define union for an employee in c.
union employee
{ int id;
char name[50];
float salary;
};
Example:
#include <stdio.h>
#include <string.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Rahim");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 1869508435
employee 1 name : Rahim
POINTERS
Pointers
The pointer in C language is a variable which stores the address of another variable. This variable can be of
type int, char, array, function, or any other pointer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol).
It is also known as indirection pointer used to dereference a pointer.
Example
int *a; //pointer to int
char *c; //pointer to char
Pointer Example
An example of using pointers to print the address and value is given below.

In the above figure, pointer variable stores the address of number variable, i.e., fff4.
The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Example Program:
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number; //stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefor
e printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a po
inter therefore if we print *p, we will get the value stored at the address contained by p.
return 0;
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Address Of (&) Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a
variable.
#include<stdio.h>
int main()
{
int number=50;
printf("value of number is %d, address of number is %u",number,&number);
return 0;
}
Output
value of number is 50, address of number is fff4
Swap two numbers without using the 3rd variable using Pointers
#include<stdio.h>
int main(){
int a=10,b=20,*p1=&a,*p2=&b;
printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
return 0;
}
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10

Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the
array. Base address i.e address of the first element of the array is also allocated by the compiler.
Suppose we declare an array arr
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be
stored as follows:

Here variable arr will give the base


address, which is a constant pointer pointing to the first element of the array, arr[0]. Hence arr contains the
address of arr[0] i.e 1000.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr
int *p;
p = arr;
// or,
p = &arr[0];
Now we can access every element of the array arr using p++ to move from one element to another.
Example
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character array with rows of varying
length.
char *name[3] = {"Adam","chris","Deniel"};
//Now lets see same array without using pointer
char name[3][20] = {"Adam","chris","Deniel"};

In the second approach memory wastage is more, hence it is preferred to use pointer in such cases.
When we define array of characters, a contiguos memory space is located equal to the maximum size of the
array, which is a wastage, which can be avoided if we use pointers instead.
Pointer to a Structure in C
We have already learned that a pointer is a variable which points to the address of another variable of any data
type like int, char, float etc. Similarly, we can have a pointer to structures, where a pointer variable can point to
the address of a structure variable. Here is how we can declare a pointer to a structure variable.
struct st {
int i;
float f;
}ref;
struct st *p = &ref;
Example:
#include <stdio.h>
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}
Accessing members using Pointer
To access members of structure using the structure variable, we used the dot . operator. But when we have a
pointer of structure type, we use arrow -> to access structure members.
Example
#include <stdio.h>
struct my_structure {
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"Computer Science", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
Output:
NAME: Computer Science
NUMBER: 35
RANK: 1

You might also like