C++ Programming Code Examples
C++ > Algorithms Code Examples
Binary arithmatic
/* Binary arithmatic */
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>
void b_to_d(char result[]); //binary to decimal
void d_to_b(int dec,char binary[]); // decimal to binary
main()
{
int ch,n1,n2,i=0,j,k,l,carry,r,x1,x2,x;
char bn1[30],bn2[30],result[30],binary[30];
char multi[30][30];
clrscr();
do
{
printf("<1> input first operand \n");
printf("<2> input second operand \n");
printf("<3> binary addition \n");
printf("<4> binary subtraction \n");
printf("<5> binary multiplation \n");
printf("<6> result to decimal \n");
printf("<7> Exit \n\n");
do
{
printf("enter your choice ");
scanf("%d",&ch);
}while(ch>7 || ch<1);
switch (ch)
{
case 1:
printf("\n input first operand ");
scanf("%d",&n1);
x1=n1;
d_to_b(n1,binary);
for(i=0;binary[i]!='\0';++i)
bn1[i]=binary[i];
bn1[i]='\0';
break;
case 2:
printf("\n input second operand ");
scanf("%d",&n2);
x2=n2;
d_to_b(n2,binary);
for(i=0;binary[i]!='\0';++i)
bn2[i]=binary[i];
bn2[i]='\0';
break;
case 3: //addition
for(i=0;i<30;++i) //reset result
result[i]='\0';
carry=0;
if(strlen(bn1)<strlen(bn2))
r=strlen(bn2);
else
r=strlen(bn1);
for(i=0;i<r;++i)
{
result[i+1]='\0';
if(carry==0)
{
if(bn1[i]-48+bn2[i]-48+carry==1)
result[i]=bn1[i]-48+bn2[i]-48+48;
else
result[i]=0+48;
}
else
{
if(bn1[i]-48+bn2[i]-48+carry==2)
result[i]=0+48;
else
result[i]=1+48;
}
if(bn1[i]-48+bn2[i]-48+carry>1)
carry=1;
else
carry=0;
if(carry==1)
result[i+1]=carry+48;
}
printf("\n%s\n",strrev(result));
break;
case 4: //subtraction
for(i=0;i<30;++i) //reset result
result[i]='\0';
carry=0;
if(strlen(bn1)<strlen(bn2))
r=strlen(bn2);
else
r=strlen(bn1);
for(i=0;i<r;++i)
{
result[i+1]='\0';
if(bn1[i]<bn2[i])
carry=2,--bn1[i+1];
else
carry=0;
if(carry+bn1[i]-48-bn2[i]+48==1)
result[i]=1+48;
else
if(carry+bn1[i]-48-bn2[i]+48==0)
result[i]=0+48;
}
printf("\n%s\n",strrev(result));
break;
case 5: //binary multiplication complited on 27-03-2004
for(i=0;i<30;++i) //reset result
result[i]='\0';
strrev(bn2); // reversing second binary operand
k=0,x=0;
for(i=0;i<strlen(bn2);++i) //creating array for addition
if(bn2[i]=='1')
{
for(j=i+1;bn2[j]!='\0';++j)
multi[k][x++]='0';
for(l=0;bn1[l]!='\0';++j,++l)
multi[k][x++]=bn1[l];
for(;x<30;++j)
multi[k][x++]='0';
++k,x=0;
}
l=0;
for(j=0;j<30;++j) //addition of all columns without carry
{
x=0;
for(i=0;i<k;++i)
x+=(multi[i][j]-48);
multi[0][l++]=x;
}
for(i=0;i<30;++i) //loop for including carry.
if(multi[0][i]>1)
multi[0][i+1]+=((multi[0][i]-(multi[0][i]%2))/2);
printf("\n");
for(i=29;i>=0;--i) // excluding first zero's (0's) of array
if(multi[0][i]!=0)
break;
j=0;
for(;i>=0;--i) // final calculations and print
if(multi[0][i]<48)
{
multi[0][i]%=2;
result[j++]=multi[0][i]+48;
// printf("%d",multi[0][i]);
}
printf("\n");
printf("%s\n",result);
break;
case 6: //result in decimal
b_to_d(result);
printf("\n");
break;
}
n1=x1;
d_to_b(n1,binary);
for(i=0;binary[i]!='\0';++i)
bn1[i]=binary[i];
bn1[i]='\0';
n2=x2;
d_to_b(n2,binary);
for(i=0;binary[i]!='\0';++i)
bn2[i]=binary[i];
bn2[i]='\0';
}while(ch!=7);
printf("\n\n i will wait for your mails");
getch();
return 0;
}
void b_to_d(char result[]) //binary to decimal
{
short int i;
long int dec=0;
strrev(result);
for(i=0;i<strlen(result);++i)
dec+=(result[i]-48)*pow(2,i);
printf("result in decimal is %ld\n",dec);
strrev(result);
}
void d_to_b(int dec,char binary[]) // decimal to binary
{
int i=0;
while(dec>0)
{
binary[i++]=dec%2+48;
binary[i]='\0';
dec-=(dec%2);
dec/=2;
}
}
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.
It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
The strrev(string) function returns reverse of the given string. An array of characters is called a string. This function is used for reversing a string. The reversed string is stored in the same string. strrev() is a pre-defined function in C++, defined inside the cstring.h header file. It is extensively applicable for reversing any C-string(character array). This function returns the string after reversing the given string.
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block. • The expression can be integer expression or a character expression. • Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:
Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program. The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input.
In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Raise to power. The pow() function returns the result of the first argument raised to the power of the second argument. This function is defined in the cmath header file. pow() function is a library function of cmath header, it is used to find the raise to the power, it accepts two arguments and returns the first argument to the power of the second argument.
Relational operators for string. Performs the appropriate comparison operation between the string objects lhs and rhs. The functions use string::compare for the comparison. These operators are overloaded in header <string>. If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.
Get string length. Returns the length of the C string str. C++ strlen() is an inbuilt function that is used to calculate the length of the string. It is a beneficial method to find the length of the string. The strlen() function is defined under the string.h header file. The strlen() takes a null-terminated byte string str as its argument and returns its length. The length does not include a null character. If there is no null character in the string, the behavior of the function is undefined.
An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C++ language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant. (2D) array in C++ programming is also known as matrix. A matrix can be represented as a table of rows and columns. In C/C++, we can define multi dimensional arrays in simple words as array of arrays. Data in multi dimensional arrays are stored in tabular form (in row major order).
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
C++ program displays the iterative solution to the Tower of Hanoi problem. Tower Of Hanoi consists of 'three rods' and a number of disks of different sizes which can "Slide Onto" any
Getting the No of processes and Burst Time. "First come First served" Algorithm. Shortest job first algorithm with preemption. Shortest job First Algorithm with NonPreemption. Cpu
The factorial of a positive integer n is equal to 1*2*3*...n. In program, user enters a positive integer. Then the "factorial" of that number is "computed and displayed" in the screen. Here