C Program to find Binomial Coefficients

C Program to find Binomial Integers without using recursion.

Binomial coefficients are positive integers that are coefficient of any term in the expansion of (x + a) the number of combination’s of a specified size that can be drawn from a given set.

There are many ways to compute the Binomial coefficients. Like,

In this post we will be using a non-recursive, multiplicative formula.

The program is given below:

// C program to find the Binomial coefficient. Downloaded from www.c-program-example.com 
#include<stdio.h> 
void main() {
    int i, j, n, k, min, c[20][20]={0};
    printf("This program is brought to you by www.c-program-example.com\n" );     
    printf("\n Enter the value of n: ");     
    scanf("%d", &n);     
    printf("\n Enter the value of k: ");     
    scanf("%d", &k);
    if(n >= k) {         
        for(i=0; i<=n; i++) {             
            min = i<k? i:k;
            for(j = 0; j <= min; j++) {
                 if(j==0 || j == i) {
                     c[i][j] = 1;
                 } else {
                     c[i][j] = c[i-1][j-1] + c[i-1][j];
                 }
             }
         }
         printf("%d\t",c[n][k]);
         printf("\n");
     } else {
         printf("\n Invalid input \n Enter value n>=k \n");
     }
}

Sample output

Links

Greedy Change Making Program in C

Problem Statement

Write a C program to solve ‘Change Making Problem’. Put simply, a solution to Change-Making problem aims to represent a value in fewest coins under a given coin system. This program was requested by one of readers on our Facebook Page.

Coin changing

Inputs to program

  • Number of different denominations available
  • List of numbers representing all the denominations
  • Amount to represent in the given coin system

Output

The program should output a way to represent the given amount using fewest number of coins. For example. if you have coins of value 1, 2, 5 and 10 and want to represent 26, the program should output the correct solution 10×2 5×1 2×0 1×1

Solution

The greedy approach is easy to understand and implement as well. We start with using the largest denomination coin/currency possible. Once the owed amount is less than the largest, we move to next largest coin, so on and so forth.

Assumptions

  • Denominations are entered in descending order. That is largest one first. Example: 100, 50, 20, 5, 1. We can add a sort method if it’s not, a minor change.
  • We always have denomination of 1(Just to make sure we have a solution for all the numbers).

Limitation

Greedy approach works best with Canonical Coin systems and may not produce optimal results in arbitrary coin systems. For example, if denominations are {4, 3, 1}, number 6 is represented as 4×1 3×0 1×2 by this program; taking 3 coins. The correct answer in this case is 4×0 3×2 1×0 with just 2 coins.

The Program

#include <stdio.h>
int main () {
int num_denominations, coin_list[100], use_these[100], i, owed;
printf("Enter number of denominations : ");
scanf("%d", &num_denominations);
printf("\nEnter the denominations in descending order: ");
for(i=0; i< num_denominations; i++) {
scanf("%d", &coin_list[i]);
// use_these[i] = 0;
}
printf("\nEnter the amount owed : ");
scanf("%d", &owed);
for(i=0; i < num_denominations; i++) {
use_these[i] = owed / coin_list[i];
owed %= coin_list[i];
}
printf("\nSolution: \n");
for(i=0; i < num_denominations; i++) {
printf("%dx%d ", coin_list[i], use_these[i]);
}
}

Sample Output

Further reading

C Program For Infix To Postfix Conversion and Evaluation of postfix expression

Infix to postfix conversion and postfix expression evaluation. In this C Program, we take an infix expression as input from the user and convert it in to a postfix expression using a stack. Then we evaluate that postfix expression to obtain the result.

Problem Statement

Write a C Program to convert a given infix expression to postfix and evaluate it. Infix expression is the most commonly used expression and we are all familiar with this. In Infix expression, the operator is between two operands, as in 1 + 2, or “5 + ((2 + 6) × 9) − 8”. In Postfix expression, also called as Reverse Polish Notation or postorder expression, operators are written after their operands. For example the above expressions become 12+ and  526+9*+8- respectively when written in postfix notation.

Read more about Infix, Postfix and Prefix

The Solution

The problem is divided into two tasks. First, the given infix expression is converted to a postfix expression. Then we take that postfix expression and evaluate it.  In C Program Examples website, we have already given programs to do these things separately. You can see them here and here.

Here we are doing it in a single program. This is in response to a request from one of our readers in a recent comment.

The Program

/*
* C Program to convert a given infix expression to postfix expression and evaluate it.
* (c) www.c-program-example.com
*/
#define SIZE 50 /* Size of Stack */
#include <ctype.h>
#include <stdio.h>
char s[SIZE];
int top = -1; /* Global declarations */
/* Function to remove spaces from given string */
void RemoveSpaces(char* source) {
char* i = source;
char* j = source;
while(*j != 0) {
*i = *j++;
if(*i != ' ')
i++;
}
*i = 0;
}
/* Function for PUSH operation */
void push(char elem) {
s[++top] = elem;
}
/* Function for POP operation */
char pop() {
return (s[top--]);
}
/* Function for precedence */
int pr(char elem) {
switch (elem) {
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
}
/*
* Function to convert from infix to postfix expression
*/
void infix_to_postfix(char *infix, char *postfix) {
char ch, elem;
int i = 0, k = 0;
RemoveSpaces(infix);
push('#');
while ((ch = infix[i++]) != '\n') {
if (ch == '(')
push(ch);
else if (isalnum(ch))
postfix[k++] = ch;
else if (ch == ')') {
while (s[top] != '(')
postfix[k++] = pop();
elem = pop(); /* Remove ( */
} else { /* Operator */
while (pr(s[top]) >= pr(ch))
postfix[k++] = pop();
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
postfix[k++] = pop();
postfix[k] = 0; /* Make postfix as valid string */
}
/*
* Function to evaluate a postfix expression
*/
int eval_postfix(char *postfix) {
char ch;
int i = 0, op1, op2;
while((ch = postfix[i++]) != 0) {
if(isdigit(ch))
push(ch-'0'); /* Push the operand */
else { /* Operator,pop two operands */
op2 = pop();
op1 = pop();
switch(ch) {
case '+' : push(op1+op2);
break;
case '-' : push(op1-op2);
break;
case '*' : push(op1*op2);
break;
case '/' : push(op1/op2);
break;
}
}
}
return s[top];
}
void main() { /* Main Program */
char infx[50], pofx[50];
printf("\nInput the infix expression: ");
fgets(infx, 50, stdin);
infix_to_postfix(infx, pofx);
printf("\nGiven Infix Expression: %sPostfix Expression: %s", infx, pofx);
top = -1;
printf("\nResult of evaluation of postfix expression : %d", eval_postfix(pofx));
}

Sample Output

Related Programs

Site Maintenance Updates

Dear fellow programmers, I have some ‘site maintenance updates’. Before I start on the updates, I would first like to thank you all for your wonderful support over the years. I really appreciate that. As most of you are aware, I have been writing C programs on this website from 2011.

Some of you here have sent emails to thank me for the programs, to ask a doubt or even to report an error you discovered. I’m sorry if I have not replied to your email in time. Our Facebook Page has also seen great response. I regret not being more active there. However, that’s going to change now.

This website started as a small blog on Blogger’s sub-domain in 2011. I started writing simple C programs with some help from my friend Chinmaya. Later, as the readership increased, I moved it to it’s own domain www.c-program-example.com. As you can see, it’s still running on the same domain. While Blogger is a great platform to start with, it lacks the flexibility of a full fledged Content Management System. Now that the website gets around 100000 page views every month, I decide to move it to WordPress.

I seem to have successfully imported all the blog posts. However, the move has not been as smooth as I wanted. Old posts had lot of embedded html and JavaScript. WordPress doesn’t play so well with it. As a result, you may see several broken links or nonfunctional buttons/features. I will be working to fix them all over next week or so. Please let me know if you find anything broken.

Let’s get to the details now.

What has changed

  • The website is now hosted on WordPress. This should not affect your website experience directly. You may notice frequent change in color/theme as I experiment with it.
  • Better layout and font options. You will notice them soon.
  • Website loads much faster, thanks to various plug-ins I’m using to optimize the website for speed and performance.
  • The code highlighting has gone! I will find a plug-in for better embedding of source code within post.

What has NOT changed

  • URLs: If I have done the migration and redirection properly, all the posts should be available at their old urls. That means, any posts you have bookmarked in your browser, or shared with someone else should all work as before.
  • Search feature: ‘Search’ continues to be one of the most used feature on our website. I have included it in this website. You can find it in the right side bar. Only difference is that the search box is much smaller 🙂
  • Facebook Page: C Program Example’s official Facebook Page remains unchanged. You can follow that page by clicking on the link in previous sentence. I will be adding a widget in sidebar soon to make it easy to ‘Like’.
  • Contact information. You can still email me on info@c-program-example.com. Oh! And I promise to reply sooner now 😉

What is Missing

  • Pages: Yes. The old site had a few static pages. One that listed all the solutions to exercise problems from K&R C. Another listed useful programs along with links. Those pages are not in the new site. I will add them with some improvements over next week or two.
  • Google+ comments: Blogger allowed visitors to comment on posts using their Google login. With new WordPress sites, you will need to have WordPress login or give your name and email.
  • Embedded Buttons in post: Posts on old site allowed readers to Like our Facebook Page or Follow us on Twitter by intuitive embedded buttons. That’s all gone now. I will clean up every post and add these buttons only in side bar. I hope this makes posts more readable.

Unknowns!

  • Feeds: I haven’t had a chance to test the feeds(RSS/atom). If you are reading this post via rss reader, then it’s most likely working. I’m adding it to my todo list.
  • Posts in Email: One of the last changes I did in old site was to add support for subscribing to posts via email. I don’t even remember which service was used for that. I have got many subscribers through that. That will be added soon.
  • Link to Pages: If posts had links to Pages, it’d all be broken.
  • Links to Search Results: Some posts have links to search results which may be invalid now.

What to expect in future

As I promised earlier, things are going to be much better over here! These are some things you can expect in near future

  • Complete website features with all relevant plugins and widgets
  • All broken links fixed or removed where irrelevant
  • Plug-ins for close integration with Facebook Page and Twitter.
  • Quicker response to comments and better comment moderation.
  • Better code display inside post by using Gists.

and in not-so-near future

  • Sample input and out put for each program
  • Screen-shots of terminal/output where needed
  • Tutorial/guide posts for beginners to learn how to compile and run C programs in various platforms.
  • A static page for listing these tutorial with support for selecting a tutorial based on OS and other options.
  • Screen record or video with audio explaining programs.
  • Weekly open hangout for discussions and/or questions. Keep watching this space (and Facebook Page) for event announcements.

That’s all for now! Thanks for reading through site maintenance updates. Happy coding.

-SN

Subscribe to C Programs updates via Email

Good news programmers! Now you can get C programs in your inbox!

Yes, now you can subscribe to our updates via Email. It’s very simple. Enter your email-id in the box below and click on “Subscribe” button.
Enter your email address:

Delivered by FeedBurner
This form is also available on the right side bar of the site. To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link
Or if you can’t find the program you are looking for, you can contact info@c-program-example.com. Thank you for visiting.

(c) www.c-program-example.com

C Aptitude: Endianness, Pointer Arithmetic

C Aptitude 31
In this episode we’ll learn learn more about Endianness, Pointer Arithmetic.

C program is one of most popular programming language which is used for core level of coding across the board. C program is used for operating systems, embedded systems, system engineering, word processors,hard ware drivers, etc.

In this site, we have discussed various type of C programs till date and from now on, we will move further by looking at the C aptitude questions.

In the coming days, we will post C aptitude questions, answers and explanation for interview preparations.

The C aptitude questions and answers for those questions along with explanation for the interview related queries.

We hope that this questions and answers series on C program will help students and freshers who are looking for a job, and also programmers who are looking to update their aptitude on C program.
Some of the illustrated examples will be from the various companies, and IT industry experts.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.


Predict the output or error(s) for the following:

C aptitude 31.1

  
main() {
int i = 258;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}

Answer: 2 1

Explanation: The integer value 257 can be represented in binary as, 00000001 00000001. Remember that the INTEL machines are ‘small-endian’ machines. Small-endian means that the lower order bytes are stored in the higher memory addresses and the higher order bytes are stored in lower addresses. The integer value 258 is stored in memory as: 00000001 00000010.

C aptitude 31.2

main() {
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}

Answer:556

Explanation:The integer value 300  in binary notation is: 00000001 00101100. It is  stored in memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory representation as: 00101100 00000010. So the integer corresponding to it  is  00000010 00101100 => 556.

C aptitude 31.3

main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
least = ((*ptr)<(least))?(*ptr):(least);
printf("%d", least);
}

Answer: 0
Explanation: After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘