Anand Singh
Write a code to sort the characters in a given string
Q12. Write an code and algorithm to sort string of characters in dictionary order
Solution : Given a string contain lowercase character from a to z and our task is to sort them in dictionary order.
String :- A string is a sequence of characters terminated with a null character \0 .
For example: char lfc[] = “alfatechlab”;
Algorithm for sort string of characters in dictionary order
//Algorithm To Sort String Of Characters
START
Step 1 -> Take string as input str.
Step 2 -> Store the count of each character in one array ARR, index 0 corresponding to a and so on.
Step 3 -> Now repeat loop I till the end of array ARR
Step 4 -> Repeat inner loop on the basis of value of ARR[I]
Step 5 -> Print (‘a’ + I)
Step 6 -> End Inner loop
Step 7 -> End Loop
STOP
Code for sort string of characters in dictionary order
//C Program To Sort String Of Characters.
#include <stdio.h>
int main()
{
char str[20]=”alfatechlab”;
int len=sizeof(str);
int charCount[26] = {0};
for (int i=0; i<len; i++)
charCount[str[i]-‘a’]++;
for (int i=0;i<26;i++)
for (int j=0;j<charCount[i];j++)
printf(“%c”,(char)(‘a’+i));
return 0;
}
//C++ Program To Sort String Of Characters.
#include <iostream>
using namespace std;
int main()
{
string str = “alfatechlab”;
int charCount[26] = {0};
for (int i=0; i<str.length(); i++)
charCount[str[i]-‘a’]++;
for (int i=0;i<26;i++)
for (int j=0;j<charCount[i];j++)
cout << (char)(‘a’+i);
return 0;
}
//Java Program To Sort String Of Characters.
public class LFC
{
public static void main(String[] args) {
String str=”alfatechlab”;
int alphabet[] = new int[26];
for (char x : str.toCharArray()) {
alphabet[x – ‘a’]++;
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < alphabet[i]; j++) {
System.out.print((char) (i + ‘a’));
}
}
}
}
//Python Program To Sort String Of Characters.
str1=”alfatechlab”
charCount = [0 for i in range(26)]
for i in range(0, len(str1), 1):
charCount[ord(str1[i]) – ord(‘a’)] += 1
for i in range(0, 26, 1):
for j in range(0, charCount[i], 1):
print(chr(ord(‘a’) + i), end = “”)
//PHP Program To Sort String Of Characters.
<?php
$str = ‘alfatechlab’;
$strsplit = preg_split(‘//u’, $str);
sort($strsplit);
echo implode(”, $strsplit);
?>
Output
aaabcefhllt
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number
Write a code to reverse a string
Q11. Write a code to reverse a string
Given a string and the task is to write a algorithm and program to reverse a string. A string is sequence of characters terminated with a null character \0. So we are given a input string and we need to print its reverse order.
For Example: We have given input string as “ALFATECHLAB” and it’s reverse output we have to find out.
Input=”ALFATECHLAB”
Output=”BALHCETAFLA”
Explanation:
1. First declare a string variable and initialize an empty string to “ALFATECHLAB”.
2. Now we have to calculate the length of the string which we can do using loop(increment the value of count until the string is \0) or using the in-build function(strlen function).
3. Define two variables start = 0 and end = length -1.(Suppose “ALFATECHLAB” has a length of 11, then we will swap the 0th character with the 10th character, the 1st character with the 9th character, and the loop will iterate until length / 2 = 5).
4. Iterate the loop from i = 0 to i = length / 2 and increment the variable i by 1.
5. As we already define the start and end variable values, so now we just have to swap the characters one by one and increment the value of start += 1 and decrement the value of end- = 1 during each iteration.
6. After completing iteration print the string and output will be “BALHCETAFLA”.
Algorithm For Reverse A String
//Algorithm To Reverse A String
START
Step 1 -> Input string str1.
Step 2 -> calculate the length of the string.
Step 3 -> define start=0 and end=length-1;
Step 4 -> for i=0 to length/2.
temp=str1[start];
str1[start]=str1[end];
str1[end]=temp;
start+=1;
end-=1;
Loop End
step 5-> Display String str1.
STOP
Code For Reverse A String
//C Program To Reverse A String.
#include <stdio.h>
int main()
{
char str1[100]=”coding in piro”;
int count = 0,i;
//Count the length using While loop
while (str1[count] != ‘\0’)
count++;
int start=0,end=count-1;
char temp;
for(int i=0;i<count/2;i++)
{
//temp is used as a temporary variable that swaps two characters.
temp=str1[start];
str1[start]=str1[end];
str1[end]=temp;
start+=1;
end-=1;
}
//print the reversed string.
printf(“%s\n”, str1);
return 0;
}
//C++ Program Reverse A String.
#include <iostream>
using namespace std;
int main()
{
string str1=”coding in piro”;
//Count the length using in-built function string.length()
int len1=str1.length(),start=0,end=len1-1;
char temp;
for(int i=0;i<len1/2;i++)
{
//temp is used as a temporary variable that swaps two characters.
temp=str1[start];
str1[start]=str1[end];
str1[end]=temp;
start+=1;
end-=1;
}
//print the reversed string.
cout<<str1;
return 0;
}
//Java Program To Reverse A String
import java.lang.*;
import java.io.*;
import java.util.*;
class Main
{
public static void main(String[] args)
{
String str1 = “coding in piro”;
char[] str2 = str1.toCharArray();
int start, end=0;
//Count the length using in-built function string.length.
end = str2.length-1;
for (start=0; start < end ; start++ ,end–)
{
//temp is used as a temporary variable that swaps two characters.
char temp = str2[start];
str2[start] = str2[end];
str2[end]=temp;
}
//print the reversed string.
for (char c : str2)
System.out.print(c);
System.out.println();
}
}
//Python Program To Reverse A String.
def reverse(str1):
str2 = “”
for i in str1:
\\define a empty string str2 and insert the character from starting.
str2 = i + str2
return str2
str1 = “coding in piro”
//print the reversed string.
print (reverse(str1))
//PHP Program To Reverse A String.
<?php
function reverse($str){
//Count the length using in-built function strlen(string)
for($i=strlen($str)-1, $j=0; $j<$i; $i–, $j++)
{ //temp is used as a temporary variable that swaps two characters.
$temp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $temp;
}
return $str;
}
$str = “coding in piro”;
//print the reversed string.
print_r(reverse($str));
?>
Output
orip ni gnidoc
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number
Write a code to make a simple calculator
Q10. Write a code to make a simple calculator
Calculator :- A calculator is used to make mathematical calculations. In this program we will create a simple calculator that can perform an arithmetic operation (+, -, *, /)
For Example :-
Enter an operator (+, -, *, /): +
Enter two operands: 4, 5
4 + 5 = 9
So as we can see that first we have to choose which arithmetic operation we want to do, then after selecting two operands for which we have to do arithmetic calculation.
There is Following Algorithm For simple calculator
START
Step 1 : Initialize the two numbers.
Step 2 : Ask the user to enter an option by giving four options.
Step 3 : After getting the option from the user write if conditions for every operation based on the option.
Step 4 : Perform the respective operation.
Step 5 : Print the result.
STOP
There is Following code to swap two numbers without using third variable
#include <stdio.h>
int main() {
char ch;
double num1, num2;
printf(“Enter an operator (+, -, *, /): “);
scanf(“%c”, &ch);
printf(“Enter two operands: “);
scanf(“%lf %lf”, &num1, &num2);
switch (ch) {
case ‘+’:
printf(“%.1lf + %.1lf = %.1lf”, num1, num2, num1 + num2);
break;
case ‘-‘:
printf(“%.1lf – %.1lf = %.1lf”, num1, num2, num1 – num2);
break;
case ‘*’:
printf(“%.1lf * %.1lf = %.1lf”, num1, num2, num1 * num2);
break;
case ‘/’:
printf(“%.1lf / %.1lf = %.1lf”, num1, num2, num1 / num2);
break;
// operator doesn’t match any case constant
default:
printf(“Error! operator is not correct”);
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
char ch;
float num1, num2;
cout << “Enter an operator (+, -, *, /): “;
cin >> ch;
cout << “Enter two operands: “;
cin >> num1 >> num2;
switch(ch)
{
case ‘+’:
cout << num1+num2;
break;
case ‘-‘:
cout << num1-num2;
break;
case ‘*’:
cout << num1*num2;
break;
case ‘/’:
cout << num1/num2;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << “Error! operator is not correct”;
break;
}
return 0;
}
import java.util.Scanner;
public class LFC {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print(“Enter two operands: “);
// nextDouble() reads the next double from the keyboard
double num1 = reader.nextDouble();
double num2 = reader.nextDouble();
System.out.print(“Enter an operator (+, -, *, /): “);
char ch = reader.next().charAt(0);
double res;
switch(ch)
{
case ‘+’:
res = num1 + num2;
break;
case ‘-‘:
res = num1 – num2;
break;
case ‘*’:
res = num1 * num2;
break;
case ‘/’:
res = num1 / num2;
break;
// operator doesn’t match any case constant (+, -, *, /)
default:
System.out.printf(“Error! operator is not correct”);
return;
}
System.out.printf(“%.1f %c %.1f = %.1f”, num1, ch, num2, res);
}
}
# Program make a simple calculator
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x – y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
# Take input from the user
ch = input(“Enter an operator (+, -, *, /): “)
num1 = float(input(“Enter first number: “))
num2 = float(input(“Enter second number: “))
if ch == ‘+’:
print(num1,”+”,num2,”=”, add(num1,num2))
elif ch == ‘-‘:
print(num1,”-“,num2,”=”, subtract(num1,num2))
elif ch == ‘*’:
print(num1,”*”,num2,”=”, multiply(num1,num2))
elif ch == ‘/’:
print(num1,”/”,num2,”=”, divide(num1,num2))
else:
print(“Error! operator is not correct”)
Output
Enter an operator (+, -, *, /): +
Enter two operands: 4,5
4+5=9
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number
Write a code to swap two numbers without using temporary variable
Q9. Write a code to swap two numbers without using temporary variable
Solution : We can swap two numbers without using temporary variable. By using + and – operator we can swap two number.
Swapping two number :- Swap two numbers means exchange the values of two variables with each other.
For example:
Before Swapping : num1 = 30 and num2 = 25.
After Swapping : num1 = 25 and num2 = 30.
Logic :- Suppose we are given 2 numbers num1 = 30 and num2 = 25 and we have to swap these 2 numbers without using third variable. Then we have to perform below operations to swap the numbers.
1. Firstly we will add both the number and will assign to the first number.
num1 = num1 + num2
num1 = 30 + 25=45
2. Secondly we will subtract second number from the first number (updated value after step 1)
num2 = num1 – num2
num2 = 45 – 25
num2 = 30
3. Third step will be subtracting second number (updated value after step 2) from the first number (updated value from step 1)
num1 = num1 – num2
num1 = 45 – 30
num1 = 25
After the above 3 steps we will get our required result i.e we have swapped 2 numbers without using third variable.
There is Following Algorithm to swap two numbers without using third variable
//Algorithm To Swap Two Numbers Without Using Temporary Variable
START
Step 1 -> Take two integer as input num1 and num2.
Step 2 -> Print number before swapping
Step 3 -> num1 = num1 + num2;
Step 4 -> num2 = num1 – num2;
Step 5 -> num1 = num1 – num2;
Step 6 -> Print numbers after swapping
STOP
There is Following code to swap two numbers without using third variable
//C Program To Swap Two Numbers Without Temporary Variable.
#include <stdio.h>
int main()
{
int num1,num2;
printf(“Enter two numers : \n”);
scanf(“%d %d”,&num1,&num2);
printf(“Number before swapping is %d and %d \n”,num1,num2);
num1=nuam1+num2;
num2=num1-num2;
num1=num1-num2;
printf(“Number after swapping is %d and %d \n”,num1,num2);
return 0;
}
//C++ Program To Swap Two Numbers Without Temporary Variable.
#include <iostream>
using namespace std;
int main()
{
int num1,num2;
cout<<“Enter Two Numbers :\n”;
cin>>num1>>num2;
cout<<“Number before swapping is “<<num1<<” and “<<num2<<“\n”;
num1=num1+num2;
num2=num1-num2;
num1=num1-num2;
cout<<“Number after swapping is “<<num1<<” and “<<num2;
return 0;
}
//Java Program To Swap Two Numbers Without Temporary Variable.
import java.util.Scanner;
public class LFC
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(“Enter Two Numbers :”);
int num1 = scan.nextInt();
int num2 = scan.nextInt();
System.out.println(“Number before swapping is “+num1+” and “+num2);
num1=num1+num2;
num2=num1-num2;
num1=num1-num2;
System.out.println(“Number after swapping is “+num1+” and “+num2);
}
}
//Python Program To Swap Two Numbers Without Temporary Variable.
print(‘Enter Two Numbers :’)
num1 = int(input())
num2 = int(input())
print(“Number before swapping is “,num1,” and “,num2)
num1 = num1 + num2;
num2 = num1 – num2;
num1 = num1 – num2;
print(“Number after swapping is “,num1,” and “,num2)
//PHP Program To Swap Two Numbers Without Temporary Variable.
<?php
$num1=30;
$num2=25;
echo “Number before swapping is $num1 and $num2 \n”;
$num1=$num1+$num2;
$num2=$num1-$num2;
$num1=$num1-$num2;
echo “Number after swapping is $num1 and $num2”;
?>
Output
Enter Two Numbers :
30,25
Number before swapping is 30 and 25
Number after swapping is 25 and 30
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number