Docsity

Computer science notes for class 12 cbse, Study notes of Computer science

Toggle sidebar
bg1
C Programming Practical Exercises
Page 1 of 3
C P R O G R A M M I N G
Practical Exercises: Variables and Decision
Making
Swapping two variables and finding the maximum of three numbers
Program 1: Exchange Two Variables Using a Third Variable
Problem Statement
Write a program in C to exchange (swap) the values of two variables using a third, temporary variable.
Source Code
#include <stdio.h>
int main()
{
int a, b, temp;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Before exchange: a = %d, b = %d\n", a, b);
temp = a;
a = b;
b = temp;
printf("After exchange: a = %d, b = %d\n", a, b);
return 0;
}
Sample Output
Enter two numbers: 10 20
Before exchange: a = 10, b = 20
After exchange: a = 20, b = 10
Logic
1. Store the value of a in temp.
2. Copy the value of b into a.
3. Copy the value of temp into b.
Thus, the values of a and b are exchanged.
pf3

Partial preview of the text

Download Computer science notes for class 12 cbse and more Study notes Computer science in PDF only on Docsity!

C P R O G R A M M I N G

Practical Exercises: Variables and Decision

Making

Swapping two variables and finding the maximum of three numbers

Program 1: Exchange Two Variables Using a Third Variable

Problem Statement

Write a program in C to exchange (swap) the values of two variables using a third, temporary variable.

Source Code

#include int main() { int a, b, temp; printf("Enter two numbers: "); scanf("%d %d", &a, &b); printf("Before exchange: a = %d, b = %d\n", a, b); temp = a; a = b; b = temp; printf("After exchange: a = %d, b = %d\n", a, b); return 0; }

Sample Output

Enter two numbers: 10 20 Before exchange: a = 10, b = 20 After exchange: a = 20, b = 10

Logic

1. Store the value of a in temp.

2. Copy the value of b into a.

3. Copy the value of temp into b.

Thus, the values of a and b are exchanged.

Program 2: Exchange Two Variables Without a Temporary Variable

Problem Statement

Write a program in C to exchange the values of two variables without using a temporary variable , by

using arithmetic operations.

Source Code

#include int main() { int a, b; printf("Enter two numbers: "); scanf("%d %d", &a, &b); printf("Before exchange: a = %d, b = %d\n", a, b); a = a + b; b = a - b; a = a - b; printf("After exchange: a = %d, b = %d\n", a, b); return 0; }

Sample Output

Enter two numbers: 10 20 Before exchange: a = 10, b = 20 After exchange: a = 20, b = 10

How It Works

Assume a = 10 and b = 20:

  • a = a + b โ†’ a = 30
  • b = a - b โ†’ b = 10
  • a = a - b โ†’ a = 20

So the values are exchanged without a third (temporary) variable.

Note: the addition can overflow if a + b exceeds the range of int. The temporary-variable method in

Program 1 is the safer choice in general.