22CS101-Problem Solving Using C++ Unit II
22CS101-Problem Solving Using C++ Unit II
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
22CS101
Problem Solving using C++
Department : CSE , IT
Batch / Year : 2023 – 2027 / I
Created by : Subject Handling Faculty
Date : 10.09.2023
1.CONTENTS
S.NO CONTENTS
1 Contents
2 Course Objectives
3 Syllabus
4 Course Outcomes
5 CO-PO Mapping
6 Lecture Plan
8 Lecture Notes
9 Assignments
11 Part-B Questions
15 Assessment Schedule
2.1 Pointers
2.2 Variables
2.3 Operators
2.4 Expressions
2.6 Functions
2.10 Recursion
2.11 Structures
2.12 Unions
2.13 Enumerations
2. Course objectives
To learn programming fundamentals in C.
To gain knowledge on pointers and functions.
To apply the principles of classes and objects
To develop a C++ application with object oriented concepts.
To use the functionalities of I/O operations, files build C++
programs using
PROBLEM SOLVING USING C++ L T P C
22CS101 3 0 2 4
(Lab Integrated)
OBJECTIVES:
• To learn programming fundamentals in C.
• To gain knowledge on pointers and functions.
• To apply the principles of classes and objects
• To develop a C++ application with object oriented concepts.
• To use the functionalities of I/O operations, files build C++ programs
using exceptions.
UNIT I PROGRAMMING FUNDAMENTALS 15
Computational thinking for Problem solving – Algorithmic thinking for problem Solving-
Building Blocks - Problem Solving and Decomposition –Dealing with Error – Evaluation.
Overview of C – Data types – Identifiers – Variables – Storage Class Specifiers – Constants
– Operators - Expressions – Statements – Arrays and Strings – Single-Dimensional – Two-
Dimensional Arrays – Arrays of Strings – Multidimensional Arrays.
UNIT II POINTERS AND FUNCTIONS 15
Pointers -Variables – Operators – Expressions – Pointers and Arrays – Functions - Scope Rules
– Function Arguments – return Statement – Recursion – Structures – Unions – Enumerations.
UNIT III CLASSES AND OBJECTS 15
Concepts of Object Oriented Programming – Benefits of OOP – Simple C++ program -
Classes and Objects - Member functions - Nesting of member functions - Private member
functions - Memory Allocation for Objects - Static Data Members - Static Member
functions - Array of Objects - Objects as function arguments - Returning objects - friend
functions – Const Member functions - Constructors – Destructors
OPERATOR OVERLOADING , INHERITANCE 15
UNIT IV
AND POLYMORPHISM
Operator Overloading - Overloading Using Friend functions – Inheritance – Types of inheritance
– Virtual Base Class - Abstract Class – Constructors in Derived Classes - member class:
nesting of classes.
Pointer to objects – this pointer- Pointer to derived Class - Virtual functions – Pure Virtual
Functions – Polymorphism
UNIT V I/O, FILES AND EXCEPTIONS 15
C++ Streams – Unformatted I/O - Formatted Console I/O – Opening and Closing File – File
modes - File pointers and their manipulations – Templates – Class Templates – Function
Templates - Exception handling.
Lab Exercises
PO PO PO PO PO PO PO PO PO PO PO PO PS PS PS
COs 1 2 3 4 5 6 7 8 9 10 11 12 O1 O2 O3
CO1 3 3 3 1 1 1 1 1 1 1
CO2 3 3 3 1 3 3 3 1 1 1
CO3 2 2 2 3 3 1 1 1 1 1
CO4 3 3 3 3 3 3 1 1 1 1
CO5 3 3 3 1 1 1 1 1 1 1
Lecture Plan
Unit 2 Pointers and Functions
Pointers &Variables
1
1 CO3 K2 Chalk & Talk
2
Operators & Expressions
1 CO3 K3 Chalk & Talk
Pointers and Arrays
3 1 CO4 K2 Chalk & Talk
4
Functions , Scope Rules
1 CO4 K2 Chalk & Talk
Function Arguments
5 Return Statement 1 CO3 K2 Chalk & Talk
6
Recursion
1 CO3 K2 Chalk & Talk
Structures
7
1 CO4 K3 Chalk & Talk
8
Unions
1 CO3 K2 Chalk & Talk
Enumerations
9 1
CO3 K2 Chalk & Talk
Activity Based Learning
Learn by questioning
DEFINITION
Initializing Pointers:
When (&) is placed before the name of a variable, the address-of
operator returns the address of the variable.
Syntax
pointer
hello guys = &variable;
Example
int *p, a=10;
p = &a;
2.3 Pointer operators
• C provides two special operators known as pointer operators.
* stands for “value at address” and it is used to access the value at a location by
means of its address.
Ex:
int *p, a=10;
p=&a;
printf(“%d”,*p);
Example
#include<stdio.h>
void main()
{
int arr[2][2] = {11,22,33,44};
int i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
printf("%d \t ", * ( * ( arr+i) + j ) );
}
}
}
hello guys
❖ Output
❖ 11 22 33 44 55
Array of pointer and Initialization of Pointer Arrays
Array of pointers can be declared as
Syntax:
datatype *array_name[size];
It sets each pointer in one array to point to an integer value and then prints the values
of the integers by dereferencing the pointers
Example
1. int *a[5]; In this array of pointer ‘a’, we can store 5 pointer values.
2. int x=45,y=67,z=89;
int *a[5];
a[0]=&x;
a[1]=&y;
a[2]=&z;
3. int x=45,y=67,z=89;
int *a[5]={&x, &y, &z};
hello guys
Program
#include<stdio.h>
void main()
{
int *p[3];
int a = 10, b = 20, c = 50, i;
p[0] = &a;
p[1] = &b;
p[2] = &c;
for(i = 0; i < 3; i++)
{
printf("Address = %u\t Value = %d\n", p[i], *p[i]);
}
}
Pointer Arithmetic (or) Arithmetic operations on Pointers
1. Addition operation
❖ An integer value can be added to the pointer variable which is commutative.
❖ That is, ptr+1 is same as 1+ptr
Example
hello guys
int n=10,*ptr;
ptr=&n;
printf(“%u”,ptr); --- 2504
printf(“%u”,ptr+1); --- 2506
2.Subtraction operation
❖ An integer value can be added to the pointer variable which is not commutative. That is,
ptr-1 is not same as 1-ptr
Example
int n=10,*ptr;
ptr=&n;
printf(“%u”,ptr); ----2504
printf(“%u”,ptr-1); ---- 2502
3.Increment operation
❖ Increment operation is applied to the operand of pointer type.
❖ It can be pre-increment or post-increment.
Example
Pre-increment Post-increment
int n=10,*a,*b; int n=10,*a,*b;
a=&n; a=&n;
b=++a; b=a++;
printf(“%u”,a); - 4206 printf(“%u”,a); ---5218
printf(“%u”,b); - 4208 printf(“%u”,b); ---5218
4.Decrement operation
❖ Decrement operation is applied to the operand of pointer type.
❖ It can be pre-decrement or post-decrement.
Example
Pre-decrement Post-decrement
int n=10,*a,*b; int n=10,*a,*b;
a=&n; a=&n;
hello guys
b=--a; b=a--;
printf(“%u”,a); - 6220 printf(“%u”,a); ---4620
printf(“%u”,b); - 6218 printf(“%u”,b); --- 4620
5.Comparison operation
❖ A pointer can be compared with a pointer of the same type.
❖ The comparison of operator is meaningful only when it points a same array.
Example
int *p1,*p2; p1<p2;
Character Pointers and Functions
Pointer with character array
❖ A string contains a sequence of characters which are stored in memory continuously like
arrays which can be accessed by a pointer of type char.
Example
char st[10]=”GOOD”;
char *p;
p=st;
printf(“%s”,p); ---- GOOD
Example
#include<stdio.h>
void main()
{
int a=10,*b,**c;
b=&a;
c=&b; // Output
printf("Value of a is %d\n",a); //Value of a is 10
printf("Value of b is %u\n",b); //Value of b is 3532047324
printf("Value of c is %u\n",c); //Value of c is 3532047328
printf("Address of a is %u\n",&a); //Address of a is 3532047324
printf("Address of b is %u\n",&b); //Address of b is 3532047328
printf("Address of c is %u\n",&c); //Address of c is 3532047336
printf("Value of a is %d\n",*b); //Value of a is 10
printf("Address of a is %u\n",*c); //Address of a is 3532047324
printf("Value of a is %d\n",*(&a)); //Value of a is 10
printf("Value of a is %d\n",**c); //Value of a is 10
}
hello guys
Pointer to functions (or ) Function Pointer
❖ In C, like normal data pointers (int *, char *, etc), we can have pointers to
functions. Following is a simple example that shows declaration and function call
using function pointer.
Example
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a); // Value of a is 10
}
int main()
{
void (*fun_ptr)(int) = &fun;
(*fun_ptr)(10);
return 0;
}
Following are some interesting facts about function pointers.
1)Unlike normal pointers, a function pointer points to code, not data. Typically a
function pointer stores the start of executable code.
2) Unlike normal pointers, we do not allocate de-allocate memory using
function pointers.
3) A function’s name can also be used to get functions’ address. For example,
in the below program, we have removed address operator ‘&’ in assignment.
We have also changed function call by removing *, the program still works.
Example
hello guys
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
void (*fun_ptr)(int) = fun; // & removed
fun_ptr(10); // * removed
return 0;
}
Pointer to Structure:
we can define pointers to structures in the same way as we define pointer to any
other variable:
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the '&'; operator before the
structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use
the → operator as follows −
struct_pointer->title;
#include <stdio.h>
#include <string.h>
struct Books
hello guys
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBook( struct Books *book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, “Dennis Ritche");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
printBook( &Book1 );
printBook( &Book2 );
return 0;
}
Like we have array of integers, array of pointers etc, we can also have
array of structure variables. And to use the array of structure variables efficiently, we
use pointers of structure type. We can also have pointer to a single structure variable,
but it is mostly used when we are dealing with array of structure variables.
#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;
hello guys
Accessing Structure Members with 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.
#include <stdio.h>
struct student
{
char name[20];
int number;
int rank;
};
int main()
{
struct student variable = {“Gokul", 35, 1};
struct student *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
Output:
NAME: Gokul
NUMBER: 35
RANK: 1
2.6 Functions
Introduction
Functions break large computing tasks into smaller ones and called a
number of times whenever required instead of starting over from scratch. Functions
hide details of operation from parts of the program and provide abstraction.
C programs consist of many small functions rather than a few big ones. A
program may reside in one or more source files. Source files may be compiled
separately and loaded together, along with previously compiled functions from
libraries.
Function declaration and definition: It is possible to declare the type of
arguments when a function is declared. Function declaration consists of the return
type of the function, name of the function, and list of arguments with their types.
Function declaration is otherwise called as function prototype or function signature.
Each function declaration or prototype has the form (general syntax):
return-type function-name(comma separated list of argument types);
function.
int z;
z= x+y;
return z;
Type of functions:
Based on whether it is created by user or already available in
language library
A. In-Built or Built-In function (Already written by someone and is available in the
system Library
B. User defined function. (Created by the user)
Built in Functions
Built in Math Functions
“math.h” header files include all the math function, which is used for
all arithmetic and logical operation.
Function Description
A program can have same name for local and global variables but the value of local
variable inside a function will take preference. Here is an example:
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}
When the above code is compiled and executed, it produces the following result
value of g = 10
2.8 Function Arguments
Types of Function Prototype:
Based on the return type and argument type
While calling the function, there are no arguments passed to the called
#include<stdio.h>
void add();
void main()
add();
void add()
int a,b,c;
scanf("%d %d",&a,&b);
c=a+b;
printf("Sum of 2 numbers=%d",c);
}
Type B:Functions with No Arguments with return Value:
The add function is not taking any argument ,but the inputs are
received as local variables inside of the add() function definition
and it is returning the value.
#include<stdio.h>
int add(void);
void main()
{
int c;
c=add();
printf("sum of two numbers=%d",c);
}
int add() //function definition
{
int a,b,d;
printf("Enter the values");
scanf("%d %d",&a,&b);
return a+b;
}
Output:
Enter the values
5
6
sum of two numbers=11
Type C: Functions with arguments, with out return value
The function is taking as input argument, but it does not return any
value , because return type is void.
#include<stdio.h>
void add(int,int);
void main()
{ int a,b;
printf("Enter the values");
scanf("%d %d",&a,&b);
add(a,b); //a,b-actual arguments
}
void add(int x, int y) //a,b-formal arguments
{
int c;
c=x+y;
printf("Sum of 2 numbers=%d",c);
}
Output:
Enter the values
5
6
Sum of two numbers=11
Type D: Functions with arguments, with return values
A function is called with arguments and returns a result to the calling
function.
#include<stdio.h>
int add(int,int);
void main()
{
int a,b,c;
printf("Enter the values");
scanf("%d %d",&a,&b);
c=add(a,b);
printf("sum of two numbers=%d",c);
}
int add(int a,int b)
{ int c;
c=a+b;
return c;
}
Output:
Enter the values
5
6
sum of two numbers=11
Call by value and Call by reference:
Functions can be invoked in two ways: (or)
Parameter Passing methods in C
Call by Value (or) Pass by value
Call by Reference. (or) Pass by Reference
pass by value (or) call by value:
1.In call by value method, the value of the actual parameters is copied into the
formal parameters.
2.In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
Swapping of two numbers
#include <stdio.h>
void swap(int, int);//function declaration
void main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping x = %dy = %d", x, y);
swap(x, y);
}
void swap(int a, int b)
{
int temp;
temp = b;
b = a;
a = temp;
printf("\n After swapping = %d %d",a,b);
}
Output
Enter the value of x and y
10
5
Before Swapping
x = 10
y=5
After swapping a and b is 5 10
Pass by reference(address) (or) Call by reference.
* In call by reference, the address of the variable is passed into the function call as
the actual parameter.
* The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
* In call by reference, the memory allocation is similar for both formal parameters
and actual parameters.
* All the operations in the function are performed on the value stored at the address
of the actual parameters, and the modified value gets stored at the same address.
Program:
#include <stdio.h>
void swap(int *, int *);
void main()
{
int x = 10;
int y = 20;
printf("Before swapping a = %d, b = %d\n",x,y);
swap(&x,&y);
printf("After swapping a = %d, b = %d\n",x,y);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values a = %d, b = %d\n",*a,*b);
}
Differences between call by value and call by reference :
Eg: Eg:
void swap(int, int); void swap(int *, int *);
The expression will be converted to the return type of the function if necessary. Parentheses
are often used around the expression, but they are optional.
The calling function is free to ignore the returned value. Furthermore, there need to be no
expression after return; in that case, no value is returned to the caller. Control also returns to
the caller with no value when execution “falls off the end'' of the function by reaching the
closing right brace.
In any case, if a function fails to return a value, its “value'' is certain to be
garbage.
The main() should return an integer. Therefore we are always writing the return statement
at last in main as follows:
return 0;
This indicates that all statements in the main function are executed perfectly without any
error to the compiler.
2.10 Recursion:
A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called as recursive function.
Using recursive algorithm, certain problems can be solved quite easily. Example of
such problem is Towers of Hanoi
In the recursive program, the solution to the base case is provided and the
solution of the bigger problem is expressed in terms of smaller problems.
Recursion is a programming technique that allows the programmer to express
operations in terms of themselves. It takes the form of a function that calls itself.
A useful way to think of recursive functions is to imagine them as a process being
performed where one of the instructions is to "repeat the process".
This makes it sound very similar to a loop because it repeats the same code, and
in some ways it is similar to looping. On the other hand, recursion makes it easier
to express ideas in which the result of the recursive call is necessary to complete
the task.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
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.
Factorial of a number:
#include <stdio.h>
int factorial( int i)
{
if(i <= 1)
return 1;
else
return i * factorial(i - 1);
}
int main()
{
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
Output:
Factorial of 12 is 479001600
Program for Fibonacci Series using recursion :
#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
return 0;
else if(i == 1)
return 1;
else
return fibonacci(i-1) + fibonacci(i-2);
}
int main()
{
int i;
for (i = 0; i < 6; i++)
{
printf("%d\t\n", fibonacci(i));
}
return 0;
}
Output:
0
1
1
2
3
5
Sum of Natural Numbers Using Recursion:
#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)
return n + sum(n-1);
else
return n;
}
Output:
Enter a positive integer:3
sum = 6
2.11 Structures:
Defining a structure
struct keyword is used to define a structure. struct defines a new data type
which is a collection of primary and derived data types.
Syntax:
struct structurename
{
datatype1 member1;//member variable 1 ;
datatype2 member2;//member variable 2 ;
datatype3 member3;//member variable 3 ;
...
}structure_variables;
As in the syntax above, we start with the struct keyword, then it's optional to
provide your structure a name, we suggest you to give it a name, then inside the
curly braces, we have to mention all the member variables, which are nothing
but normal C language variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables,
again this is optional.
Note: The closing curly brace in the structure type declaration must be
followed by a semicolon (;).
Example of Structure
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
};
Here struct Student declares a structure to hold the details of a student which
consists of 4 data fields, namely name, age, branch and gender. These fields
are called structure elements or members.
Each member can have different data type, like in this case, name is an array
of char type and age is of int type etc. Student is the name of the structure
and is called as the structure tag.
Declaring Structure Variables
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
};
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student.
Accessing Structure Members
Example:
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
};
int main()
{
struct Student s1;
s1.age = 18;
strcpy(s1.name, "Viraaj");
printf("Name of Student 1: %s\n", s1.name);
hello printf("Age
guys of Student 1: %d\n", s1.age);
return 0;
}
Output:
Name of Student 1: Viraaj
Age of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", s1.name);
scanf(" %d ", &s1.age);
Structure Initialization
Like a variable of any other data type, structure variable can also be initialized at
compile time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
We can pass a structure as a function argument just like we pass any other
variable or an array as a function argument.
Example:
#include<stdio.h>
hello guys
struct Student
{
char name[10];
int roll;
};
void show(struct Student st);
void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}
void show(struct Student st)
{
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
}
Array of Structures
We can also declare an array of structure variables. in which each element of the
array will represent a structure variable.
Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the
array emp is of type Employee.
#include<stdio.h>
struct Employee
{
char ename[10];
int sal;
hello guys};
struct Employee emp[5];
int i, j;
void input()
{
for(i = 0; i < 3; i++)
{
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
Example:
struct Student
{
char[30] name;
int age;
hello struct
guys Address
{
char[50] locality;
char[50] city;
int pincode;
}addr;
};
Pointer to Array of Structures in C
Like we have array of integers, array of pointers etc, we can also have
array of structure variables. And to use the array of structure variables efficiently,
we use pointers of structure type. We can also have pointer to a single structure
variable, but it is mostly used when we are dealing with array of structure variables.
#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;
int main()
{
hello guys
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the
structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
int main()
{
struct node ob1; // Node1
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
ob1.link = &ob2;
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
Output:
30
40
2.12 Unions:
The only difference is in terms of storage. In structure each member has its
own storage location, whereas all members of union uses a single shared
memory location which is equal to the size of its largest data member.
This implies that although a union may contain many members of different types, it
cannot handle all the members at the same time. A union is declared using the union
keyword.
union item
{
int m;
float x;
char c;
}It1;
This declares a variable It1 of type union item. This union contains three members
each with a different data type. However only one of them can be used at a time. This
is due to the fact that only one location is allocated for all the union variables,
irrespective of their size. The compiler allocates the storage that is large enough to
hold the largest variable type in the union.
In the union declared above the member x requires 4 bytes which is largest amongst
hello guysfor a 16-bit machine. Other members of union will share the same
the members
memory address.
An Example for Union:
#include <stdio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch = 'z';
printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);
return 0;
}
Output:
-26426
20.1999
Z
hello guys
Differences between Arrays and Structures:
Array Structures
Array is a collection of homogeneous Structure is a collection of heterogeneous
data items data items.
Array name points to the first element Structure name does not point to the first
in that array so, array name is a element in that structure so, structure name
pointer. is not a pointer.
Example:
#include<stdio.h>
enum SWITCH { off, on };
void main()
{
enum SWITCH s1=on;
enum SWITCH s2=s1;
enum SWITCH s3=off;
printf(“The value of s1 is %d”,s1); // s1=1
printf(“The Value of s2 is %d”,s2); // s2=1
Printf(“ The Value of s3 is %d”, s3); // s3=0
}
The enumerated data type is a user defined type based on the standard integer
type.
enumeration consists of a set of named integer constants. In an enumerated type
, each integer value is assigned an identifier.
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}
Output
Day 4
Assignment Questions
It sets each pointer in one array to point to an integer value and then prints the
values of the integers by dereferencing the pointers
Example
1. int *a[5]; In this array of pointer ‘a’, we can store 5 pointer values.
2. int x=45,y=67,z=89;
int *a[5];
a[0]=&x;
a[1]=&y;
a[2]=&z;
12. Write a program to find the sum of two nos using pointers.
#include<stdio.h>
main()
{
int a,b,c; Output:
int *p1,*p2;
printf(“\nEnter two integer values:”); // Enter two integer values: 100 200
scanf(“%d%d”,&a,&b);
p1=&a;
p2=&b;
c=*p1 + *p2; // *ptr1 -> value of a and *ptr2 -> value of b
printf(“\n Sum is = %d”,c); // ------- Sum is = 300
}
#include <stdio.h>
int main()
int x, y;
scanf("%d%d",&x,&y);
swap(&x, &y);
return 0;
int temp;
temp = *b;
*b = *a;
*a = temp;
}
18.Define Structure:
Structure is a user-defined data type, which allows us to combine data of
different types together. Structure helps to construct a complex data type which is
more meaningful. It is somewhat similar to an Array, but an array holds data of
similar type only. But structure on the other hand, can store data of any type,
which is practical more useful.
In structure, data is stored in form of records
Syntax:
struct structurename
{
datatype1 member1;
datatype2 member2;
…….
datatype n member;
}structure_variables;
19. Nested Structures
Nesting of structures, is also permitted in C language. Nested structures
means, that one structure has another stucture as member variable.
Example:
struct Student
{
char name[30];
int age;
struct Address
{
char[50] locality;
char[50] city;
int pincode;
}addr;
};
20.Define Union :
Union is a user defined data type which allows us to combine data of different
types together. Union is similar to structure but the storage is the different.
In Union all the members are sharing the common memory.
Syntax:
union unionname
{
datatype1 member1;
datatype2 member2;
…..
datatype n member;
}union variables.
PART – B Questions
1. Explain pointer arithmetic in detail.
2. Write a C program for sorting of a set of numbers using pointers.
3. Write a C code for sum of first N natural numbers using recursion.
4.Write a c Program for Binary search using recursion.
5..Write a C Program for arranging the elements into ascending order.
6. Explain the function prototypes in detail.
7. Write a C program for matrix multiplication using function.
8.What are the parameter passing methods in C.
9.Write a C program for Student database.
10.Write a C program for Employee database.
11.What are differences between structure and union.
12.Write a C program for GCD of 2 numbers using function.
13. Write a C program for Binary search using recursion.
14.Write a C program for Generating Fibonacci series using recursion.
15.Write a C Program for finding grade of 5 different subjects using recursion.
Supportive online courses
❖ C – Sololearn
❖ https://www.coursera.org/
❖ https://www.udemy.com/
❖ https://unacademy.com/
❖ https://www.sololearn.com/
❖ https://www.tutorialspoint.com/cprogramming/index.htm
❖ https://www.w3schools.in/c-tutorial/
❖ https://www.geeksforgeeks.org/c-language-set-1-introduction/
❖ https://www.programiz.com/c-programming
Real Time Applications
CONTENT BEYOND SYLLABUS
Bit-fields:
Bit Fields allow the packing of data in a structure. This is especially useful when
memory or data storage is at a premium. Typical examples include:
Packing several objects into a machine word. e.g. 1 bit flags can be compacted.
Reading external file formats -- non-standard file formats could be read in, e.g.,
9-bit integers.
struct packed_struct
{
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type
and a 9-bit my_int.
The arguments passed from command line are called command line arguments.
These arguments are handled by main() function.
To support command line argument, you need to change the structure of main()
function as given below.
Here, argc counts the number of arguments. It counts the file name as the first
argument.
The argv[] contains the total number of arguments. The first argument is the
file name always.
Example
Let's see the example of command line arguments where we are passing one
argument with file name.
#include <stdio.h>
void main(int argc, char *argv[] )
{
printf("Program name is: %s\n", argv[0]);
if(argc < 2)
{
printf("No argument passed through command line.\n");
}
else
{
printf("First argument is: %s\n", argv[1]);
}
}
Output:
$ cc program.c
$ ./a.out hello
Text Books:
1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH, 2015. (Unit 1 & 2)
2. E Balagurusamy,”Object Oriented Programming with C++”, 4th Edition, Tata
McGraw-Hill Education, 2008. (Unit 3, 4 & 5)
Reference Books:
1. Nell Dale, Chip Weems, “Programming and Problem Solving with C++”, 5th Edition,
Jones and Barklett Publishers, 2010.
2. John Hubbard, “Schaum's Outline of Programming with C++”, MH, 2016.
3. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
4. ISRD Group, “Introduction to Object-oriented Programming and C++”, Tata McGraw-
Hill Publishing Company Ltd., 2007.
5. D. S. Malik, “C++ Programming: From Problem Analysis to Program Design”, Third
Edition, Thomson Course Technology, 2007.
6.https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_01297200240671948
837_shared/overview
Mini Project Suggestions
3.Telephone Directory.
Thank you
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.