Showing posts with label Yashawant Kanetkar. Show all posts
Showing posts with label Yashawant Kanetkar. Show all posts

Monday, July 27, 2015

Copy Array to another Reverse Order - C Program (Procedural)


Problem Question



Write a program to copy the contents of one array into another in the reverse order.

Explanation of Problem



The user enters 25 numbers in an array. The program needs to copy this array into another in reverse order.




Code



#include <stdio.h>
/**@Title: ReverseArray.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 27-07-2015*
*/

int main()
{
    int arr1[25], arr2[25], i, j;
    for ( i = 0, j = 24; i < 25; i++, j-- )
    {
        scanf ("%d", &arr1[i]);
        arr2[j] = arr1[i];
    }
    printf("\nArray 1\n");
    for ( i = 0; i < 25; i++ )
    {
        printf("%d ", arr1[i]);
    }
    printf("\nArray 2\n");
    for ( i = 0; i < 25; i++ )
    {
        printf("%d ", arr2[i]);
    }
    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.

int arr1[25], arr2[25], i, j; -> Here we define the variables we are going to use in our program.
arr1[25], arr2[25] hold the user input numbers and reversed array respectively.
i, j are used as the loop variables to loop through the array.

    for ( i = 0, j = 24; i < 25; i++, j-- )
    {
        scanf ("%d", &arr1[i]);
        arr2[j] = arr1[i];
    }


Here we loop through both arrays and do the required things. Look at the for loop definition. We have used the "," (comma) operator to initialise and increment multiple variables. This saves a few lines of code. Loop variables are initialised in one go and incrmeented/decremented in one go as well.
We then take user input to build first array. In the next step we copy that value in the last element of the second array. The loop variable "i" traverses "arr1" from left to right, and loop variable "j" traverses "arr2" from right to left. Hence we increment "i" and decrement "j".

    printf("\nArray 1\n");
    for ( i = 0; i < 25; i++ )
    {
        printf("%d ", arr1[i]);
    }
    printf("\nArray 2\n");
    for ( i = 0; i < 25; i++ )
    {
        printf("%d ", arr2[i]);
    }


Here we just loop through both arrays and print them for reference.

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)









Download Source Code





Thursday, July 09, 2015

Count Number Types C Program - Procedural


Problem Question



Write a program to get the number of odd, even, positive and negative numbers from an array of numbers.

Explanation of Problem



The user enters 25 numbers in an array. The program needs to print the number of odd, even, positive and negative numbers input by the user.




Code



#include <stdio.h>
/**@Title: CountNumberTypes.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 09-07-2015*
*/

int main()
{
    int elements[25], loopCounter, positiveCount = 0, negativeCount = 0, evenCount = 0, oddCount = 0;

    for (loopCounter = 0; loopCounter < 25; loopCounter++)
    {
        printf ("\nEnter Value #%d: ", loopCounter + 1);
        scanf ("%d", &elements[loopCounter]);
        if (elements[loopCounter] < 0)
        {
            negativeCount++;
        }
        else
        {
            positiveCount++;
        }
        if (elements[loopCounter] % 2 == 0)
        {
            evenCount++;
        }
        else
        {
            oddCount++;
        }
    }
    printf ("\nNumber of Positive Numbers: %d", positiveCount);
    printf ("\nNumber of Negative Numbers: %d", negativeCount);
    printf ("\nNumber of Even Numbers: %d", evenCount);
    printf ("\nNumber of Odd Numbers: %d\n", oddCount);
    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 elements[25], loopCounter, positiveCount = 0, negativeCount = 0, evenCount = 0, oddCount = 0; -> Here we define the variables we are going to use in our program.
elements[25] hold the user input numbers.
loopCounter is used as the loop variable to loop through the array. The variables positiveCount, negativeCount, evenCount, oddCount are used to track the count of each type of number.

for (loopCounter = 0; loopCounter < 25; loopCounter++)
    {
        printf ("\nEnter Value #%d: ", loopCounter + 1);
        scanf ("%d", &elements[loopCounter]);
        if (elements[loopCounter] < 0)
        {
            negativeCount++;
        }
        else
        {
            positiveCount++;
        }
        if (elements[loopCounter] % 2 == 0)
        {
            evenCount++;
        }
        else
        {
            oddCount++;
        }
    }


Here we loop through the entire array, get user input, and each input is checked whether it's odd/even/negative/positive. Appropriate count variable is incremented to store the count.

printf ("\nNumber of Positive Numbers: %d", positiveCount);
printf ("\nNumber of Negative Numbers: %d", negativeCount);
printf ("\nNumber of Even Numbers: %d", evenCount);
printf ("\nNumber of Odd Numbers: %d\n", oddCount);


After the loop, here we print the values of each variable to give the output stating the count of each number type in the user input.

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)









Download Source Code





Sunday, June 22, 2014

Sum of Natural Numbers (Recursion) - C Program

Problem Question


Write a recursive function to obtain the running sum of first 25 Natural Numbers.

Explanation of Problem


I have made a more general program that could handle most of the numbers in the integer limits. The user can obtain the desired output by inputting 25 to the program.

Code


#include <stdio.h>

/**@Title: recSumNat.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 22-06-2014*
*/

int recSumNat(int a)
{
  if (a < 1)
    return a;
  else if (a == 1)
    return 1;
  else
    return (a + recSumNat(a-1));
}

int main()
{
  int number;
  printf("\n\nEnter a number: ");
  scanf("%d", &number);
  printf("\n\nSum of Natural numbers upto %d: %d\n\n", number, recSumNat(number));
  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.

if (a < 1) return a; -> If the user enters an integer which is not a Natural Number, the program would return the number itself, since the program is trying to find the sum of natural numbers upto the number entered by the user, that is, first n natural numbers.

else if (a == 1)
return 1;
-> As soon as the value of the 'a' argument becomes 1, the function returns 1.

else
return (a + recSumNat(a-1));
-> For any natural number other than 1, the function returns the sum of the current value of 'a' with the current call to the function, and the value returned by the function when called with 'a-1'. Thus, we are guaranteed to exit the recursive stack as soon as the value of 'a' reaches 1.

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)





Download Source Code


Thursday, June 12, 2014

Binary Equivalent of a Number using Recursion - C Program

Problem Question


A positive integer is entered through the keyboard, write a function to find binary equivalent of this number using recursion.

Explanation of Problem


We need to design a recursive function that could find the binary equivalent of a positive integer. It is a simple program. All our function needs to do is print the (number modulus 2) at each iteration, while we keep feeding the next call with number/2.

Code


#include <stdio.h>
/**@Title: BinaryEquivalent Recursive.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Block 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 12-06-2014*
*/
void binaryEquiRec(long a)
{
  if (a)
  {
    int num = a % 2;
    binaryEquiRec(a / 2);
    printf("%d", num);
  }
}

int main()
{
  long number;
  printf("\n\nEnter a number: ");
  scanf("%ld", &number);
  printf("\nBinary equivalent of %ld is: ", number);
  binaryEquiRec(number);
  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.

if (a) -> Since in each recursive call, we divide the number fed to the function by 2 (binaryEquiRec(a / 2);), this if condition guarantees that the function would return in case 'a' becomes zero, which would mean 'a / 2 = 0', which is rue iff 'a' is zero. I keep dividing the number by 2 in each call because since we use the statement, int num = a % 2; to set 'num' as 'a % 2', it means we should reject the current 2's multiple from the number to keep on going with our calculation (the current multiple has already contributed).

printf("%d", num); -> This statement is used to print the binary equivalent digit by digit. I have called this after the recursive call to get the number in correct order, else I would get the reverse of the binary equivalent. So what happens is that, as soon as the if condition fails, the last function call returns, that means the MSD of the binary equivalent is returned, which must be published as the leading bit.

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)




Download Source Code


Saturday, May 31, 2014

Fibonacci Sequence using Recursion - C Program

Problem Question


Write a Recursive Function to obtain first 25 numbers of a Fibonacci Sequence. In a Fibonacci sequence, the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci Sequence:

1 1 2 3 5 8 13 21 34 55 89...

Explanation of Problem


The problem is simple enough and we just need to print the first 25 terms of the Fibonacci sequence using a recursive function. But I have written a rather general program which could generate the Fibonacci sequence upto nth term. All you need to do is, supply 25 as the input and you will get the first 25 terms.

Code


#include <stdio.h>
/**@Title: RecursiveFibonacci.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 31-05-2014*
*/

int recFibo(int a1, int a2, int num)
{
  if (num)
  {
    printf("%d ", a1);
    return recFibo(a2, a1 + a2, num - 1);
  }
  return 0;
}

int main()
{
  int number;
  printf("\n\nEnter a number: ");
  scanf("%d", &number);
  recFibo(1, 1, number);
  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.

recFibo(1, 1, number); -> This is the call to the recursive function we have designed in this program. Just pass 25 as the value of the variable number to get the sequence upto 25 terms. Else he program is generalised to get results upto nth term (as long as the result is within the range of int, memory & computational power).

int recFibo(int a1, int a2, int num) -> The function that calculates the Fibonacci Sequence. It's input are two successive terms, a1 and a2 which are used to compute the next term. The variable num is the number of times we wish to call this function.

if (num) -> The statement makes sure that the block is executed only if the value of num is non zero. As soon as the value becomes zero, the block is not executed. Please note that on encounter of a negative number, we will get unfavourable results. The program is designed to handle positive int only. In case you wish to handle the negative number situation, you can use, if (num > 0).

printf("%d ", a1); -> Prints the first term. We could have also used a1 + a2, but then we will not able to produce 1 1 in the beginning. So while calling the function from main, if you rather use recFibo(0, 1, number);, then you can use, printf("%d ", a1 + a2); instead.

return recFibo(a2, a1 + a2, num - 1); -> This is the most important line in this program which makes recursive call to the function recFibo. Please note, we have supplied the second term, and third term of any three terms in sequence in this call. Also, we decrement num by 1 on each recursive call, so that our if condition gets violated at right time and the program terminates at the right time.

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)




Download Source Code


Friday, May 23, 2014

Prime Factors of a Number using Recursion - C Program

Problem Question


A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

Explanation of Problem


In this program, we need to devise a function that would find the prime factors of a number recursively.

Code


#include <stdio.h>
/**@Title: PrimeFactorsRec.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 23-05-2014*
*/

void prime(int x)
{
 int a; //loop counter
 for( a = 2; a <= x; a++ )
 {
  if( x % a == 0 )
  {
   printf("%d ",a);
   prime(x/a);
   break;
  }
 }
}

int main()
{
 int number;
 printf("\n\nEnter a number: ");
 scanf("%d", &number);
 prime(number);
 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.

 for( a = 2; a <= x; a++ )
 {
  if( x % a == 0 )
  {
   printf("%d ",a);
   prime(x/a);
   break;
  }
 }


This is the part of code where the calculation takes place. The for loop, for( a = 2; a <= x; a++ ) keeps incrementing the counter, 'a'. We use it to divide the number that user entered. The if condition, if( x % a == 0 ) checks if the number is divisible by the current value of the counter 'a'. If that is the case, we print the number 'a' and call our function prime recursively, but this time with a value 'x/a' rather than 'x'. With this, we are not stuck in an infinite recursion of printing the same prime factor. Since we keep on dividing the number by the prime factor found in last iteration, we are sure of segregating any multiples of this 'found prime factor'. Hence, we avoid getting the composite factors, since the counter always starts at 2. Thus only prime factors get printed on the screen, with a single space separating each of 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.

Output(s)



Friday, May 09, 2014

Prime Factors of a Number - C Program

Problem Question


A positive integer is entered through the keyboard. Write a function to obtain the prime factors of this number.

Explanation of Problem


Our program shall accept an integer from the user and print on screen the prime factors of that number. For example, prime factors of 24 are 2, 2, 2 and 3, whereas prime factors of 35 are 5 and 7.

Code


#include <stdio.h>

/**@Title: PrimeFactors2.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 09-05-2014*
*@Update: Updated version of the 05/05/2014 program called PrimFactors.c*
*/

int main()
{
  int number, i, primeCheck, j, flag = 1;
  printf("\n\nEnter a number: ");
  scanf("%d", &number);
  primeCheck = (number / 2) + 1;
  printf("%d = ", number);
  for ( i = 2; i < number; i++ )
  {
    if ((number % i))
    {
      flag = 1;
    }
    else
    {
      flag = 0;
      break;
    }
  }
  if (flag == 1)
    printf("1 X %d", number);
  else
  {
    for ( i = 2; i <= primeCheck; i++ )
    {
      while ( !(number % i) || (number == i) )
      {
        printf("%d ", i);
        number /= i;
        if ( number > 1 )
          printf("X ");
      }
    }
  }
  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.

int number, i, primeCheck, j, flag = 1; -> The variable 'number' is used to get the user input. The variable 'i' & 'j' are the loop counters. The variable 'primeCheck' is used as the upper limit for the loop that checks if the number entered by the user is prime. Since a number which is prime is not divisible other than 1 and the number itself, it is better to check the numbers upto half the number itself rather than checking every number upto the number. Thus, I have used this assignment statement: primeCheck = (number / 2) + 1;. The variable 'flag' is used as a flag to check condition inside the loop whether to find the prime factors of the number(if the number is not prime) or not (if the number is prime).

for ( i = 2; i < number; i++ )
{
if ((number % i))
{
flag = 1;
}
else
{
flag = 0;
break;
}
}


This is the first for loop which checks if the user entered number is prime. If that is the case we set flag as 1, else as soon as the number is found to be divisible by any number between 1 and the number itself (both exclusive) we set the flag as 0 and break out of the loop.

if (flag == 1)
printf("1 X %d", number);


Once we are out of the first for loop we check the flag. If it is found to be 1, that means the number was prime, and thus we print 1 X number as the output and return.

But if the number is not a prime? Then we use the else case. For simplicity, I will break the else case now. All the statements inside the else block have been enveloped in a for loop:
for ( i = 2; i <= primeCheck; i++ )
In this for loop, we again use the variable 'primeCheck' as the upper limit. Why did I do that? Again the reason being the fact that we need to check only the numbers upto 'primCheck'! We don't have to check the numbers beyond that because the factors need to be whole number (and thus we need to check only half of the numbers since any number bigger than 'number'/2 won't give a integral multiple of the number).


while ( !(number % i) || (number == i) )
{
printf("%d ", i);
number /= i;
if ( number > 1 )
printf("X ");
}


Now let's come to the while loop condition. (number % i) returns true if the number is not divisible by i. I have used !(number % i), i.e., the NOT of the condition, which would return true if the number is divisible by i. (number == i) returns true if the number and i are equal. If any of the two conditions is true, we execute the while loop block. Now since, !(number % i) || (number == i) means that the number is divisible by i (the first condition is explained earlier, and the second one is of course true! the number is always divisible by itself!!), thus the statement printf("%d ", i); prints i since the program flow proves 2 things, i is a prime number and a factor of 'number', thus the prime factor of 'number'. How does it prove that it is a prime factor? To answer this question you can do a little paperwork. In the loop, I am going up the loop. Thus, as soon as I find the smallest number that can divide the variable 'number' I print that number and divide the the variable 'number' by that, and continue this until that number cannot factorize the variable 'number' anymore. So in case the number is even, my loop will keep dividing it by 2 until it turns out to be odd. Thus, the possibility of any other even factor than 2 is removed. Similarly, for 3, we keep dividing the number by 3 until no more '3s' can be extracted from it's factors, thus eliminating all the multiples of '3' from the candidate of being a prime factor. Thus , only prime numbers are left and hence, we get the prime factors only. Thus, we don't need any explicit loop that feeds this loop's 'i' with a prime value only. Hence, out current system is sufficient to find the factors of the number, which are all prime. You can try some examples on paper to verify and also check the program for any erroneous output. Though in my sample runs, none of the outputs were wrong.

The next statement, number /= i; divides the number by 'i' so that we are left with the rest of the number and we are not stuck in an infinite loop of printing the same prime factor again and again.

The next statement,
if ( number > 1 )
printf("X ");

prints an X followed by a space. This improves readability of the output, separating each prime factor by an X. We print this only if the number is greater than 1. If the last division of dividing the number by i resulted in 1, we don't wish to print an extra X or space between the last factor found and nothing. Thus this statement is just meant for improved readability of the program output.

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, May 06, 2014

Sum of Digits of a number Function (Recursive and Non Recursive) - C Program

Problem Question


A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:
(1) Without using recursion
(2) Using recursion

Explanation of Problem


We wish that the user enters a 5 digit number. We have to make 2 functions one of which will calculate the sum of digits normally, and other will use recursion to do the same.

Code


#include <stdio.h>

/**@Title: SumOfDigitsFunctions.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 06-05-2014*
*/

int digSum(int number)
{
  int sum = 0;
  while (number)
  {
    sum += number % 10;
    number /= 10;
  }
  return sum;
}

int digSumRec(int number)
{
  if (number)
    return (number % 10 + digSumRec(number / 10));
  else
    return 0;
}

int main()
{
  int number, sum = 0;
  printf("\n\nEnter a 5 digit number: ");
  scanf("%d", &number);
  printf("\nSum without recursion: %d\nSum with recursion: %d\n\n", digSum(number), digSumRec(number));
  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 digSum(int number)
{
int sum = 0;
while (number)
{
sum += number % 10;
number /= 10;
}
return sum;
}


This is the first function that calculates the sum of digits normally. main() calls this functions with the user entered number as the argument. Inside the function, I have devised a while loop. Why have I used 'number' in the condition? Since I will extract the last digit and add it to the running sum into the variable 'sum', and also divide the number by 10 in each iteration. Once the number turns to be 0 on continuous dividing, the control comes out of the loop, and 'sum' is returned.

int digSumRec(int number)
{
if (number)
return (number % 10 + digSumRec(number / 10));
else
return 0;
}


This is our recursive function. In this case, we do the same thing as above, but instead of while loop, we achieve the same thing using recursion. The if condition is similar to the while loop block in the former function. The statement which executes when the 'if' block condition is true, calls the function digSumRec recursively, but the argument is passed as number / 10 instead of number. Thus as soon as number / 10 returns zero, the if block is not executed. Moreover, the return statement in the if block does the addition part. It extracts the last digit from the 'number' and adds to it what is returned by the recursive call to the procedure.

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, May 05, 2014

Prime Factors of a Number - C Program

Problem Question


A positive integer is entered through the keyboard. Write a function to obtain the prime factors of this number.

Explanation of Problem


Our program shall accept an integer from the user and print on screen the prime factors of that number. For example, prime factors of 24 are 2, 2, 2 and 3, whereas prime factors of 35 are 5 and 7.

Code


#include <stdio.h>

/**@Title: PrimFactors.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 05-05-2014*
*/

int main()
{
  int number, i, primeCheck, j, flag = 1;
  printf("\n\nEnter a number: ");
  scanf("%d", &number);
  primeCheck = (number / 2) + 1;
  printf("%d = ", number);
  for ( i = 2; i < number; i++ )
  {
    if ((number % i))
    {
      flag = 1;
    }
    else
    {
      flag = 0;
      break;
    }
  }
  if (flag == 1)
    printf("1 X %d", number);
  else
  {
    for ( i = 2; i <= primeCheck; i++ )
    {
      flag = 1;
      for ( j = 2; j < i; j++ )
      {
        if ( (i % j) == 0 )
        {
          flag = 0;
          break;
        }
      }
      if ( flag )
      {
        while ( !(number % i) || (number == i) )
        {
          printf("%d ", i);
          number /= i;
          if ( number > 1 )
            printf("X ");
        }
      }
    }
  }
  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.

int number, i, primeCheck, j, flag = 1; -> The variable 'number' is used to get the user input. THe variable 'i' & 'j' are the loop counters. The variable 'primeCheck' is used as the upper limit for the loop that checks if the number entered by the user is prime. Since a number which is prime is not divisible other than 1 and the number itself, it is better to check the numbers upto half the number itself rather than checking every number upto the number. Thus, I have used this assignment statement: primeCheck = (number / 2) + 1;. The variable 'flag' is used as a flag to check conditions inside the loop at various levels.

for ( i = 2; i < number; i++ )
{
if ((number % i))
{
flag = 1;
}
else
{
flag = 0;
break;
}
}


This is the first for loop which checks if the user entered number is prime. If that is the case we set flag as 1, else as soon as the number is found to be divisible by any number between 1 and the number itself (both exclusive) we set the flag as 0 and break out of the loop.

if (flag == 1)
printf("1 X %d", number);


Once we are out of the first for loop we check the flag. If it is found to be 1, that means the number was prime, and thus we print 1 X number as the output and return.

But if the number is not a prime? Then we use the else case. For simplicity, I will break the else case now. All the statements inside the else block have been enveloped in a for loop:
for ( i = 2; i <= primeCheck; i++ )
In this for loop, we again use the variable 'primeCheck' as the upper limit. Why did I do that? Again the reason being the fact that we need to check only the numbers upto 'primCheck'! We don't have to check the numbers beyond that because the factors need to be whole number. The first thing inside this for loop that we do is to set the flag again to 1. flag = 1; Inside the else block, the flag variable is used as the flag to break off the loop which returns the next prime number. That is why we started the for loop from 2.

for ( j = 2; j < i; j++ )
{
if ( (i % j) == 0 )
{
flag = 0;
break;
}
}


This is the for loop nested inside the for loop which is the part of the else block. This for loop returns the next prime number. What are we doing here is that, the outer for loop sets 'i' as the next integer on the number line. This for loop will check if that number is prime. If that is not the case, the flag variable is set to 0, the control breaks off from this loop, and the control reaches to the outer for loop since the next statement after this inner for loop will check the value of the variable flag. This for loop is a reason why I set the flag variable as 1 at the start of the outer for loop. This is necessary since we want to execute the set of statements that follow this for loop even if the last number was not a prime and this number is.

if ( flag )
{
while ( !(number % i) || (number == i) )
{
printf("%d ", i);
number /= i;
if ( number > 1 )
printf("X ");
}
}


Now consider that the for loop that was checking whether i is prime or not, exited normally, that mean i is a prime number. Thus the value of flag is not changed, and hence is 1 only. Now let's come to the while loop condition. (number % i) returns true if the number is not divisible by i. I have used !(number % i), i.e., the NOT of the condition, which would return true if the number is divisible by i. (number == i) returns true if the number and i are equal. If any of the two conditions is true, we execute the while loop block. Now since, !(number % i) || (number == i) means that the number is divisible by i (the first condition is explained earlier, and the second one is of course true! the number is always divisible by itself!!), thus the statement printf("%d ", i); prints i since the program flow proves 2 things, i is a prime number and a factor of 'number', thus the prime factor of 'number'.

The next statement, number /= i; divides the number by 'i' so that we are left with the rest of the number and we are not stuck in an infinite loop of printing the same prime factor again and again.

The next statement,
if ( number > 1 )
printf("X ");

prints an X followed by a space. This improves readability of the output, separating each prime factor by an X. We print this only if the number is greater than 1. If the last division of dividing the number by i resulted in 1, we don't wish to print an extra X or space between the last factor found and nothing. Thus this statement is just meant for improved readability of the program output.

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

Power Function (X^Y - X Raised to power Y) - C Program

Problem Question


Write a function power ( a, b ), to calculate the value of a raised to b.

Explanation of Problem


It is a simple program wherein the main function shall accept 2 inputs from user, X & Y (for X^Y). The power function should return an int which should be the result of X^Y. Our program should print this result.

Code


#include <stdio.h>

/**@Title: Power Function.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 04-05-2014*
*/

int power(int a, int b)
{
 int i, pro = 1;
 for ( i = 0; i < b; i++ )
 {
  pro *= a;
 }
 return pro;
}

int main()
{
 int a, b, ex;
 printf("\n\nEnter 2 numbers: ");
 scanf("%d%d", &a, &b);
 ex = power(a, b);
 printf("\n%d raise to power %d is: %d\n\n", a, b, ex);
 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 power(int a, int b)
{
 int i, pro = 1;
 for ( i = 0; i < b; i++ )
 {
  pro *= a;
 }
 return pro;
}

This is the power function that the problem statement asks us to code. The return type is int since I am returning an integer value, which is the result of the operation a^b where a & b are the arguments to the function 'power'. The for loop calculates the value of a^b. The for loop counter starts from 0 to the value of exponent 'b'. We keep multiplying the number to itself (or the running product) until the counter reaches the value 1 less than b (since we are starting from 0). Now we have our result ready. So we return it to the calling function.

ex = power(a, b); -> Here we have an integer variable 'ex' in which we store the result. I have called the function power with the user input values of a and b and assigned the returned value to variable 'ex'.

We can replace the variable 'ex' in our program. We need 'ex' for storing the result so that we can print it. But we can replace this use by calling the power() function directly in the printf() function, like:
printf("\n%d raise to power %d is: %d\n\n", a, b, power(a, b));

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, 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)