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 30, 2014

System() calls in C++ and their roles in programming

Hey!

You must have often heard that using system("PAUSE") is bad practice and to use std::cin.get() instead. Is it true? We will discuss that today. We will also try to find out answers to questions, like, When is it appropriate to use system() calls? How should they be applied? When should they NOT be applied?

system("PAUSE") is certainly less than ideal. using a call to system creates a subprocess, which on windows is fairly expensive and in any case not terribly cheap on any operating system. On embedded systems the memory overhead is significant.

If there is any way to do it without much pain natively then do it. In the case of waiting for the user to press a single button, cin.get() will be very hard to beat. In this case, your applications process will just block on stdin, setting only a few flags visible to the kernel, and most importantly, allocates no new memory and creates no new scheduling entities, not even an interrupt handler.

Additionally, it will work the same on all operating systems with all c++ compilers, since it uses only a very basic feature of a very standard part of the language, rather than depend on anything the OS provides.

Predicting the concern that it doesn't matter if it's expensive because the whole idea is to pause. Well, first off, if its expensive, then it's going to hurt performance for anything else that might be going on. Ever noticed (on windows) when one application is launching, other, already open apps become less responsive too? Additionally, your user might not be a live human, but rather another program working on behalf of a human user (Say, a shell script). The script already knows what to do next and can pre-fill stdin with a character to skip over the wait. If you have used a subprocess here, the script will experience a (noticeable to a human) delay. If the script is doing this hundreds (or hundreds of millions!) of times, a script that could take seconds to run now takes days or years.

When to use system(): when you need to do something that another process does, that you can't do easily. system() isn't always the best candidate because it does two things that are somewhat limiting. First, the only way to communicate with the subprocess is, command line arguments as input and return value as output. The second is that the parent process blocks until the child process has completed. These two factors limit the cases in which system is usable.

On UNIX systems, most sub-processes happen with fork because it allows the same program to continue in the same place as two separate processes, one as a child of the other (which is hardly noticeable unless you ask for it from the OS). On Linux, this is especially well optimized, and about as cheap as creating a pthread. Even on systems where this is not as fast, it is still very useful (as demonstrated by the apache process-pool methodology) (unavailable on windows/link to unix docs)

Other cases (on windows too!) are often handled by popen or exec family of functions. popen creates a subprocess and a brand new pipe connecting to the subprocesses' stdin or stdout. Both parent and child processes can then run concurrently and communicate quite easily. (link to windows docs/link to unix docs)

exec* family of functions (there are several, execl, execv and so on) on the other hand causes the current program to be replaced by the new program. The original program exits invisibly and the new process takes over. When then new process returns, it will return to whatever called the original process, as if that process had returned at that point instead of vanishing. The advantage of this over exit(system("command")) is that no new process is created, saving time and memory (though not always terribly much) (link to windows docs /link to unix docs)

system could plausibly be used by some scripted tool to invoke several steps in some recipe action. For example, at a certain point, a program could use system to invoke a text editor to edit some configuration file. It need not concern itself too much with what happens, but it should certainly wait until the user has saved and closed the editor before continuing. It can then use the return value to find out if the editing session was successful, in the sense that the editor actually opened the requested file (and that the editor itself existed at all!), but will read the actual results of the session from the edited file directly, rather than communicating with the subprocess. (link to windows docs/link to unix docs)

Source: http://stackoverflow.com/questions/900666/system-calls-in-c-and-their-roles-in-programming

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)