Sunday, April 27, 2014

Menu Driven Factorial Prime Odd Even - C Program

Problem Question


Write a menu driven program which has following options:
1. Factorial of a number.
2. Prime or not
3. Odd or even
4. Exit

Explanation of Problem


Make use of switch statement.

The outline of this program is given below:


/* A menu driven program */
main( )
{
int choice ;
while ( 1 )
{
printf ( "\n1. Factorial" ) ;
printf ( "\n2. Prime" ) ;
printf ( "\n3. Odd/Even" ) ;
printf ( "\n4. Exit" ) ;
printf ( "\nYour choice? " ) ;
scanf ( "%d", &choice ) ;
switch ( choice )
{
case 1 :
/* logic for factorial of a number */
break ;
case 2 :
/* logic for deciding prime number */
break ;
case 3 :
/* logic for odd/even */
break ;
case 4 :
exit( ) ;
}
}
}
Note: The statement while ( 1 ) puts the entire logic in an infinite loop. This is necessary since the menu must keep reappearing on the screen once an item is selected and an appropriate action taken.

Code


#include <stdio.h>
/*Factorial Prime Odd Even.C*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 27-04-2014**/

int main()
{
  while(1)
  {
    int choice, num, i;
    printf("\nChoose an option:\n\t1. Factorial\n\t2. Prime Check\n\t3. Odd or Even\n\t4. Exit\nChoice: ");
    scanf("%d", &choice);
    switch(choice)
    {
      case 1:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        int factorial = 1;
        for (i = num; i > 1; i--)
          factorial *= i;
        printf("\nThe factorial is: %d\n", factorial);
        break;
      }
      case 2:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        int flag = 0;
        for (i = 2; i < (num / 2 + 1); i++)
        {
          if ( num % i == 0)
          {
            printf("\nNot Prime\n");
            flag = 1;
            break;
          }
        }
        if (!flag)
          printf("\nPrime\n");
        break;
      }
      case 3:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        if (num % 2)
          printf("\nODD\n");
        else
          printf("\nEVEN\n");
        break;
      }
      case 4:
      {
        exit(0);
      }
      default:
      {
        printf("Wrong Choice");
        break;
      }
    }
  }
  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 function has to be 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.

switch ( choice )
{
case 1 :
/* logic for factorial of a number */
break ;
case 2 :
/* logic for deciding prime number */
break ;
case 3 :
/* logic for odd/even */
break ;
case 4 :
exit( ) ;


This part of code represents the menu part. The 'switch' is a block that takes an argument 'choice' (the name can be anything, it is a variable), the value of which drives the program flow to one of the 'case' logics. A 'default' case is a case that executes if the value of the 'choice' doesn't match that of any of the cases. So here, if the user enters '1', '1' gets stored in variable 'choice' and upon seeing the switch statement, the program goes to case 1, that is, 'factorial of a number' in our case.

case 1:
{
printf("\nEnter a number: ");
scanf("%d", &num);
int factorial = 1;
for (i = num; i > 1; i--)
factorial *= i;
printf("\nThe factorial is: %d\n", factorial);
break;
}


In this case, we calculate the factorial of a number. The logic is simple, keep multiplying until the number comes down to 1 from it's value 'n'. That's what the loop above does. It decrements the 'num' entered by 1 each time through the loop, and multiplies it with the running product, the factorial, until 'num' has a value 1.

case 2:
{
printf("\nEnter a number: ");
scanf("%d", &num);
int flag = 0;
for (i = 2; i < (num / 2 + 1); i++)
{
if ( num % i == 0)
{
printf("\nNot Prime\n");
flag = 1;
break;
}
}
if (!flag)
printf("\nPrime\n");
break;
}


In this case, the usr enters a number and the statements check whether the number is Prime or not. How do we acheive this? Simple! If a number is not divisible by any number (less than or equal to half the number itself), it is a prime number. The loop does the same thing. It divides the number by every natural number except 1, till the counter reaches half the number. As soon as the number is found to be divisible, we break out of the loop and print 'NOT PRIME' on the screen. Once the program is out of the loop, the 'flag' value is tested if the program came out of the loop normally, or the break made it to come out of the loop. If the former is tha case, we print 'PRIME' on the screen.

case 3:
{
printf("\nEnter a number: ");
scanf("%d", &num);
if (num % 2)
printf("\nODD\n");
else
printf("\nEVEN\n");
break;
}


In this case, the user enters a number, and we divide it by 2. If the number is divisible by 2, it is even, else odd and we print the result.

case 4:
{
exit(0);
}
default:
{
printf("Wrong Choice");
break;
}


Case 4 represents the case when the user wants to exit the program. In such a scenario, we call the 'exit()' function, with a value '0' which represents a normal exit status. The defaul case, represents the case when the yser enters a choice for which no case is defined in the switch block. In my program, I just print 'Wrong Choice' on the screen.

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, April 18, 2014

Pattern – C Program

Problem Question


Write a program to produce the following output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Explanation of Problem


This is a simple pattern printing program. A carefully taken set of loops (and nested loop) with well formatted printf() function makes this a very easy program to make. The only aim of this program is to print the above pattern. The above pattern is a Pascal’s Triangle. Each value in Pascal’s Triangle can be computed in two ways:
  1. Sum of two terms from upper row
  2. By combination logic: n! / k! * (n-k)!, where n is the row number, and k represents the kth entry of that row. I am going to use this method in my program.

Code


#include <stdio.h>
/*PATTERN2.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Block 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 18-04-2014**/
int main()
{
  int i, j, k = 1, iFactorial, jFactorial, dFactorial;
  for (i = 0; i < 5; i++)
  {
    for (j = i - 4; j <= 0; j++)
      printf(" ");
    iFactorial = 1;
    for (k = i; k > 0; k--)
      iFactorial = iFactorial * k;
    for (j = 0; j <= i; j++)
    {
      jFactorial = 1;
      for (k = j; k > 0; k--)
        jFactorial = jFactorial * k;
      dFactorial = 1;
      for (k = i - j; k > 0; k--)
        dFactorial = dFactorial * k;
      printf("%d ", iFactorial/(jFactorial * dFactorial));
    }
    printf("\n");
  }
  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 function has to be 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 i, j, k = 1, iFactorial, jFactorial, dFactorial; -> The variable ‘i’ is the loop variable for outer loop, ‘j’ is the loop variable for the inner loop that prints the numbers of the pattern, and the variable ‘k’ is used as the loop variable for the loops that computer the factorial values of the row number(n! which is iFactorial), entry number(k! which is jFacotrial), and the factorial of their difference (n-k)! which is dFactorial in this program.

The outer for loop, for (i = 0; i < 5; i++) , is used to print the pattern in 5 distinct lines. To achieve this, all other printing loops are nested inside this, and at the end of this loop there is a printf() function printing a newline character.
The counter ‘i’ of the outermost loop is used to print a specific number of spaces at the beginning of each line using the first nested loop, for (j = i - 4; j <= 0; j++). It is quite evident that this loop prints, 4 spaces in the first line, 3 in 2nd, 2 in 3rd, 1 in 4th and no space in 5th line.

for (j = 0; j <= i; j++) -> This loop is used to calculate the entries and print them.

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.

Rest of the program is self-explanatory, or can be inferred correctly from the logic explained under the ‘explanation of problem’ heading.

Output(s)



Thursday, April 17, 2014

Pattern – C Program

Problem Question


Write a program to produce the following output:


   1
  2 3
 4 5 6
7 8 9 10


Explanation of Problem


The problem needs us to make a program that would print the above pattern. It is a pretty simple program, with a simple logic of printing a number of spaces before each line, and a single space between each number.

Code


#include <stdio.h>
/*PATTERN1.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 17-04-2014**/
int main()
{
  int i, j, k = 1;
  for (i = 1; i <= 4; i++)
  {
    for (j = i - 3; j <= 0; j++)
      printf(" ");
    for (j = i; j > 0; j--)
      printf("%d ", k++);
    printf("\n");
  }
  system("pause");
}

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 function has to be 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 i, j, k = 1; -> Variables ‘i’ and ‘j’ are loop variables. Variable ‘k’ is used to print the numbers which we require in the pattern, which is why I initialised it to 1 and post-increment it in the printf() function.

The outer for loop, for (i = 1; i <= 4; i++) is used because I wish to print 4 lines in my pattern. At the end of this loop, I use printf() to print a new line at each iteration.

The first inner for loop, for (j = i - 3; j <= 0; j++) is used to print the spaces at the beginning of each line in the pattern. It is quite evident from the question that we need 3 spaces before 1(beginning of first line), 2 before 2(beginning of second line), 1 before 4(beginning of third line), and no space before 7(beginning of fourth line). Thus the loop refers to the value of ‘i’ of the the outer loop to achieve this.

The final inner for loop, for (j = i; j > 0; j--) does the printing job of the numbers in the pattern. It prints the numbers (‘i’ numbers per line) of each line, and a space after each number.

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)



Wednesday, April 16, 2014

Octal Convert – C Program

Problem Question


Write a program to find the octal equivalent of the entered number.

Explanation of Problem


It is a simple program that accepts user’s input (integer) and calculate its octal equivalent and displays the result.

Code


#include <stdio.h>
/*Octal Calculator.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 16-04-2014**/
int main()
{
  int number;
  printf("\n\nEnter a 5-digit number:\t");
  scanf("%d", &number);
  printf("The octal equivalent is: 0000");
  while (number > 0)
  {
    printf("%d\b\b", number % 8);
    number /= 8;
  }
  printf("\n\n");
  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 function has to be 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.

while (number > 0)
{
printf("%d\b\b", number % 8);
number /= 8;
}
This is the main part of the program where the calculation takes place. I am not storing the complete octal equivalent as such, rather displaying each digit on the screen as it is calculated. I used the line printf("The octal equivalent is: 0000"); for the output prompt. I have used four zeroes, so that I can display the output in the correct manner. Since I am not storing the digits of the octal output, and my logic calculates the octal equivalent backwards, if I display the digits as it is the result would be reverse of the expected output! So I used four zeroes in the output prompt, and ‘\b’ when I wanted to print the digit. What happens is that, once the digit is printed, the cursor shifts one character ahead. Then upon seeing the ‘\b’ the printf() function forces the cursor to move one space back. I have used two ‘\b’ so that my already printed digit doesn’t get erased by the next digit being printed. Instead of using 4 zeroes, I could have used something else too, but if the user enters a number which has less than 5 digits, the result would contain extra characters that are not required, and zero that I have used is not a problem since a zero to the left of a number doesn’t make a difference. If I used spaces instead, the formatting of the result would be absurd. Like if the user enters a single digit number, the output would be quite far from the output prompt. I have asked the user to enter a 5-digit number because I have formatted the output that way. Else, if you observe, within the limits of ‘int’ any number is acceptable and a CORRECT result will be produced.

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)



Tuesday, April 15, 2014

ASCII Values – C Program

Problem Question


Write a program to print all the ASCII values and their equivalent characters using a while loop. The ASCII values vary from 0 to 255.

Explanation of Problem


We need to make a program that will simply print the ASCII values from 0-255. What we do to achieve this is pretty simple. Just use int ranging from 0 to 255 and during the use of printf() function, use %c to print the corresponding character value.

Code


#include <stdio.h>
/*ASCII.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 15-04-2014**/
int main()
{
  int i = 0;
  printf("\n\nASCII VALUES\n\n");
  while (i <= 255)
  {
    printf("%d: %c", i, i);
    if(i % 5)
      printf("\t");
    else
      printf("\n");
    i++;
  }
  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 function 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.

printf("%d: %c", i, i); -> With %d the number (integer itself) is printed, and %c prints the corresponding ASCII character.

if(i % 5)
printf("\t");
else
printf("\n");

There’s nothing big about this piece of code. I have used this just to format the output. Using this I got 5 characters per line printed.

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)




Monday, April 14, 2014

Matchsticks Game – C Program

Problem Question


Write a program for a matchstick game being played between the computer and a user. Your program should ensure that the computer always wins. Rules for the game are as follows:

− There are 21 matchsticks.
− The computer asks the player to pick 1, 2, 3, or 4 matchsticks.
− After the person picks, the computer does its picking.
− Whoever is forced to pick up the last matchstick loses the game.

Explanation of Problem


The user should make the first move. You have to ensure that you win in all cases. For the given problem with 21 matchsticks, the logic is quite simple. Whatever the user picks, the computer should pick somehow that the total of the two become 5. Like if user picked 1, computer picks 4; if user picked 3, computer picks 2; etc. This will ensure that the computer will always win.

Code


#include <stdio.h>
/*MATCHSTICKS.C*
*@Language: ANSI C*
*@Compiler: GNU GCC *
*@IDE: Code::Blocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 14-04-2014**/
int main()
{
  int availableMatchSticks = 21, pickedMatchSticks = 0, lastChance = 1;
  printf("\nAvailable MatchSticks: %d", availableMatchSticks);
  while (availableMatchSticks > 0)
  {
    pickedMatchSticks = 0;
    while (pickedMatchSticks < 1 || pickedMatchSticks > 4 || availableMatchSticks - pickedMatchSticks < 0)
    {
      printf("\nPick matchsticks: (1/2/3/4): ");
      scanf("%d", &pickedMatchSticks);
      if (pickedMatchSticks < 1 || pickedMatchSticks > 4 || availableMatchSticks - pickedMatchSticks < 0)
        printf("\aWrong move! Try again!");
    }
    availableMatchSticks -= pickedMatchSticks;
    lastChance = 1;
    printf("\nAvailable MatchSticks: %d", availableMatchSticks);
    if (availableMatchSticks == 0)
      break;
    printf("\nComputer's Turn..Please Wait...\n");
    pickedMatchSticks = 5 - pickedMatchSticks;
    printf("\nComputer Picked: %d", pickedMatchSticks);
    availableMatchSticks -= pickedMatchSticks;
    printf("\nAvailable MatchSticks: %d", availableMatchSticks);
    lastChance = 0;
  }
  if(lastChance == 1)
    printf("\nYou lose!\n");
  else
    printf("\nYou win!\n");
  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 function 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.

while (availableMatchSticks > 0) -> Make sure the program ends as soon as the matchsticks count reaches 0.

pickedMatchSticks = 0; -> Before the start of next turn (of the payer-computer move pair), we set the pickedMatchsticks count to 0. I did this because in my next line I check if the user makes a wrong move, which includes picking less than 1 matchstick, more than 4 matchsticks, or picking more than available matchsticks. I do his checking in the nested while loop:
while (pickedMatchSticks < 1 || pickedMatchSticks > 4 || availableMatchSticks - pickedMatchSticks < 0)
{
printf("\nPick matchsticks: (1/2/3/4): ");
scanf("%d", &pickedMatchSticks);
if (pickedMatchSticks < 1 || pickedMatchSticks > 4 || availableMatchSticks - pickedMatchSticks < 0)
printf("\aWrong move! Try again!");
}

Asking for the user to input unless a legal move is made.

availableMatchSticks -= pickedMatchSticks; -> After each move I make sure I decrease the count of matchsticks available. I do this once after the player has made his move, and once again after the computer has made his move.

lastChance -> The variable ‘lastChance’ is used to check who is the person(user or computer) who moved the last time before the program came out of the loop. Thus deciding, who is the loser? I set this variable after the player’s move and also after the computer’s move. In my program,
if(lastChance == 1)
printf("\nYou lose!\n");
else
printf("\nYou win!\n");

I mean if the value of lastChance is 1 the user has lost the game, else he has won. Though the latter won’t happen! ;)

if (availableMatchSticks == 0)
break;
-> If the matchstick count reaches 0 after the user’s move, I cannot let the computer make the next move. Thus, I break out of the while loop as soon as this happens.

pickedMatchSticks = 5 - pickedMatchSticks; -> This is the main logic of the program causing the computer to always win! Since we have 21 matchsticks and we wish that the last matchstick remains for the user, I ask the computer to keep the sum of matchsticks picked by the user and computer to be 5, so that in the final move, only one matchstick is left which the user is forced to pick. As long as the total count of matchsticks is of the order (10n +1, where n is a Natural Number), and the user makes the first move, this logic will ensure the computer always wins.

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, April 12, 2014

X^Y (X raised to Y) – C Program

Problem Question


Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another.

Explanation of Problem


Our program shall accept 2 numbers from the user, and find the value of one number raised to the power of another. For simplicity, we are making it to be the first number raised to the second.

Code


#include <stdio.h>
/*X raised to Y.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 12-04-2014**/
int main()
{
  int num1, num2, product = 1;
  printf("\n\nPlease enter 2 numbers: ");
  scanf("%d%d", &num1, &num2);
  printf("\n\nCALCULATING.......\n\n");
  while(num2 > 0)
  {
    product = product * num1;
    num2--;
  }
  printf("\nAnswer is: %d\n", product);
  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 function 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.

while(num2 > 0) {
product = product * num1;
num2--;
}
Here we have the main part of the program where the calculation takes place. We multiply the value of the variable ‘product’ with the value of the variable ‘num1’ and store the result in the variable ‘product’. We then decrement the value of variable ‘num2’. We iterate this procedure in a while loop until num2 becomes 0. This way we have the value of (num1^num2) stored in the variable ‘product’ which we then display on the screen.

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, April 11, 2014

Factorial of a Number – C Program

Problem Question


Write a program to find the factorial value of any number entered through the keyboard.

Explanation of Problem


We need to write a program which shall accept a whole number from the user, calculate its factorial, and print the result.

Code


#include <stdio.h>
/*Factorial.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 11-04-2014**/
/*Note: This program works with integers only.
Carefully choose input such that the output doesn’t go out of the int range.*/
int main()
{
  int number, factorial = 1;
  printf("\n\nEnter a number: ");
  scanf("%d", &number);
  while(number >= 1)
  {
    factorial *= number--;
  }
  printf("\nFactorial: %d\n", factorial);
  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 function 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.

while(number >= 1) {
factorial *= number--;
}
This is the code where we calculate the factorial of the number user entered. We decrement the variable ‘number’ at each iteration of the while loop because we want to calculate the factorial using the formula: n! = n X (n-1) X (n-2) X…..X 2 X 1
Thus the limits/condition of the while loop is self-explanatory.
factorial *= number--; multiplies the value of variable ‘factorial’ with the value of variable ‘number’, stores the result in the variable ‘factorial’ and then decrements the value of the variable ‘number’.

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, April 04, 2014

Leap Year Check - C Program

Problem Question


Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.

Explanation of Problem


We want our program to accept user’s input, an integer which shall represent a year. Our program should check whether or not it is a leap year. For an year to be leap, it should be divisible by 4 and not divisible by 400.

Code


#include <stdio.h>
/*LEAP CHECK*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 04-04-2014**/
int main()
{
  int year;
  printf("\n\nEnter an year: ");
  scanf("%d", &year);
  if (!(year % 4) && (year % 400))
    printf("\n\nLEAP\n\n");
  else
    printf("\n\nNOT LEAP\n\n");
  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 function 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.

(!(year % 4) && (year % 400)) -> This is the main logic of the program. ‘year’ stores the value user entered. If we wish that the number entered represent a leap year, then ‘year%4’ must be zero (year is divisible by 4), and ‘year%400’ should not be zero (year is not divisible by 400). I used a ‘!’ (LOGICAL NOT) on the first condition, and used ‘&&’ (LOGICAL AND) between the two conditions of checking the divisibility of the variable ‘year’. LOGICAL AND helps in making sure that when both the conditions are true (1. year is divisible by 4; 2. Year is not divisible by 400), the value of year represents a LEAP year.
To explain the logic I have used, consider a few cases:
  1. year=1998: In this case, let’s analyse our condition, (!(year % 4) && (year % 400)). For the first part, !(year % 4), year%4 returns a non-zero value since 1998 is not divisible by 4. Thus, !(year%4) turns out to be zero. Since it is followed by &&, and the first condition is denoting false, the program won’t check divisibility by 400 condition. Hence, NOT LEAP will be printed on screen.
  2. year=2000: In this case, let’s analyse our condition, (!(year % 4) && (year % 400)). For the first part, !(year % 4), year%4 returns a zero since 2000 is divisible by 4. Thus, !(year%4) turns out to be non-zero. Since it is followed by &&, and the first condition is denoting true, the program would check divisibility by 400 condition. On checking the second condition, (year % 400), we see that 2000 is divisible by 400, and hence (year % 400) returns 0. Now && is applied like, 1 && 0, thus, returning zero. Hence, NOT LEAP will be printed on screen.
  3. year=2004: In this case, let’s analyse our condition, (!(year % 4) && (year % 400)). For the first part, !(year % 4), year%4 returns a zero since 2004 is divisible by 4. Thus, !(year%4) turns out to be non-zero. Since it is followed by &&, and the first condition is denoting true, the program would check divisibility by 400 condition. On checking the second condition, (year % 400), we see that 2004 is not divisible by 400, and hence (year % 400) returns non-zero value. Now && is applied like, 1 && 1, thus, returning 1. Hence, LEAP will be printed on screen.

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)



Thursday, April 03, 2014

Odd Even Check – C Program

Problem Question


Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

Explanation of Problem


The program accepts the user input, an integer, and checks whether it is an odd number or even number.

Code


#include <stdio.h>
/*Odd Even Check*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 03-04-2014**/
int main()
{
    int num = 0;
    printf("\n\nEnter a number(integer): ");
    scanf("%d", &num);
    if (num%2)
    {
        printf("\n\nODD");
    }
    else
    {
        printf("\n\nEVEN\n\n");
    }
    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 function 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.

num%2 -> returns 0 if the number is even, else the number is odd. So the statement if (num%2) reflects the condition to be executed if the expression num%2 returns a number other than 0. Thus we print odd in that case. The else condition reflects the case when the expression num%2 returns 0, that means a number is completely divisible by 2 and leaves a remainder 0. Thus the the number should be even in that case. The ‘%’ (modulus operator) finds the remainder on dividing the number on left by the number on right of the ‘%’. Thus, an even number on division with 2 would leave a remainder 0 (the else condition) and an odd number would leave a remainder 1 (the if condition).

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)



Wednesday, April 02, 2014

Sum of first and last digit – C Program

Problem Question


If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of this number.

Explanation of Problem


In this program the user will enter a 4-digit number. The program should extract the first and last digit of the number, find their sum, and display the result.

Code


#include <stdio.h>
/*Sum of first-n-last digit*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodelBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 02-04-2014**/
int main()
{
    printf("\n\nEnter a four digit number: ");
    int number, digitSum = 0, digit1, digit4;
    scanf("%d", &number);
    printf("\nCalculating sum of digits......");
    digit1 = (number % 10000) / 1000;
    digit4 = (number % 10);
    digitSum = digit1 + digit4;
    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 function 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 % 10000) / 1000;
digit4 = (number % 10);

The above piece of code reflects the part of the code in which we extract all the digits of the 4-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 10000. On dividing, the remainder found, with 1000, I found the digit at the 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 ones digit is found. You can try it on paper to justify my statement to yourself.

Once I have found the first and fourth digit of the four-digit number, I use the statement digitSum = digit1 + digit4; to find their sum.

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)



Tuesday, April 01, 2014

Number Reverser – C Program

Problem Question


If a five-digit number is input through the keyboard, write a program to reverse the number.

Explanation of Problem


In this program the user enters a 5 digit number. The program should be able to reverse the number. For example if the user enters 12345, the output should be 54321.

Code


#include <stdio.h>
/*Number Reverser*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: CodeBlocks 12.11*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 01-04-2014**/
int main()
{
    printf("\n\nEnter a five digit number: ");
    int number, reverseNumber = 0, digit1, digit2, digit3, digit4, digit5;
    scanf("%d", &number);
    printf("\nCalculating reverse of number......");
    digit1 = (number % 100000) / 10000;
    digit2 = (number % 10000) / 1000;
    digit3 = (number % 1000) / 100;
    digit4 = (number % 100) / 10;
    digit5 = (number % 10);
    reverseNumber = (digit5 * 10000) + (digit4 * 1000) + (digit3 * 100) + (digit2 * 10) + digit1;
    printf("\nThe reverse of number is: %d\n", reverseNumber);
    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 function 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 it on paper to justify my statement to yourself.

reverseNumber = (digit5 * 10000) + (digit4 * 1000) + (digit3 * 100) + (digit2 * 10) + digit1; -> In this statement I calculate the final number we required. So I just did the necessary multiplications which are quite self-explanatory.

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)