0% found this document useful (0 votes)
55 views

Programming in C Essay

The document provides information about programming in C including examples of C programs and explanations of different types of operators and selection structures in C. Specifically, it contains: 1) Examples of C programs to check if a year is a leap year and if an integer is even or odd. 2) Explanations and examples of different operators in C including arithmetic, relational, logical, bitwise, and assignment operators. 3) Explanations of two-way and multi-way selection structures in C including if-else statements and switch cases, with examples.

Uploaded by

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

Programming in C Essay

The document provides information about programming in C including examples of C programs and explanations of different types of operators and selection structures in C. Specifically, it contains: 1) Examples of C programs to check if a year is a leap year and if an integer is even or odd. 2) Explanations and examples of different operators in C including arithmetic, relational, logical, bitwise, and assignment operators. 3) Explanations of two-way and multi-way selection structures in C including if-else statements and switch cases, with examples.

Uploaded by

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

PROGRAMMING IN C

ESSAY QUESTIONS AND ANSWERS

Module 1

1. Write a C program to check whether the entered year is leap year or not.

(Leap year program in C


Generally, a year has 365 days in a year, but a leap year has 366 days which comes after four year. Below
are some points related to leap year: A leap year comes once in four years, in which February month has
29 days. With this additional day in February, a year becomes a Leap year. Some leap years examples are
- 1600, 1988, 1992, 1996, and 2000.Although 1700, 1800, and 1900 are century years, not leap years.)

#include<stdio.h>
void main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if((year%4==0) && ((year%400==0) || (year%100!==0)))
{
printf("%d is a leap year", year);
}
else
{
printf("%d is not a leap year", year);
}
}
Output
Enter a year: 2004
2004 is a leap year
2. Explain different operators in C.

An operator is a symbol that tells the compiler to perform specific mathematical or


logical functions. C language is rich in built-in operators and provides the following
types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
Arithmetic Operators
Operator Description

+ Adds two operands.

− Subtracts second operand from the first.

* Multiplies both operands.

/ Divides numerator by de-numerator.

% Modulus Operator and remainder of after an integer


division.

++ Increment operator increases the integer value by one.

-- Decrement operator decreases the integer value by one.

Relational Operators
Operator Description

== Checks if the values of two operands are equal or not. If yes, then
the condition becomes true.

!= Checks if the values of two operands are equal or not. If the


values are not equal, then the condition becomes true.

> Checks if the value of left operand is greater than the value of
right operand. If yes, then the condition becomes true.

< Checks if the value of left operand is less than the value of right
operand. If yes, then the condition becomes true.

>= Checks if the value of left operand is greater than or equal to the
value of right operand. If yes, then the condition becomes true.

<= Checks if the value of left operand is less than or equal to the
value of right operand. If yes, then the condition becomes true.

Logical Operators
Operator Description

&& Called Logical AND operator. If both the operands are non-
zero, then the condition becomes true.

|| Called Logical OR Operator. If any of the two operands is non-


zero, then the condition becomes true.

! Called Logical NOT Operator. It is used to reverse the logical


state of its operand. If a condition is true, then Logical NOT
operator will make it false.

Bitwise Operators
Operator Description

& Binary AND Operator copies a bit to the result if it exists in both
operands.

| Binary OR Operator copies a bit if it exists in either operand.

^ Binary XOR Operator copies the bit if it is set in one operand but not
both.

~ Binary One's Complement Operator is unary and has the effect of


'flipping' bits.

<< Binary Left Shift Operator. The left operands value is moved left by the
number of bits specified by the right operand.

>> Binary Right Shift Operator. The left operands value is moved right by the
number of bits specified by the right operand.

Assignment Operators
Operator Description

= Simple assignment operator. Assigns values from right side operands to


left side operand

+= Add AND assignment operator. It adds the right operand to the left
operand and assign the result to the left operand.

-= Subtract AND assignment operator. It subtracts the right operand from


the left operand and assigns the result to the left operand.

*= Multiply AND assignment operator. It multiplies the right operand with


the left operand and assigns the result to the left operand.

/= Divide AND assignment operator. It divides the left operand with the
right operand and assigns the result to the left operand.

%= Modulus AND assignment operator. It takes modulus using two operands


and assigns the result to the left operand.

<<= Left shift AND assignment operator.

>>= Right shift AND assignment operator.

&= Bitwise AND assignment operator.

^= Bitwise exclusive OR and assignment operator.


|= Bitwise inclusive OR and assignment operator.

Misc Operators ↦ sizeof & ternary


Operat Description Example
or

sizeof() sizeof(a), where a is integer, will


Returns the size of a variable.
return 4.

& &a; returns the actual address of the


Returns the address of a variable.
variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value X :


Conditional Expression.
otherwise value Y

3. write a c program to check whether the integer is even or odd.

#include <stdio.h>
int main()
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);

// true if num is perfectly divisible by 2


if(num % 2 == 0)
printf("%d is even.", num);
else
printf("%d is odd.", num);

return 0;
}
Output
Enter an integer: -7
-7 is odd.

4. With syntax and example explain


(i) two way selection (ii) multi-way selection

Selection Structure.
Use to make a decision or comparison and then, based on the result of that
decision or comparison, to select one of two paths. The condition must result
in either a true (yes) or false (no) answer.
There are two types of selection structures
a) two way selection structures
b) multi-way selection structures

Two way selection structures

A multi-way selection statement is used to execute at most ONE of the


choices from two.

It can be classified into 2

a)if statement

b)if-else statement

a)if statement

An if statement consists of a Boolean expression followed by one or more


statements.
Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the
'if' statement will be executed.
If the Boolean expression evaluates to false, then the first set of code after
the end of the 'if' statement (after the closing curly brace) will be executed.
Flow chart

Example
#include <stdio.h>
int main ()
{
int a = 10;
if( a < 20 )
{
printf("a is less than 20\n" );
}

printf("a is greater than 20\n");

return 0;
}

b)if-else statement

An if statement can be followed by an optional else statement, which executes


when the Boolean expression is false.
Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed,
otherwise, the else block will be executed.
Flow Diagram

Example
#include <stdio.h>
int main ()
{
int a = 100;
if( a < 20 )
{
printf("a is less than 20\n" );
}
else
{
printf("a is not less than 20\n" );
}
return 0;
}

Output
a is not less than 20
MULTIWAY SELECTION STRUCTURE

A multi-way selection statement is used to execute at most ONE of the choices of a


set of statements presented. There are three types

a)if … else if… else statement


b)switch
c)nested if

a)If...else if...else Statement(else if ladder)


An if statement can be followed by an optional else if...else statement, which is
very useful to test various conditions using single if...else if statement.
Syntax
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
Example
#include <stdio.h>
int main ()
{
int a = 100;
if( a == 10 )
{
printf("Value of a is 10\n" );
}
else if( a == 20 )
{
printf("Value of a is 20\n" );
}
else if( a == 30 )
{
printf("Value of a is 30\n" );
}
else
{
printf("None of the values is matching\n" );
}
return 0;
}
output
None of the values is matching
b)Switch

A switch statement allows a variable to be tested for equality against a list of


values. Each value is called a case, and the variable being switched on is checked
for each switch case.
Syntax
switch(expression)
{

case value1 :
statement(s);
break;

case value 2 :
statement(s);
break;

default :
statement(s);
break;
}
Flow Diagram

Example
#include<stdio.h>
int main()
{
float a,b,c;
int ch;
printf("Enter a number\n");
scanf("%f",&a);
printf("Enter another number\n");
scanf("%f",&b);
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("Please enter your choice\n");
scanf("%d",&ch);
switch(ch)
{ case 1: c=a+b;
printf("sum=%f",c);
break;
case 2: c=a-b;
printf("sub=%f",c);
break;
case 3: c=a*b;
printf("product=%f",c);
break;
case 4: c=a/b;
printf("division=%f",c);
break;
default: printf("Invalid choice");
break;
}
return 0;
}
Output
Enter a number
2
Enter another number
5
1. Addition
2. Subtraction
3. Multiplication
4. Division
Please enter your choice
3 Product=10.00000

c)nested if statements
which means you can use one if or else if statement inside another if or else if
statement(s).
Syntax
if( boolean_expression 1)
{

if(boolean_expression 2)
{
Statements;
}
}
Example
#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter three numbers\n");
scanf("%d%d %d ",&a,&b,&c);
if (a>b)
{
if(a>c)
{
printf("The number %d is largest",a);
}
else
{
printf("The number %d is largest",c);
}
}
else
{
if(b>c)
{
printf("The number %d is largest",b);
}
else
{
printf("The number %d is largest",c);
}
}
return 0;
}
Output
Enter three numbers
2
4
8
The number 8 is largest

5. Explain the structure of a C program with example.

BASIC STRUCTURE OF C PROGRAM

A C program is divided into different sections. There are six main sections to a basic
c program.
The six sections are,

 Documentation
 Link
 Definition
 Global Declarations
 Main functions
 Subprograms
Documentation Section
The documentation section is the part of the progra
programm where the programmer gives
the details associated with the program. He usually gives the name of the program,
the details of the author and other details like the time of coding and description. It
gives anyone reading the code the overview of the code.

Example

/*
MULTILINE COMMENT
File Name: Helloworld.c

Author: deepthy

date: 09/08/2019

*/

//Single line comment

Link Section
This part of the code is used to declare all the header files that will be used in the
program. This leads to the compiler being told to link the header files to the system
libraries.

Example

#include<stdio.h>
Definition Section
In this section, we define different constants. The keyword define is used in this
part.

#define PI=3.14

Global Declaration Section


This part of the code is the part where the global variables are declared. All the
global variable used are declared in this part. The user-defined functions are also
declared in this part of the code.

Example

Float area;

int a=7;

Main Function Section


Every C-programs needs to have the main function. Each main function contains 2
parts.

a) A declaration part
b) Execution part.

The declaration part is the part where all the variables are declared. The execution
part begins with the curly brackets and ends with the curly close bracket. Both the
declaration and execution part are inside the curly braces.

Example

int main(void)

int a=10;

printf(" %d", a);

return 0;

Sub Program Section


All the user-defined functions are defined in this section of the program.
Sample Program
/* File Name: areaofcircle.c

Author: Manthan Naik

date: 09/08/2019

*/

#include<stdio.h>//link section

int main()//main function

float r;

printf(" Enter the radius:r\n");

scanf("%f",&r);

printf("the diameter is: %f",2*r)

return 0;

Output

Enter the radius:r


5
the diameter is: 10
6. Write a C program to find the largest among three numbers.

Example
#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter three numbers\n");
scanf("%d%d %d ",&a,&b,&c);
if (a>b)
{
if(a>c)
{
printf("The number %d is largest",a);
}
else
{
printf("The number %d is largest",c);
}
}
else
{
if(b>c)
{
printf("The number %d is largest",b);
}
else
{
printf("The number %d is largest",c);
}
}
return 0;
}

7. Describe the various data types in C with suitable examples.

Variables in C are associated with data type. Each data type requires an amount of
memory and performs specific operations.
There are some common data types in C −
 int − Used to store an integer value.
 char − Used to store a single character.
 float − Used to store decimal numbers with single precision.
 double − Used to store decimal numbers with double precision.

Data Types Bytes Range

int 2 -32,768 to 32,767

signed char 1 -128 to 127

unsigned char 1 0 to 255

float 4 1.2E-38 to 3.4E+38

double 8 2.3E-308 to 1.7E+308

Here is the syntax of datatypes in C language,


data_type variable_name;
Here is an example of datatypes in C language,
Example
#include >stdio.h>
int main() {
// datatypes
int a = 10;
char b = 'S';
float c = 2.88;
double d = 28.888;
printf("Integer datatype : %d\n",a);
printf("Character datatype : %c\n",b);
printf("Float datatype : %f\n",c);
printf("Double Float datatype : %lf\n",d);
return 0;
}
Output
Integer datatype : 10
Character datatype : S
Float datatype : 2.880000
Double Float datatype : 28.888000

8. Write a C program to display the area of a circle.


#include<stdio.h>
int main()
{
int r;
float A;
float PI=3.14;
printf("enter radius\n");
scanf("%d" ,&r);
A=PI*r*r;
printf("area=%f" ,A); return 0;
}
OUTPUT
Enter radius
2
Area=12.56

9.Write a C program to read the month number (between 1 and 12) and display
the corresponding month name (1-Jan, 2-Feb,…12-Dec) using switch statement

#include<stdio.h>
int main()
{
int m;
printf("enter a number between 1 and 12:");
scanf("%d" ,&m);
switch(m)
{
case 1: printf("january");
break;
case 2: printf("february");
break;
case 3: printf("march");
break;
case 4: printf("april");
break;
case 5: printf("may");
break;
case 6: printf("june");
break;
case 7: printf("july");
break;
case 8: printf("august");
break;
case 9: printf("september");
break;
case 10: printf("october");
break;
case 11: printf("november");
break;
case 12: printf("december");
break;
default: printf("invalid");
break;
}
return 0;
}
10.List the rules for defining variables

A variable in simple terms is a storage place which has some memory allocated to
it. Basically, a variable used to store some form of data.
Rules for defining variables
1. A variable can have alphabets, digits, and underscore.
2. A variable name can start with the alphabet, and underscore only. It can’t start
with a digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword, e.g. int, goto , etc.
5. A variable does not contain any special characters and white space

11.Write a C program to read three sides a, b & c of a triangle. Check whether it is


a valid triangle. If valid find the perimeter of the triangle. [Hint : perimeter : a+b+c,
for a valid triangle: length of a side < sum of other two sides.]

#include<stdio.h>
int main()
{
int a,b,c,per,;
printf("enter 3 sides\n");
scanf("%d %d %d" ,&a,&b,&c);
if(a <b+c &&b<a+c &&c<a+b)
{
printf("triangle valid\n");
per=a+b+c;
printf("perimeter=%d" ,per);
}
else
{
printf("invalid triangle");
}
Return 0;
}
12. What is the use of 'default' statement in switch?
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for
each switch case.

A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none of
the cases is true. No break is needed in the default case.
13Write a C program and check whether a given character is a vowel or not
#include<stdio.h>
int main()
{
char Al;
printf("enter an alphabet\n");
scanf("%c" ,&Al);
if(Al=='A'||Al=='a'||Al=='e'||Al=='E'||Al=='I'||Al=='i'||Al=='o'|| Al
=='O'||Al=='U'||Al=='u')
{
printf("%c is vowel" ,Al);
}
else
{
printf("%c is consonant" ,Al);
}
return 0;
}
Module 2
1) Write C program to find the sum of first N odd numbers using while loop.

#include<stdio.h>

int main()

int num, count = 1, sum = 0;

printf("Enter a integer number\n");

scanf("%d", &num);

while(count <= num)

if(count%2 != 0)

sum = sum + count;

count++;

printf("Sum of ODD integer number is %d\n", sum);

return 0;

Output :
Enter a integer number
5
Sum of ODD integer number is 9

2) Explain how two dimensional arrays are created.


Two Dimensional Array in C
 The two-dimensional array can be defined as an array of arrays.
 The 2D array is organized as matrices which can be represented as the
collection of rows and columns.

Declaration of two dimensional Array in C

syntax

data_type array_name[rows][columns];

creation of 2D Array in C
method 1

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

eg:

#include<stdio.h>

int main()
{
int i=0,j=0;
Int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}
}
return 0;
}
Method 2

#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
}

3) Compare entry controlled loop and exit controlled loop.


Entry Control Loop Exit Control Loop

Entry control loop checks condition The exit control loop first executes the body of the
first and then loop and
body of the loop will be executed. checks condition at last.

The body of the loop may or may The body of the loop will be executed at least once
not be executed at all. because the condition is checked at last

for, while are an example of an


Do…while is an example of an exit control loop.
entry control loop

4) Write a C program to find the sum of elements of an array


#include <stdio.h>
void main()
{
int a[100];
int i, n, sum=0;
printf("\nFind sum of all elements of array:\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}

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


{
sum =sum+ a[i];
}

printf("Sum of all elements stored in the array is : %d\n", sum);


}
Output
Find sum of all elements of array:
Input the number of elements to be stored in the array :3
element - 0 : 2
element - 1 : 5
element - 2 : 8
Sum of all elements stored in the array is : 15

5)Explain how to crate a one dimensional array.


An array is a group of related items that store with a common name.

One – dimensional array


The Syntax is as follows −
datatype arrayname [size]
For example, int a[5]
Initialization
An array can be initialized in two ways, which are as follows −

 Compile time initialization


 Runtime initialization
compile time initialization
#include<stdio.h>
int main ( )
{
int a[5] = {10,20,30,40,50};
int i;
printf ("elements of the array are");
for ( i=0; i<5; i++)
printf ("%d", a[i]);
}
runtime initialization
#include<stdio.h>
main ( )
{
int a[5],i;
printf ("enter 5 elements");
for ( i=0; i<5; i++)
scanf("%d", &a[i]);
printf("elements of the array are");
for (i=0; i<5; i++)
printf("%d", a[i]);
}
6.Write a C program to display the difference of largest and second largest
numbers stored in an array of 10 integer numbers.

#include <stdio.h>

int main()
{
//Initialize array
int arr[10] = {5, 2, 8, 7, 1,6,10,9,4,3};
int temp,res;
int i, j;

//Displaying elements of original array


printf("Elements of original array: \n");
for( i = 0; i <=10; i++)
{
printf("%d ", arr[i]);
}
//Sort the array in ascending order

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


{
for ( j = i+1; j <=9; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("\n");

//displaying result difference between largest and second largest element


res=arr[9]-arr[8];
printf(“result= %d”,res);
return 0;
}

Output
5
2
8
7
1
6
10
9
4
3
Result=1

6. What is a loop ? Why it is necessary in the program ?


LOOPS
Let's consider a situation when you want to print Hello, World! five times. Here is a
simple C program to do the same −
#include <stdio.h>

int main() {
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
 It was simple, but again, let's consider another situation when you want to
write Hello, World! a thousand times.
 We can certainly not write printf() statements a thousand times.
 Almost all the programming languages provide a concept called loop, which
helps in executing one or more statements up to a desired number of
times. All high-level programming languages provide various forms of
loops, which can be used to execute one or more statements repeatedly.
 example
#include <stdio.h>

int main() {
int i = 0;

while ( i < 5 ) {
printf( "Hello, World!\n");
i = i + 1;
}
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
 The above program makes use of a while loop, which is being used to
execute a set of programming statements enclosed within {....}. Here, the
computer first checks whether the given condition, i.e., variable "a" is less
than 5 or not and if it finds the condition is true, then the loop body is
entered to execute the given statements. Here, we have the following two
statements in the loop body −
 First statement is printf() function, which prints Hello World!
 Second statement is i = i + 1, which is used to increase the value of variable i
 After executing all the statements given in the loop body, the computer goes
back to while( i < 5) and the given condition, (i < 5), is checked again, and the
loop is executed again if the condition holds true. This process repeats till the
given condition remains true which means variable "a" has a value less than
5.
To conclude, a loop statement allows us to execute a statement or group of
statements multiple times.

7. Write a program to print the reverse of a given number n.


#include<stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter a number: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n=n/10;
}
printf("Reversed Number: %d",reverse);
return 0;
}
Output:
Enter a number: 123
Reversed Number: 321

8. Write a program to print the transpose of a 3x3 matrix.


#include<stdio.h>
int main()
{
int r,c,i,j;
printf(“enter the row r:”);
scanf(“%d”,&r);
printf(“enter the column c:”);
scanf(“%d”,&c);
int arr[r][c];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“enter the element a%d%d”,i,j);
scanf(“%d”,&a[i],[j]);
}
}

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“%d\t”,a[i][j]);
}
print(“\n”);
}
// print transpose of A
for(i=0;i<c;i++)
{
for(j=0;j<r;<j++)
{
printf(“%d\t”,a[j[i]);
}
print(“\n”);
}
return 0;
}

9) Write a C program to check whether the given number is palindrome or not.

#include <stdio.h>
int main()
{
int n, rev = 0, rem, org;
printf("Enter an integer: ");
scanf("%d", &n);
org= n;
// reversed integer is stored in reversed variable
while (n != 0) {
rem = n % 10;
rev = rev * 10 + rem;
n =n/10;
}

// palindrome if orignal and reversed are equal


if (org == rev)
printf("%d is a palindrome.", org);
else
printf("%d is not a palindrome.", org);

return 0;
}

Output
Enter an integer: 1001
1001 is a palindrome.

Module 3
1)Explain any three possible pointer arithmetic operations.
Pointer Arithmetic’s in C
Pointers variables are also known as address data types because they are used to
store the address of another variable. The address is the memory location that is
assigned to the variable. It doesn’t store any value.
The pointer operations are:
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is
incremented, it actually increments by the number equal to the size of the data
type for which it is a pointer.
ForExample:
 If an integer pointer that stores address 100 is incremented, then it will
increment by 2(size of an int) and the new address it will points to 102.
 While if a float type pointer is incremented then it will increment by 4(size of a
float) and the new address will be 104.
main()
0 1 2 3 4
{
5 8 9 6 10
Int A[5]={5,8,9,6,10}; 100 102 104 106 108
Int*p,*q;
P=&A[0];
P++; P++
p

100 102
}
Decrement: It is a condition that also comes under subtraction. When a pointer is
decremented, it actually decrements by the number equal to the size of the data
type for which it is a pointer.
ForExample:
 If an integer pointer that stores address 102 is decremented, then it will
decrement by 2(size of an int) and the new address it will points to 100.
 While if a float type pointer is decremented then it will decrement by 4(size of a
float) and the new address will be 98.
main()
0 1 2 3 4
{
5 8 9 6 10
Int A[5]={5,8,9,6,10}; 100 102 104 106 108
Int*p,*q;
P=&A[0];
P--; P
p--

100 102
}
Addition
When a pointer is added with a value, the value is first multiplied by the size of data
type and then added to the pointer.
main()
0 1 2 3 4
{
5 8 9 6 10
Int A[5]={5,8,9,6,10}; 100 102 104 106 108
Int *p,*q;
P=&A[0];
P=p+2; P+2
p

100 104
}

Subtraction

When a pointer is subtracted with a value, the value is first multiplied by the size of
the data type and then subtracted from the pointer.

main()
0 1 2 3 4
{
5 8 9 6 10
Int A[5]={5,8,9,6,10}; 100 102 104 106 108
Int *p,*q;
P=&A[0];
p=p-2; P
p-2

100 104
}
Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data type.
The result is generated by calculating the difference between the addresses of the
two pointers and calculating how many bits of data it is according to the pointer
data type. The subtraction of two pointers gives the increments between the two
pointers.
For Example:
Two integer pointers say ptr1(address:100) and ptr2(address:106) are subtracted.
The difference between address is 6 bytes. Since the size of int is 2 bytes, therefore
the increment between ptr1 and ptr2 is given by (6/2) = 3.

main()
0 1 2 3 4
{
5 8 9 6 10
Int A[5]={5,8,9,6,10}; 100 102 104 106 108
Int *p,*q,l;
p=&A[0];
q=&A[3]
l=p-q; q
p-2
106
100
}

2. Write a C program to read a string and get its duplicate without using string
function.

#include <stdio.h>
#include <string.h>

int main()
{
char Str[100], CopyStr[100];
int i;
printf("\n Please Enter any String : ");
gets(Str);

for (i = 0; Str[i]!='\0'; i++)


{
CopyStr[i] = Str[i];
}
CopyStr[i] = '\0';
printf("\n String that we coped into CopyStr = %s", CopyStr);
return 0;
}

3. Explain the use of NULL character in the declaration and initialization of strings.
An array of characters (or) collection of characters is called a string.
Declaration
Refer to the declaration given below −
char stringname [size];
For example - char a[50]; a string of length 50 characters.
Initialization
The initialization is as follows −
 Using single character constant −
char string[20] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

 Using string constants −


char string[20] = "Hello":;

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

 ‘\0’ is called a null character. It marks the end of the string.


 ‘\0’ is automatically placed by the compiler, if a string is given as input.
 The user has to take care of placing ‘\0’ at the end if a single character is
given.
Accessing − There is a control string "%s" used for accessing the string, ll it
encounters ‘\0’
4. Explain comparison of two pointers with the help of a program.

Pointer Comparison in C

When two pointers are compared, the result depends on the relative locations in
the address space of the objects pointed to. If two pointers to object types both
point to the same object, or both point one past the last element of the same array
object, they compare equal.( ര ് pointers compare െച ുേ ാൾ, pointed object ന്െറ relative position

ആ ശയി ിരി ും result. pointers ര ും ഒേര object േലേ ാ അെ ിൽ ഒേര array object ന്െറ lastelement കഴി
Pointer കളിേലേ ാ ആെണ ിൽ, അവ equal മായി compare െച ു ു.)

#include <stdio.h>

int main()

int A[]={1,2,3,4,5]

int *ptrA,*ptrB;

ptrA = &A[1];

ptrB = &A[4];

if(ptrB> ptrA)

printf("PtrB is greater than ptrA");

return(0);

OUTPUT

PtrB is greater than ptrA


5. What is a sting ? How it can be initialized? Explain
 Strings are actually one-dimensional array of characters terminated by
a null character '\0'.
 Thus a null-terminated string contains the characters that comprise the
string followed by a null.
 The following declaration and initialization create a string consisting of the
word "Hello".
 To hold the null character at the end of the array, the size of the character
array containing the string is one more than the number of characters in the word
"Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C

Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the '\0' at the end of the string when it initializes the
array.
#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
6. Write a C program to read a sting from keyboard and display it using character
pointer

#include <stdio.h>
int main()
{
char str[100];
char *ptr;

printf("Enter a string: ");


gets(str);

//assign address of str to ptr


ptr=str;

printf("Entered string is: ");


while(*ptr!='\0')
printf("%c",*ptr++);

return 0;
}

Output

Enter a string: This is a test string.


Entered string is: This is a test string.

7. Explain the syntaxes of strlen(), strdup(), stuupr() functions


strlen()
strlen() stands for string length. This function is used to find number of

characters stored in a string variable or string constant. This function

doesn’t count null character.

Program to demonstrate the use of strlen() function.

#include<stdio.h>
#include<string.h>
int main()
{
char studentname[20]=”Amit”;
int n;
n=strlen(studentname);
printf(“\nNumber of characters=%d”,n);
return(0);
}

Output

Number of characters=4

The strdup() and strndup() functions are used to duplicate a string.


strdup() :

// C program to demonstrate strdup()


#include<stdio.h>
#include<string.h>

int main()
{
char source[] = "GeeksForGeeks";

// A copy of source is created dynamically


// and pointer to copy is returned.
Char * target = strdup(source);

printf("%s", target);
return 0;
}
Output:
GeeksForGeeks

strndup() :

// C program to demonstrate strndup()

#include<stdio.h>

#include<string.h>
int main()

char source[] = "GeeksForGeeks";

// 5 bytes of source are copied to a new memory

// allocated dynamically and pointer to copied

// memory is returned.

char* target = strndup(source, 5);

printf("%s", target);

return 0;

Output:
Geeks

8. Write a C program to swap two numbers using pointers.


#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);

printf("Before Swapping x = %d y= %d ", x, y);

a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
printf("After Swapping x = %d y = %d ", x, y);
return 0;
}
9. Describe the string handling functions to concatenate two strings with
example.
In C, the strcat() function is used to concatenate two strings.
The function takes two strings as input; the destination string, and the source
string. The pointer of the source string is appended to the end of the destination
string, thus concatenating both strings.
Example
#include <stdio.h>
#include <string.h>
int main()
{
char destination[] = "Hello ";
char source[] = "World!";
strcat(destination,source);
printf("Concatenated String: %s\n", destination);
return 0;
}

Output
Concatenated String: Hello World!

Module4
1. Write a C program to find out sum of two numbers using function
#include <stdio.h>
int sum(int a, int b)
{
return a+b;
}
int main()
{
int num1, num2, num3;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);

//Calling the function


num3 = sum(num1, num2);
printf("Sum of the entered numbers: %d", num3);
return 0;
}
Output:

Enter first number: 22


Enter second number: 7
Sum of the entered numbers: 29

2.Explain recursive function with the help of a suitable example


Python recursive functions
 When a function calls itself is known as recursion.
 Recursion works like loop but sometimes it makes more sense to use
recursion than loop.
 A recursive function calls itself.
 Imagine a process would iterate indefinitely if not stopped by some condition!
 Such a process is known as infinite iteration.
 The condition that is applied in any recursive function is known as base
condition.
 A base condition is must in every recursive function otherwise it will continue
to execute like an infinite loop.
Working Principle:
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to
continue recursion.
Here is an example of recursive function used to calculate factorial.
Example:
def fact (n):
if n = = 0:
return 1;
else:
return n * fact (n – 1);
print (fact (0));
print (fact (5));

Output: 1

You might also like