Monday, March 31, 2014

Sum of Digits (5-digit Number) – C Program

Problem Question


If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits. (Hint: Use the modulus operator ‘%’)

Explanation of Problem


In this program, we wish to get a user input which should be a 5 digit number. Then we shall extract the digits one by one and add them. This sum should then be displayed on the user terminal.

Code



#include <stdio.h>
/*Sum of Digits *
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 31-03-2014**/
int main()
{
    printf("\n\nEnter a five digit number: ");
    int number, digitSum = 0, digit1, digit2, digit3, digit4, digit5;
    scanf("%d", &number);
    printf("\nCalculating sum of digits......");
    digit1 = (number % 100000) / 10000;
    digit2 = (number % 10000) / 1000;
    digit3 = (number % 1000) / 100;
    digit4 = (number % 100) / 10;
    digit5 = (number % 10);
    digitSum = digit1 + digit2 + digit3 + digit4 + digit5;
    printf("\nThe sum of digits is: %d\n", digitSum);
    system("pause");
    return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This functions has to named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

digit1 = (number % 100000) / 10000;
digit2 = (number % 10000) / 1000;
digit3 = (number % 1000) / 100;
digit4 = (number % 100) / 10;
digit5 = (number % 10);

The above piece of code reflects the part of the code in which we extract all the digits of the 5-digit number. ‘%’ operator (called the modulus operator) finds the remainder of the division of the number on left with the number on right of the operator. What I did here is, first I applied the modulus operator between the number and 100000. On dividing the remainder found with 10000, I found the digit at the ten-thousand position of the number. This is possible because I am using the ‘int’ data type, which thus rejects the digits after the decimal. Similarly, the other digits are found. You can try a it on paper to justify my statement to yourself.

digitSum = digit1 + digit2 + digit3 + digit4 + digit5; -> This is where we calculate the sum of the digits extracted above.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Sunday, March 30, 2014

Contents Swap – C Program

Problem Question


Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.

Explanation of Problem


We need the user to enter 2 numbers, which should be stored in two variables ‘C’ and ‘D’. Our program should be able to interchange the values held by these variables.

Code


#include <stdio.h>
/*Content Swap*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 30-03-2014**/
int main()
{
    printf("\n\nEnter two numbers: ");
    int C, D;
    scanf("%d%d", &C, &D);
    int temp;
    temp = C;
    C = D;
    D = temp;
    printf("\n\nC = %d, D = %d\n", C, D);
    system("pause");
    return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This functions has to named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

int temp; -> Introduces a new variable which will help in the transition of the values of the variables during the swapping process.

temp = C;
C = D;
D = temp;

Using the above lines of code, we swap the values. The value of variable ‘C’ is stored in the variable ‘temp’. Then, in the variable ‘C’ we store the value of variable ‘D’. Now, in the variable ‘C’ we have the value of ‘D’. Now we need to store the original value of ‘C’ into ‘D’. We do this by using the variable ‘temp’. We now allocate the value of ‘temp’ (the original value of ‘C’) to the variable ‘D’. Now we just output the result, since we have successfully swapped the values of the two variables.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Saturday, March 29, 2014

Area and Perimeter Calculator – C Program

Problem Question


The length & breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to calculate the area & perimeter of the rectangle, and the area & circumference of the circle.

Explanation of Problem


We wish to write a program in which the user will enter 3 numerical values which will denote the length & breadth of a rectangle and radius of a circle. Our program shall compute the rectangle’s perimeter, circle’s circumference, and area for both the geometrical figures. The program is a simple input output program.

Code


#include <stdio.h>
/*Area Perimeter Circumference Calculator*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 29-03-2014**/
int main()
{
    float lengthRectangle, breadthRectangle, radiusCircle, perimeterRectangle, circumference, areaRectangle, areaCircle;
    printf("\n\nEnter lenght of the Rectangle: ");
    scanf("%f", &lengthRectangle);
    printf("Enter breadth of the Rectangle: ");
    scanf("%f", &breadthRectangle);
    printf("Enter radius of the Circle: ");
    scanf("%f", &radiusCircle);
    printf("\nCalculating......\n");
    perimeterRectangle = ( lengthRectangle + breadthRectangle ) * 2;
    areaRectangle = lengthRectangle * breadthRectangle;
    circumference = radiusCircle * 2 * 3.14;
    areaCircle = radiusCircle * radiusCircle * 3.14;
    printf("\nArea:\n\tRectangle: %f\n\tCircle: %f\nPerimter:\n\tRectangle: %f\n\tCircle: %f\n", areaRectangle, areaCircle, perimeterRectangle, circumference);
    system("pause");
    return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This functions has to named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

perimeterRectangle = ( lengthRectangle + breadthRectangle ) * 2;
areaRectangle = lengthRectangle * breadthRectangle;
circumference = radiusCircle * 2 * 3.14;
areaCircle = radiusCircle * radiusCircle * 3.14;
These lines of code are the real processing of the program where the calculation of the perimeter, circumference, and area are calculated.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Sunday, March 23, 2014

Temperature Conversion – C Program

Problem Question


Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees.

Explanation of Problem


This is another simple C program in which the user enters a number which is interpreted as the temperature in degree Fahrenheit for certain city. Our program should convert this into degree Celsius and display the result.

Code


#include <stdio.h>
/*Fahrenheit to Celcius*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 23-03-2014**/
int main()
{
    printf("\n\nEnter the temperature in Fahrenheit: ");
    float temperatureF = 0.0, temperatureC = 0.0;
    scanf("%f", &temperatureF);
    printf("\nCalculating.......\n");
    temperatureC = (temperatureF - 32) * 5 / 9;
    printf("\nTemprature in Celsius: %f\n", temperatureC);
    system("pause");
    return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This functions has to named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal. We use this function in this program to display a prompt for user’s input and the final result at the user’s screen.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function. Here, we use this function to store the user entered float value in the variable ‘temperatureF’.

float temperatureF = 0.0, temperatureC = 0.0 -> The float variables to accommodate the real numbers since the temperature are generally in decimals. ‘temperatureF’ variable is used to store Fahrenheit temperature, and ‘temperatureC’ variable is used to store Celcius temperature.

temperatureC = (temperatureF - 32) * 5 / 9 -> This is the calculation part in which we calculate the Celcius temperature from Fahrenheit temperature and store the result in the variable ‘temperatureC’.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Saturday, March 22, 2014

Aggregate and Percentage Marks - C Program

Problem Question


If the marks obtained by a student in five different subjects are input through the keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume that the maximum marks that can be obtained by a student in each subject is 100.

Explanation of Problem


We wish to make a program over here which will let the user enter 5 numbers, which are the marks in 5 subjects out of 100. Out program should then calculate the aggregate and percentage marks, and display the result.

Code



#include <stdio.h>

/*Aggregate and Percentage Marks *
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Codelocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: *22-03-2014*/

int main()
{
    printf("\n\nEnter the marks in 5 subjects:\n");
    int marks[5], total = 0, i = 0;
    for(i = 0; i < 5; i++)
        {
                printf("\nEnter marks in Subject%d: ", i+1);
                scanf("%d", &marks[i]);
                total += marks[i];
        }
        printf("\nCalculating........\n");
        float percent = total / 5;
        printf("\nAggregate marks: %d\nPercentage makrs: %f\n\n", total, percent);
        system("pause");
        return 0;
}


Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This functions has to named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

int marks[5], total = 0, i = 0; -> In this statement, I have declared an integer array called 'marks' of size 5. This means I have declared an array that can hold 5 integer values. The variable 'total' is used to store the aggregate marks. I initialized it to zero so that I can directly start adding the marks to it as they are entered by the user. The variable 'i' is used as the for loop counter variable.

    for(i = 0; i < 5; i++){
                printf("\nEnter marks in Subject%d: ", i+1);
                scanf("%d", &marks[i]);
                total += marks[i];}

-> This is the for loop, where I get the user inputs and keep adding them to get the aggregate marks, stored in the variable called 'total'.

float percent = total / 5; -> In this statement, I declare a variable of type float named 'percent' which stores the percentage marks. I simply divide the total by 5 to get the percentage.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



Friday, March 21, 2014

Distance between cities conversion in different units – C Program

Problem Question


The distance between two cities (in km.) is input through the keyboard. Write a program to convert and print this distance in meters, feet, inches and centimeters.

Explanation of Problem


The problem wants the program to ask user for an input. The user enters a number which is interpreted as the distance in km. Our program should be able to convert this distance into the above mentioned units by doing calculations, and displaying the result to the user, since without the output there is no sure-shot way to guarantee the correctness of the result.

Code


#include
/*DISTANCE BETWEEN CITIES*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 21-03-2014**/
int main()
{
    printf("\n\nEnter distance(in km): ");
    float distanceInKm, distanceInM, distanceInFt, distanceInIn, distanceInCm = 0.0;
    scanf("%f", &distanceInKm);
    distanceInM = distanceInKm * 1000;
    distanceInCm = distanceInM * 100;
    distanceInIn = distanceInCm * 2.54;
    distanceInFt = distanceInIn * 12;
    printf("Calculating........\nThe result is:\n\nMeter: %f\nCentimeter: %f\nInches: %f\nFeet: %f\n", distanceInM, distanceInCm, distanceInIn, distanceInFt);
    system("pause");
    return 0;
}

Explanation of Code


#include -> #include calls the C Preprocessor directing it to include the STDIO header file which contains the standard Input Output functions for the C Language. This step is executed before the compilation starts.

int main() -> In ANSI C, we declare main() with return type int. main() is the entry point of the C Program, i.e., the point where the code execution begins.

printf("\n\nEnter distance(in km): "); -> The printf() function of the standard C Library displays the string passed to it on the user’s display. Here we use to prompt the user to enter the distance. Another printf() use appears at the end of the program in the statement:
printf("Calculating........\nThe result is:\n\nMeter: %f\nCentimeter: %f\nInches: %f\nFeet: %f\n", distanceInM, distanceInCm, distanceInIn, distanceInFt);
where we use it to print the result, i.e. display the converted distance on the user’s display.

float distanceInKm, distanceInM, distanceInFt, distanceInIn, distanceInCm = 0.0; -> To make the program more flexible and so that it can accept and display decimal values, I used float instead of int. These variables will be used to hold the input and the results.

scanf("%f", &distanceInKm); -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable ‘distanceInKm’. Since it is a float type variable, we use ‘%f’.

distanceInM = distanceInKm * 1000;
distanceInCm = distanceInM * 100;
distanceInIn = distanceInCm * 2.54;
distanceInFt = distanceInIn * 12;
-> This is the part of the code where the calculation takes place and we store the result in different variables.

Please Note: In this program, we could substitute the lines:

distanceInM = distanceInKm * 1000;
distanceInCm = distanceInM * 100;
distanceInIn = distanceInCm * 2.54;
distanceInFt = distanceInIn * 12;
printf("Calculating........\nThe result is:\n\nMeter: %f\nCentimeter: %f\nInches: %f\nFeet: %f\n", distanceInM, distanceInCm, distanceInIn, distanceInFt);


by the line:

printf("Calculating........\nThe result is:\n\nMeter: %f\nCentimeter: %f\nInches: %f\nFeet: %f\n", distanceInKm * 1000, distanceInKm * 1000 * 100, distanceInKm * 1000 * 100 * 2.54, distanceInKm * 1000 * 100 * 2.54 * 12) ;

This way although the readability of the program is hampered, but we save a nice amount of space since we would no longer need any variables other than ‘distancInKm’.

Output(s)



Thursday, March 20, 2014

Reverse of a Number – Linux Shell Scripting

Problem Question


Write a script to display the given number in reverse order.

Explanation of Problem


Here we wish to write a Linux Shell Script that would accept one command line parameter (integer) and reverse it. A sample run should yield the output of the following kind:
sh ReverseNumber.sh 123
the output should be 321.

Code



#*ReverseNumber*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 20-03-2014
n=$1
a=""
while [ $n -gt 0 ]
 do
  a=$( echo ${a}$(( $n % 10)) )
  n=$(( $n / 10))
 done
echo $1 in Reverse Order is $a

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

n=$1 -> -> We save the command line argument into a variable named ‘n’. This variable is required since we are going to use it to segregate the digits by recursively dividing it with 10 and storing the remainder.

a="" -> ‘a’ is our string variable here which is going to hold he answer, the reverse number.

while [ $n -gt 0 ] -> Our main loop of the program which is going to extract the digits one by one from the variable ‘n’ and store it into our variable ‘a’. For this purpose we us the line a=$( echo ${a}$(( $n % 10)) ) where we do the following –
The value of the last digit is extracted by applying modulus function to the number. We use the echo command to display the current value of variable ‘a’ followed by this extracted digit. But since we enclose this echo inside another $, we store the result of the echo to the variable ‘a’ rather than displaying it on the terminal. Thus we build up the string ‘a’ holding the reverse of the number as we traverse through the loop.

n=$(( $n / 10)) -> Since we have used the last digit in the above line, thus we reject it using this line of code so that we are left with the remaining part of the number.

do done -> While loop block delimiters.

echo $1 in Reverse Order is $a -> We this time use the echo command of the linux shell to display the output to the screen. The output, i.e. the reverse number is stored in variable ‘a’ while ‘$1’ denotes the command line argument, i.e. our original number.

Output(s)



Wednesday, March 19, 2014

Sum of Digits – Linux Shell Scripting

Problem Question


Write a script to calculate the sum of digits of the given number.

Explanation of Problem


Here we wish to write a Linux Shell Script that would accept one command line parameter (integer) and find the sum of it’s digits. Thus, in a sample run like:
sh SumOfDigits.sh 123
the output should be 6.

Code



#*SumOfDigits*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 19-03-2014
x=$1
a=0
b=0
while [ $x -gt 0 ]
 do
  a=$(( $x % 10 ))
  x=$(( $x / 10 ))
  b=$(( $b + $a ))
 done
echo Sum of digits of $1 is $b

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

x=$1 -> We save the command line argument into a variable named ‘x’. This variable is required since we are going to use it to segregate the digits by recursively dividing it with 10 and storing the remainder.

a=0 b=0 -> We use the variable ‘a’ to store the remainder using a=$(( $x % 10 )) and variable ‘b’ to store the sum using b=$(( $b + $a )).

while [ $x -gt 0 ] -> We use this while loop to do the operations stated above. Apart from that, we divide ‘x’ by 10 using x=$(( $x / 10 )) everytime in the loop and store the answer in ‘x’ because we want to reject the last digit as soon as we have stored it in variable ‘a’.

do done -> While loop block delimiters.

echo Sum of digits of $1 is $b -> echo command of the linux shell is then used to display the string following it. ‘$1’ implies the first command line argument, and ‘$b’ the sum we were required to calculate.

Output(s)



Tuesday, March 18, 2014

Factorial – Linux Shell Scripting

Problem Question


Write a script to calculate the factorial of a given number

Explanation of Problem


Here we wish to write a Linux Shell Script that would accept one command line parameter and find the factorial of that number.

Code



#*Factorial*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 18-03-2014
fact=1
for (( i=1;i<=$1;i++ ))
 do
  fact=$(($fact*$i))
 done
echo Factorial of $1 is $fact

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

fact=1 -> We initialise a variable ‘fact’ that would hold the value of the final answer. We initialise it to one because we are going to multiply it recursively (1 being the multiplicative identity).

for (( i=1;i<=$1;i++ )) -> Our main loop where we multiply the number(say n) with all numbers from 1 to (n – 1). We do this by using fact=$(($fact*$i)), where the variable ‘fact’ is multiplied by the loop counter (‘i’) and at the same time we store the value in ‘fact’ itself since we have to multiply it with more numbers(probably). The loop counter ‘i’ helps by taking the values ‘1’ to ‘n – 1’ to be multiplied by the number whose factorial was to be found.

do done -> The for loop block delimiters.

echo Factorial of $1 is $fact -> echo command of the linux shell used to display the string following it to the standard output display of the terminal. ‘$1’ represents he first command line argument (the number whose factorial is to be calculated).

Output(s)



Monday, March 17, 2014

Fibonacci Series upto n terms – Linux Shell Script

Problem Question


Write a script to print the Fibonacci series upto n terms

Explanation of Problem


Here we wish to write a Linux Shell Script that takes a command line parameter which denotes upto which term we wish to generate Fibonacci series, and generate the same.

Code



#*Fibonacci Series*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 17-03-2014
f1=0
f2=1
echo""
echo "Fibonacci sequence for n=$1 is : "
echo""
for (( i=0;i<=$1;i++ ))
 do
  echo -n "$f1 "
  fn=$((f1+f2))
  f1=$f2
  f2=$fn
 done
echo " "
echo""

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

f1=0 f2=1 -> The first two terms of the Fibonacci Series(fixed).

echo"" -> Used to print a blank line

$1 -> The first command line argument

echo -> Linux shell command used to display the string following it to the standard output terminal display.

for (( i=0;i<=$1;i++ )) -> For loop used to loop with the code that calculates and prints the next term.

echo -n "$f1 " -> The ‘-n’ option of echo command makes the output to print in the same line. Please note a single whitespace after ‘$f1’ that I have used so that the terms are well separated.

fn=$((f1+f2)) -> We declare a variable ‘fn’ and assign it the value of expression ‘(f1+f2)’

f1=$f2 f2=$fn -> f1 is given the value of f2, and f2 the value of the new term we just found. Actually in Fibonacci series, the new term is calculated as the sum of previous two terms. Thus, we need a track of previous two terms, for which we use f1 and f2.

do done -> for loop delimiters

Output(s)



Sunday, March 16, 2014

Check if the number is prime – Linux Shell Script

Problem Question


Write a script to check whether the given number is prime or not

Explanation of Problem


Here we wish to write a Linux Shell Script that would take a command line argument and check if that number is prime or not and print the result (PRIME or NOT PRIME) on the terminal.

Code



#*Check Prime*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 16-03-2014
x=`expr $1 / 2`
i=2
while [ $i -le $x ]
 do
  if [ `expr $1 % $i` -eq 0 ]
   then
    echo Not Prime
    exit
  fi
  i=`expr $i + 1`
 done
echo Prime

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

x=`expr $1 / 2` -> We declare a variable ‘x’ and assign it a value which is equal to half that of the first command line argument. This will help us know where to stop our loop which will divide the number with every integer until it finds the remainder of the division to be zero. Thus we can limit the loop counter to half the value of the number to be checked. Thus we use while [ $i -le $x ] as our loop.

i=2 -> This is our loop counter. We start at 2 since every number is divisible by 1.

if [ `expr $1 % $i` -eq 0 ] -> As soon as we find the remainder of the division is zero, we use echo Not Prime to display Not Prime on the terminal, and with the exit command we close our shell running the script, i.e., the script terminates.

i=`expr $i + 1` -> Loop counter incremented by one.

echo Prime -> If the control reaches here, it means that the number is not prime since it was not divisible by any of the numbers (upto half the number itself). Thus, we print Prime on the terminal.

then fi -> if block delimiters.

do done -> while block delimiters.

Output(s)



Saturday, March 15, 2014

C Program to calculate gross salary (DA=40%, HRA=20%, Input Salary)

Problem Question


Ramesh's basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.

Explanation of Problem


We got a very simple problem at hand. We need the user to enter a value which is Ramesh's Basic Salary. Then we have to add to it, it's 40% and 20% to get the gross salary.

Code


/*Ramesh's Gross Salary *
*@Language: ANSI C *
*@Compiler: GNU GCC *
*@IDE: CodeBlocks 12.11 *
*@Author: Toxifier *
*@URL: http://letsplaycoding.blogspot.com/ *
*@Date: 15-03-2014 **/

#include <stdio.h>

int main()
{
    printf("\n\nEnter Ramesh's salary: ");
    int rameshSalary = 0;
    scanf("%d", &rameshSalary);
    printf("Dearness allowance: 40 percent and House Rent allowance: 20 percent\nCalculating...\n\n");
    float grossSalary = rameshSalary + rameshSalary * 0.2 + rameshSalary*0.4;
    printf("Ramesh's gross salary = %f\n", grossSalary);
    system("pause");
    return 0;
}

Explanation of Code


#include <stdio.h> -> This statement calls the C Preprocessor to link the STDIO header file which has some basic functions we use in any C program, like printf and scanf.

int main() -> The starting point/entry point of the program execution. We use this function to call any other function in a C program. In ANSI C specification, main must return an integer value, that's why the return type is 'int'.

printf() -> This function takes as argument a string and displays that on the user's terminal. The first argument is the string to be displayed, while rest of the arguments are different values(generally variables/constants declared in our program) which are to be displayed.

scanf() -> This function makes the program to wait until the user enters some value and presses 'space' or 'enter' key. This is is a standard input function which takes as argument, a string and the addresses of the memory where to store the value entered by the user.

&rameshSalary -> Denotes the address of he variable 'rameshSalary'.

system("pause") -> I use this function to display the Press any key to continue message. Please note, this function may or may not work on your compiler, and it's use is completely optional. If you use CodeBlocks, you won't need this in this program. If you use DevC++, then you'll need this, and if you use TurboC then this function won't work at all!

return 0 -> In ANSI C, main generally returns zero when there is a normal execution and termination of the program.

Output(s)



Friday, March 14, 2014

Average of n numbers - Linux Shell Scripting

Problem Question


Write a script to calculate the average of n numbers

Explanation of Problem


Here we wish to write a Linux Shell Script which when executed any number of command line arguments, calculates their average(integer value only). So if the script is executed as the following, the outputs would be as under.

sh AverageCalculator.sh

ERROR

sh AverageCalculator.sh 1

1

sh AverageCalculator.sh 1 2

1

sh AverageCalculator.sh 1 2 3

2

sh AverageCalculator.sh 1 2 3 4 5 23 234 234 234 23 234 235 123 14

97

Code



#*Average Calculator*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 14-03-2014

sum=0
for i in $*
 do
  sum=`expr $sum + $i`
 done
avg=`expr $sum / $#`
echo $avg

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

sum=0 -> We declare a variable 'sum' and initialize it to value zero. We will be using it for holding the sum of all the values passed as command line arguments.

for i in $* -> Here we initialize a for loop which travels through the whole list in the command line. '$*' imply the list of command line arguments. 'i' is the loop counter variable we have introduced. It could have been anything else than 'i' also.

sum=`expr $sum + $i` -> We tell the shell to store the value of the expression, (sum + i) in the variable sum. We repeat this since we are in a 'for' loop. Thus we get the sum of all the numbers in the command line arguments list.

avg=`expr $sum / $#` -> '$#' implies the number of command line arguments. Thus, we introduce a new variable named 'avg' that would hold the integer value returned by the division of 'sum' and '$#'.

echo $avg -> echo command writes the value following it to the standard display terminal.

do done -> do and done are the delimiters of the loop block. They can be understood similar to the {}braces in C/C++.

Output(s)



Thursday, March 13, 2014

Check if the given number is even or odd - Linux Shell Scripting

Problem Question


Write a script to check whether the given no. is even/odd

Explanation of Problem


Here we wish to write a Linux Shell Script that checks if the first number passed as command line argument is even or odd. So when executing the script EvenOdd.sh as under:

sh EvenOdd.sh 1

should give the answer as 1 is odd

and when run as

sh EvenOdd.sh 2

should give the output as 2 is even

Code



#*Even Odd Check*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 13-03-2014

x=`expr $1 % 2`
if [ $x -eq 0 ]
  then
   echo $1 is even
else
 echo $1 is odd
fi

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

x=`expr $1 % 2` -> We introduce a new variable 'x' to our shell. Then, we tell it to assign 'x' the value that follows the '=' sign. The shell then encounters `` which makes it understand the expression inside will return something that has to be assigned to 'x'. Then we tell it that this is an expression, by using the keyword 'expr' which is followed by the expression. Note that the whole expression is quoted as `expr YOUR EXPRESSION`. Then we assign the expression as Command Line Argument 1(implied by $1) modulus 2. We apply the modulus operator (%) and thus we find the remainder when we divide $1 by 2.

if [ $x -eq 0 ] -> Here we have our if block. The condition says if $x is zero. Note that now we use a $ sign with x since the variable is already declared. If a number is even, it will give a remainder zero when divided by 2, else not. This is what we check.

then -> follows the code that has to executed in case the if condition is true. That means the remainder on dividing the first command line argument with 2 is zero. Thus we print $1 is even.

else -> Starts our else block executed in case the if condition fails. That means the remainder ain't zero when we divide $1 by 2. Thus we print $1 is odd.

echo -> Linux shell command used to print to standard output, the terminal display.

fi -> End of the if block.

Output(s)



Wednesday, March 12, 2014

Find the greatest of three numbers (passed as command line parameters) - Linux Shell Scripting

Problem Question


Write a script to find the greatest of three numbers (numbers passed as command line parameters)

Explanation of Problem


We need to write a Linux Shell Script that when executed, will find the greatest of the three numbers. These numbers should be passed as command line arguments. This means that, if the name of our script is GreatestOfThree.sh, then we execute it as under to get the result:

sh GreatestOfThree.sh 23 121 1

and the result should be 121

Code




#*Greatest of Three Numbers*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 12-03-2014

if [ $1 -gt $2 ]
 then
  if [ $1 -gt $3 ]
  then
   echo $1 is the greatest
  else
   echo $3 is the greatest
fi
else
 if [ $2 -gt $3 ]
  then
   echo $2 is the greatest
  else
   echo $3 is the greatest
 fi
fi

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

$1, $2, ... $n -> The nth command line argument
if [ x -gt y ] -> -gt check if the argument before it is greater than the one that follows it.
then -> In case the 'if' condition passes, this part of code is executed that follows 'then'
else -> In case the 'if' condition fails, this part of code is executed that follows 'else'
fi -> Closes the 'if' or 'if-else' block

In the code above what we did is, first we checked if the first command line argument is greater than the second, if yes, we check if it is greater than the third. If this is also true, we print the first argument using '$1' followed by the phrase is the greatest. If the second if block fails, it means that $1>$2, but $1<$3 => $3 is the greatest. Then, we print the third argument using '$3' followed by the phrase is the greatest.

If the first if block fails, then we compare second and third argument. After testing again, we do the same thing as above.

Output(s)




Tuesday, March 11, 2014

Hello World: C

Problem Question


Write the Hello World Program in C Language

Explanation of Problem


Hello World Program, is the first program generally taught when you take some programming classes. This program is one of the simplest program to write and perhaps every coder has written this once in their life. This program helps in checking that the compiler is working fine as far as the basic functionality is concerned.

Code




/*Hello World program
*Language: ANSI C
*Compiler: GNU GCC
*IDE: CodeBlocks 12.11
*Written by: Toxifier
*URL: http://letsplaycoding.blogspot.com/
*Date: 11-03-2014*/

#include <stdio.h>

int main()
{
printf("Hello World, from Toxifier");
return 0;
}


Explanation of Code


#include <stdio.h> -> This statement calls the C preprocessor to include the Header File named STDIO(Standard Input/Output). Thus, all the functions declared in this header file(and defined in it's linked file) are available for your use in the program.

int main() -> The starting point of program execution is the main function. In ANSI C, main needs to be returning an integer value, that's why the return type is int

printf("Hello World, from Toxifier") -> This statement calls the printf function from stdio and which prints the string that is passed to it.

return 0 -> A zero returned implies no problem during execution. In ANSI C main returns an int, which is preferably zero. We use non-zero values to indicate an error. The values help in debugging.

{} -> These braces are block delimiters. The statements inside a pair of braces become the part of a block which is sequentially executed.

Output(s)




Saturday, March 08, 2014

Welcome!

Hello friends! :)

I welcome you all to my coding blog. I will be sharing here codes to various programming problems. I'll try to explain all of my codes. I include here codes that I submitted during my college time for labs, or I made when I was reading some programming book, or something I made randomly.

I have formatted each post into following parts:

1. "Problem Question"
2. "Explanation of Problem"
3. "Code"
4. "Explanation of Code"
5. "Output(s)"

For suggestions and queries, feel free to leave comments, or email me. You can find contact information in my Disclosure Policy page.

I hope you find my work helpful. I agree these codes that can be used for completing your assignments, but since I love coding, I suggest you all to try and understand things and submit your original work. Anyways, that's all for the introduction part of this blog and a welcome message. Bon Voyage en mi blog amigos! :D