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

22CS101-Problem Solving Using C++ Unit II

This document provides information about a course on problem solving using C++. It contains a disclaimer, course objectives, syllabus, course outcomes mapping, and lecture plan for the unit on pointers and functions. The objectives are to learn programming fundamentals in C, gain knowledge on pointers and functions, apply object-oriented concepts, develop C++ applications, and use I/O operations and files. The unit covers topics like pointers, variables, operators, expressions, pointers and arrays, functions, scope rules, function arguments, return statements, and recursion.

Uploaded by

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

22CS101-Problem Solving Using C++ Unit II

This document provides information about a course on problem solving using C++. It contains a disclaimer, course objectives, syllabus, course outcomes mapping, and lecture plan for the unit on pointers and functions. The objectives are to learn programming fundamentals in C, gain knowledge on pointers and functions, apply object-oriented concepts, develop C++ applications, and use I/O operations and files. The unit covers topics like pointers, variables, operators, expressions, pointers and arrays, functions, scope rules, function arguments, return statements, and recursion.

Uploaded by

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

Please read this disclaimer before proceeding:

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

7 Activity Based Learning

8 Lecture Notes

9 Assignments

10 Part- A Questions & Answers

11 Part-B Questions

12 Supportive Online Courses

13 Real Time Applications

14 Content beyond the Syllabus

15 Assessment Schedule

16 Prescribed Text books & Reference Books

17 Mini Project Suggestions


UNIT –II Pointers and Functions
Chapter No CONTENTS

2.1 Pointers

2.2 Variables

2.3 Operators

2.4 Expressions

2.5 Pointers and Arrays

2.6 Functions

2.7 Scope rules

2.8 Function Arguments

2.9 return Statement

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

1. Write C/C++ programs for the following:


a. Find the sum of individual digits of a positive integer.
b. Compute the GCD of two numbers.
c. Find the roots of a number (Newton‘s method)
2. Write C/C++ programs using arrays:
a. Find the maximum of an array of numbers.
b. Remove duplicates from an array of numbers.
c. Print the numbers in an array after removing even numbers.
3. Write C/C++ programs using strings:
a. Checking for palindrome.
b. Count the occurrences of each character in a given word.
4. Generate salary slip of employees using structures and pointers. Create a structure
Employee with the following members:
EID, Ename, Designation, DOB, DOJ, Basicpay
Note that DOB and DOJ should be implemented using structure within structure.
5. Compute internal marks of students for five different subjects using structures and
functions.
6. Write a program Illustrating Class Declarations, Definition, and Accessing Class
Members.
7. Program to illustrate default constructor, parameterized constructor and copy constructors
8. Write a Program to Demonstrate the i) Operator Overloading. ii) Function Overloading.
9. Write a Program to Demonstrate Friend Function and Friend Class.
10. Program to demonstrate inline functions.
11. Program for Overriding of member functions.
12. Write C++ programs that illustrate how the following forms of inheritance are supported:
a) Single inheritance b)Multiple inheritance c)Multi level inheritance d)Hierarchical
inheritance
13. Program to demonstrate pure virtual function implementation.
14. Count the number of account holders whose balance is less than the minimum
balance using sequential access file.
15. Write a Program to Demonstrate the Catching of all Exceptions.
16. Mini project.
TOTAL: 45+30 = 75
PERIODS
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)
REFERENCES:
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_01297200240671948837_shared/overview
4.Course Outcomes
CO1: Solve problems using basic constructs in C.

CO2: Implement C programs using pointers and functions.

CO3: Apply object-oriented concepts and solve real world problems.

CO4: Develop C++ programs using operator overloading and polymorphism.

CO5: Implement C++ programs using Files and exceptions.


CO – PO Mapping
POs and PSOs

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

S. No. Propose Actual Pertainin Taxonom Mode of


Topic
No. of d Lecture g y Delivery
Perio Date Date CO Level
ds

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 solving problems – Tutorial Sessions can be conducted

- Tutorial sessions available in Skillrack


for practice

Learn by questioning

Learn by doing hands-on


Lecture Notes

UNIT –II POINTERS AND FUNCTIONS

Pointers – Variables – Operators – Expressions- Pointers and


Arrays –Functions – Scope Rules –Function Arguments-return statement –
Recursion – Structures- Unions –Enumerations.
2.1 Pointers

DEFINITION

❖ A pointer is a variable which contains the address ( in memory)of another variable.


❖ A pointer is a variable which points or represents a storage location in memory
(RAM) of a data item, such as a variable or an array.
❖ The memory address is the location where program instructions and data are stored,
pointers can be used to access and manipulate data stored in the memory.
❖ A pointer is a variable that stores the address of another variable.
A pointer can be incremented/decremented,
❖ i.e., to point to the next / previous memory location.
❖ The purpose of pointer is to save memory space and achieve faster
execution time.

2.2 Pointer variable


A pointer is a numeric variable, it must be declared before it can be
used.
Syntax
datatype *ptrname;
Here, * is the indirection operator,
& it indicates that ptrname is a pointer to datatype.
Example
int *p1,*p2; Here a,b are pointers to type integer.
char *ch1, *ch2; Here ch1 and ch2 both are pointers to type char

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.

They are & - Address of operator / referencing operator


* - Value at operator / indirection operator / dereferencing operator
& stands for “Address of” and it is used to retrieve the address of a variable.

* 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);

2.4. Pointers and Function Arguments

❖ Pointer as a function parameter is used to hold addresses of arguments passed


during function call. This is also known as call by reference. When a function is called
by reference any change made to the reference variable will effect the original
variable.
Example
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int a,b;
scanf(“%d%d”,&a,&b);
swap(&a, &b);
printf("After Swapping:\ %d %d”,a,b);
hello guys return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
2.5 Pointers and Arrays

❖ Values in an array can be accessed efficiently using pointers.


❖ Array elements are always stored in consecutive memory locations according to the
size of the array.
❖ The base address of an array is assigned to the pointer.
❖ Then the pointer will be moved to other elements in the array using pointer address
arithmetic.
❖ A pointer when incremented, always points to a location after skipping the number of
bytes required for the data type pointed to it.
❖ First element address is called as base address.
Pointer to 1D array
Example
int a[5]={10,20,30,40,45};
int *b;
b=&a[0];
Here, ‘b’ is a pointer variable which holds the base address of the array ‘a’. That
is, b=a[0];
The array is in integer type, the integer will have 2 bytes and hence the address
of the next element is incremented by 2.
Example
#include<stdio.h>
void main()
{
int a[2]={10,20};
hello guys int *p;
p=&a[0];
printf(“%d”,*p); ---------------------- 10
printf("%d\n",++*p); --------- 11
printf("%u\n",p); -----------------------65522
printf("%u\n",++p); -----------------------65524
}
Reading / writing values in 1D array using pointer
To read the values in an array, the base address of an array is assigned to the
pointer and it is then incremented.

Read the values of 1D array using pointer


for(i=0;i<10;i++)
scanf("%d",(x+i));
When this has been executed, user has to enter 10 values.
The base address of an array x with the subscript I is used to refer and store the values
in the array m different memory locations.

Print the values of 2D array using pointer


for(i=0;i<10;i++)
printf("%d",*(x+i));
The indirection operator is used to access the value in that memory location.

Program – Reading and Writing in an array using pointer


#include<stdio.h>
void main()
{
int x[10],i;
printf(“Enter the value of n “);
scanf(“%d”,&n);
printf(“Enter five numbers \n”);
for(i=0;i<5;i++)
scanf("%d",(x+i));
hello guys
printf("Elements are\n");
for(i=0;i<5;i++)
printf("%d",*(x+i));
}
Pointer to 2D array

Read the values of 2D array using pointer


for(i=0;i<10;i++)
for(j=0;j<10;j++)
scanf("%d",((x+i)+j));

Print the values of 2D array using pointer


for(i=0;i<10;i++)
for(j=0;j<10;j++)
printf("%d", *(*(ax+i)+j));

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};

Address = 1548824464 Value = 10


Address = 1548824468 Value = 20
Address = 1548824472 Value = 50

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

❖ Arithmetic operations can be applied to pointers in a restricted form.


❖ When arithmetic operators are applied on pointers, the outcome of the operation is
governed by pointer arithmetic.
The following are the list of operation on pointer variable:
1. Addition operation.
2. Subtraction operation
3. Increment operation
4. Decrement operation
5. Comparison operation

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

Character Pointers and Functions

Character array can be passed as a function argument to function definition.


Example
void strcpy(char s[], char t[])
{
int i;
for(i = 0; t[i] != '\0'; i++)
s[i] = t[i];
s[i] = '\0';
}
Note that we have to manually append the '\0' to s after the loop. Note that in doing so
we depend
The same way character pointer also passed as argument to the function definition.
Here is a similar function, using pointer notation:
hello guys
void strcpy(char *s, char *t)
{
while(*t != '\0')
*s++ = *t++;
*s = '\0';
}
Pointer to Pointer

❖ Pointer is a variable that contains the address of another variable.


❖ Similarly, another pointer variable can store the address of this pointer variable.

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;

Let us re-write the above example using structure pointer.

#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;
}

void printBook( struct Books *book )


{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
Output:
hello title
Book guys: C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
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;

struct Book b[10]; //Array of structure variables


struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}

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);

Each function definition has the form (general syntax):


return-type function-name(argument declarations)
{
declarations and statements
}

If the return type is omitted, int is assumed.


Note: The default return type of a function in C is int.
Example: Write a function that adds two numbers and returns the sum to the calling

function.

The function declaration would be:

int addition(int, int);

The function definition would be:

int addition(int x, int y)

int z;

z= x+y;

return z;

This function can be rewritten as follows:


int addition(int x, int y)
{
return (x+y);
}
The full program may look like:
#include<stdio.h>
int addition(int,int);
int main()
{
int a,b,c;
printf(“Enter 2 integers to be added\n”);
scanf(“%d%d”,&a,&b);
c=addition(a,b);
printf(“The sum is : %d \n”,c);
return 0;
}
int addition(int x, int y)
{
return (x+y);
}
Another example is to write a program for finding the factorial of a given number
using a function.
int fact (int n)
{
int f=1, i;
for (i=1; i<=n; i++)
f =f * i;
return f;
}

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

This function returns the nearest integer which is less


floor ()
than or equal to the argument passed to this function.

round ( ) This function returns the nearest integer value

This function returns nearest integer value which is


ceil ( ) greater than or equal to the argument passed to this
function.

sin ( ) This function is used to calculate sine value.

cos ( ) This function is used to calculate cosine.

cosh ( ) This function is used to calculate hyperbolic cosine.

This function is used to calculate the exponential “e” to


exp ( )
the xth power.

tan() This function is used to calculate tangent

tanh ( ) This function is used to calculate hyperbolic tangent.

sinh ( ) This function is used to calculate hyperbolic sine.

log ( ) This function is used to calculates natural logarithm.

log10 ( ) This function is used to calculates base 10 logarithm.


Scientific Calculator Using Built in Math Functions
#include<stdio.h>
#include<math.h>
void main()
{
int choice, i, a, b;
float x, y, result;
do {
printf(“\nSelect your operation (0 to exit):\n”);
printf(“1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n”);
printf(“5. Square root\n6. X ^ Y\n7. X ^ 2\n8. X ^ 3\n”);
printf(“9. 1 / X 10. X ^ (1 / Y)11. X ^ (1 / 3)\n”);
printf(“12. 10 ^ X 13. X! 14. %\n15. log10(x)\n16. Modulus\n”);
printf(“17. Sin(X)\n18. Cos(X)\n19. Tan(X)\n20. Cosec(X)\n”);
printf(“21. Cot(X)\n22. Sec(X)\n”);
printf(“Choice: “);
scanf(“%d”, &choice);
if(choice == 0) exit(0);
switch(choice) {
case 1://integer constant or character constant
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x + y;
printf(“\nResult: %f”, result);
break;
case 2:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x – y;
printf(“\nResult: %f”, result);
break;
case 3:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x * y;
printf(“\nResult: %f”, result);
break;
case 4:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x / y;
printf(“\nResult: %f”, result);
break;
case 5:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sqrt(x);
printf(“\nResult: %f”, result);
break;
case 6:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = pow(x, y);//pow(2,3) =8
printf(“\nResult: %f”, result);
break;
case 7:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 2);
printf(“\nResult: %f”, result);
break;
case 8:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 3);
printf(“\nResult: %f”, result);
break;
case 9:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, -1);
printf(“\nResult: %f”, result);
break;
case 10:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = pow(x, (1/y));
printf(“\nResult: %f”, result);
break;
case 11:
printf(“Enter X: “);
scanf(“%f”, &x);
y = 3;
result = pow(x, (1/y));
printf(“\nResult: %f”, result);
break;
case 12:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(10, x);//pow(10,3)=1000
printf(“\nResult: %f”, result);
break;
case 13:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1;
for(i = 1; i <= x; i++) {
result = result * i;
}
printf(“\nResult: %.f”, result);
break;
case 14:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = (x * y) / 100;
printf(“\nResult: %.2f”, result);
break;
case 15:
printf(“Enter X: “);
scanf(“%f”, &x);
result = log10(x);
printf(“\nResult: %.2f”, result);
break;
case 16:
printf(“Enter X: “);
scanf(“%d”, &a);
printf(“\nEnter Y: “);
scanf(“%d”, &b);
result = a % b; //4 % 7= 4
printf(“\nResult: %d”, result);
break;
case 17:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sin(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 18:
printf(“Enter X: “);
scanf(“%f”, &x);
result = cos(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 19:
printf(“Enter X: “);
scanf(“%f”, &x);
result = tan(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 20:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / (sin(x * 3.14159 / 180));
printf(“\nResult: %.2f”, result);
break;
case 21:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / tan(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 22:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / cos(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
default:
printf(“\nInvalid Choice!”);
}
} while(choice);
}
2.7 Scope rules:
A scope in any programming is a region of the program where a defined
variable can have its existence and beyond that variable it cannot be accessed.
There are three places where variables can be declared in C programming language
Inside a function or a block which is called local variables.
Outside of all functions which is called global variables.
In the definition of function parameters which are called formal parameters.
Local Variables and Global variables:
Local Variables:
Variables that are declared inside a function or block are called local
variables. They can be used only by statements that are inside that function or block
of code. Local variables are not known to functions outside their own. The following
example shows how local variables are used. Here all the variables a, b, and c are
local to main() function.
#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the
program. Global variables hold their values throughout the lifetime of your program
and they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global
variable is available for use throughout your entire program after its declaration. The
following program show how global variables are used in a program.
Global variables are defined outside a function, usually on top of the
program. Global variables hold their values throughout the lifetime of your program
and they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global
variable is available for use throughout your entire program after its declaration. The
following program show how global variables are used in a program.

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

A. Functions with no arguments, with out return value


B. Functions with no arguments, with return value
C. Functions with arguments, with out return value
D. Functions with arguments, with return values

Type A: Functions with no arguments, with out return value

While calling the function, there are no arguments passed to the called

function and the function returns nothing to the calling function.

Example: addition of 2 numbers.

#include<stdio.h>

void add();

void main()

add();

void add()

int a,b,c;

printf(“Enter the values”);

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 :

Call by Value Call by reference


In call by value, value of the variable is In call by reference, the address of the
passed as an argument variable is passed as an argument.
Any changes in formal parameter will Any changes in formal parameter will
not affect actual parameter affect actual parameter
It is using more momory Using less memory

Eg: Eg:
void swap(int, int); void swap(int *, int *);

2.9 return statement

A program is just a set of definitions of variables and functions. Communication


between the functions is by arguments and values returned by the functions, and through
external variables.
The functions can occur in any order in the source file, and the source program
can be split into multiple files, so long as no function is split. The return statement is the
mechanism for returning a value from the called function to its caller. Any
expression can follow return:
return expression; or return value;

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:

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.

For example: If I have to write a program to store Student information, which


will have Student's name, age, branch, permanent address, father's name etc.,
which included string values, integer values etc., how can I use arrays for this
problem, I will require something which can hold data of different types together.

In structure, data is stored in form of records

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

It is possible to declare variables of a structure, either along with structure


definition or after the structure is defined. Structure variable declaration is
similar to the declaration of any normal variable of any other data type.
Structure variables can be declared in following two ways:

Declaring Structure variables separately

struct Student
{
char name[25];
int age;
char branch[10];
char gender;
};

struct Student S1, S2; //declaring variables of struct Student


hello guys
Declaring Structure variables with structure definition

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

Structure members can be accessed and assigned values in a


number of ways. Structure members have no meaning individually without the
structure. In order to assign a value to any structure member, the member
name must be linked with the structure variable using a dot . operator also
called period or member access operator.

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;

Structure and functions:

Structure as Function Arguments

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);
}

printf("\nDisplaying Employee record:\n");


for(i = 0; i < 3; i++)
{
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
}
void main()
{
input();
}
Nested Structures

Nesting of structures, is also permitted in C language. Nested structures means,


that one structure has another structure as member variable.

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;

struct Book b[10]; //Array of structure variables


struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}
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.
hello guys
#include <stdio.h>
struct my_structure
{
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {“C Programming", 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: C Programming
NUMBER: 35
RANK: 1
Self-referential structures
Self-referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential
in nature.
Example:
struct node
{
int data1;
char data2;
struct node* link;
};

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.

An important point to consider is that the pointer should be initialized properly


before accessing, as by default it contains garbage value.
Example:
#include <stdio.h>
struct node
{
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob1; // Node1
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2


ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

ob1.link = &ob2;

printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);

hello guys return 0;


}

Output:

30
40
2.12 Unions:

Unions are conceptually similar to structures. The syntax to


declare/define a union is also similar to that of a structure.

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.

Union and Structure comparison:

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.

It is a derived data type It is an user defined data type

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.

Eg: Struct student


Int a [20]; {
char name[20];
int age;
}s1;

Differences between structure and Union :


2.13 Enumeration

In C programming, an enumeration type (also called enum) is a


data type that consists of integral constants. To define enums, the enum keyword is
used.
The enumeration provide another way to create user defined types.
An Enumeration type is designed for the objects that can have a
limited set of values.
Enumerated Type Declaration
enum flag {const1,const2,…,constN};
( or )
enum enumeration-name {enumeration-list};
When you define an enum type, the blueprint for the variable is
created. Here's how you can create variables of enum types.
enum boolean {false, true};
enum boolean check;
enum day{sun,mon,tue,wed,thu,fri,sat};

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

Write programs for the given


S.No. problems K-Level COs

Write a program to remove duplicate elements K3 CO5

1. and print unique elements in an array using


pointer and function.
Write a C program to swap the unit digits of 2
numbers using Function.
2. For Example Before swapping : K3 CO3
The numbers are 456 and 289
After Swapping 459 and 286
Write a structure to store the name, account
number and balance of customers (more than 10)
and store their information.
1 - Write a function to print the names of all the
customers having balance less than $200.
3. 2 - Write a function to add $100 in the balance of K3 CO3
all the customers having more than $1000 in their
balance and then print the incremented value of
their balance.

Write a program to compare two dates entered


by user. Make a structure named Date to store
4 the elements day, month and year to store the K3 CO3

dates. If the dates are equal, display "Dates are


equal" otherwise display "Dates are not equal".
PART - A
1. Define pointers in C
• C Pointer is a variable that stores/points the address of another variable.
• C Pointer is used to allocate memory dynamically i.e. at run time.
• The variable might be any of the data type such as int, float, char, double, short etc.
Syntax
data_type *var_name;
Example
int *p; char *p;
Where, * is used to denote that, “p” is pointer variable and not a normal variable
2. How to declare and initialize a pointer variable in C.
Pointer declaration
A pointer is a numeric variable, it must be declared before it can be used.
Syntax
datatype *ptrname; Here, * is the indirection operator,
Example
int *a,*b; Here a,b are pointers to type integer.
char *ch1, *ch2; ch1 and ch2 both are pointers to type char
Initializing Pointers:
When (&) is placed before the name of a variable, the address-of operator
returns the address of the variable.
Syntax pointer = &variable;
Example int *ptr;
int a;
ptr = &a ; & it indicates that ptr is a pointer to datatype
3. What do you mean by Chain of pointers/Pointer to Pointer:
• Pointer is a variable that contains the address of another variable.
• Similarly, another pointer variable can store the address of this pointer variable.
Example #include<stdio.h>
void main()
{ int a=10,*b,**c;
b=&a;
c=&b;
printf("Value of a is %d\n",**c); // Value of a is 10
}
4. What is Pointer Expression & Pointer Arithmetic?
C allows pointer to perform the following arithmetic operations:
• A pointer can be incremented / decremented.
• Any integer can be added to or subtracted from the pointer.
5. Define Pointers and Arrays
A pointer is a variable which contains the address (in memory) of another
variable.
A pointer is a variable which points or represents a storage location in
memory (RAM) of a data item, such as a variable or an array.
The memory address is the location where program instructions and data
are stored, pointers can be used to access and manipulate data stored in
the memory.
6. What are the uses of pointer?
Saves Memory Space
Used for dynamic memory allocation
Faster execution
Used to pass array of values to a function as a single argument
7. What is referencing pointer operator in C.
• & - Address of operator / referencing operator
• & is used to retrieve the address of a variable.
Ex: int a=10,*p;
p=&a;
printf(“%d”,*p);
8. What is pointer arithmetic?
Arithmetic operations can be applied to pointers in a restricted form.
When arithmetic operators are applied on pointers, the outcome of the
operation is governed by pointer arithmetic.
The following are the list of operation on pointer variable:
1. Addition operation.
2. Subtraction operation
3. Increment operation
4. Decrement operation
5. Comparison operation
9. List out the operations that are not allowed in pointers.
1. Addition of 2 pointers is not allowed
2. Only integer can be added to pointer. Float and double values are not
allowed.
3. Multiplication, division and bit-wise operations cannot be applied to pointers.
4. A pointer of one type cannot be assigned to pointer of another type.
5. A pointer variable cannot be assigned a non-address value (except zero)

Valid pointer operations Invalid pointer operations


p1-p2 p1+p2
p1++ p1*p2
p2=p2-1 p1/p2
p1=p1+2 p1/3
10. What is array of pointer?
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;
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
}

13. What is the output of the following program.


#include<stdio.h>
void main()
{
int a=10,*p1;
float b=20.5,*p2;
char c=’m’,*p3;
p1=&a;
p2=&b;
p3=&c; Output
printf(" \n%d\n ", a); // 10
printf(" %u\n ", p1); // 1074959264
printf(" %u\n ", &a); // 1074959264
printf(" %d\n ", *p1); // 10
printf(" %d\n ", *(&a)); // 10
a=a+5;
printf(" %d\n ", a); // 15
printf(" %u\n ", p1); // 1074959264
printf(" %d\n ", *p1); // 15
printf(" %f\n ", b); // 20.5
printf(" %u\n ", p2); // 1074959268
printf(" %f\n ", *p2); // 20.5
b=b+5;
printf(" %f\n ", b); // 25.5
printf(" %u\n ", p2); // 1074959268
printf(" %f\n ", *p2); // 25.5
printf(" %c\n ", c); // m
printf(" %u\n ", p3); // 1074959268
printf(" %c\n ", *p3); // m
}
14 ) Write definition of function. Indicate types of functions available .
A function is a self-contained block or a sub-program of one or more statements
that performs a special task when called.
Types of functions
• Without arguments or return values. Eg. abc()
• With arguments but without return values. Eg. abc (int x)
• With arguments and return values. Eg. int abc(int x)
• Without argument but with return values. Eg. int abc().
15) Write the difference between pre-defined (library) function and user defined
function.
Library (Pre-defined) function
a) Contains Pre-defined set of functions
b) User cannot understand the internal working
c) Source code is not visible
d) User cannot modify the function
User defined function
a) The user defined the functions
b) User can understand internal working
c) Source code is visible
d) User can modify the function
16) Write a program to find the factorial of a given number using function.
#include<stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
17) Write a program to swap two numbers using call by reference

#include <stdio.h>

void swap(int*, int*);

int main()

int x, y;

printf("Enter the value of x and y\n");

scanf("%d%d",&x,&y);

printf("Before Swapping\nx = %d\ny = %d\n", x, y);

swap(&x, &y);

printf("After Swapping\nx = %d\ny = %d\n", x, y);

return 0;

void swap(int *a, int *b)

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

❖ Introduction to Programming in C – Coursera

❖ C for Everyone: Programming Fundamentals – Coursera

❖ C for Everyone: Structured Programming - Coursera

❖ Computational Thinking with Beginning C Programming - Coursera

❖ Problem solving through Programming In C – Swayam

❖ C – Sololearn

❖ C Programming For Beginners – Udemy

❖ C Programming For Beginners - Master the C Language – Udemy

External Links for additional resources


❖ https://swayam.gov.in/

❖ 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.

C allows us to do this in a structure definition by putting :bit length after the


variable. For example:

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.

C automatically packs the above bit fields as compactly as possible, provided


that the maximum length of the field is less than or equal to the integer word
length of the computer. If this is not the case, then some compilers may allow
memory overlap for the fields while others would store the next field in the next
word.
Command line arguments

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.

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

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

Program name is: program


First argument is: hello
Assessment Schedule
As per Academic Calendar
Text books & References

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

1. Telecom Billing Management System

2. Medical store management system

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.

You might also like