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

[gist id=”ba3675bad57dae3341713c23161ca318″]

Sample Output

Further reading

Infix to Postfix Conversion and Evaluation in C – With Example

Infix notation is the way humans write arithmetic: A + B, 5 * (2 + 3). The operator sits between its operands. Computers, however, evaluate expressions more efficiently in postfix notation (also called Reverse Polish Notation), where the operator comes after its operands: A B +, 5 2 3 + *.

This C program does both jobs in one pass: it converts an infix expression to postfix using a stack, then evaluates the postfix result to give the final answer.

Infix vs Postfix — The Key Difference

Expression Infix Postfix
A plus B A + B A B +
A plus B times C A + B * C A B C * +
Parenthesised (A + B) * C A B + C *
Complex 5 + ((2 + 6) * 9) - 8 5 2 6 + 9 * + 8 -

Why postfix? It eliminates the need for parentheses and operator precedence rules during evaluation. A simple left-to-right scan with a stack is all you need — no lookahead required. This is how compilers and calculators work internally.

Algorithm — Infix to Postfix Conversion

Uses a stack to hold operators temporarily. Operands go straight to output; operators wait on the stack until a lower-precedence operator or end of expression forces them out.

Rules:

  1. Scan left to right.
  2. Operand (letter or digit) → write to output immediately.
  3. ( → push onto stack.
  4. ) → pop and output until ( is found; discard both parentheses.
  5. Operator → pop and output all operators of equal or higher precedence first, then push the current operator.
  6. End of expression → pop and output everything remaining on the stack.

Precedence: * / (level 3) > + - (level 2) > ( (level 1) > # sentinel (level 0)

Walkthrough: Converting A + B * C

Token   Action                Stack       Output
A       operand → output      [#]         A
+       pr(#)=0 < pr(+)=2     [# +]       A
        push +
B       operand → output      [# +]       A B
*       pr(+)=2 < pr(*)=3     [# + *]     A B
        push *
C       operand → output      [# + *]     A B C
end     pop all: * then +     [#]         A B C * +

Result: A B C * +

Algorithm — Postfix Evaluation

  1. Scan left to right.
  2. Operand → push onto stack.
  3. Operator → pop two operands, apply operator, push result.
  4. End of expression → the single value on the stack is the answer.

Walkthrough: Evaluating 5 2 6 + 9 * + 8 -

Token   Stack after
5       [5]
2       [5, 2]
6       [5, 2, 6]
+       pop 6,2 → 2+6=8    [5, 8]
9       [5, 8, 9]
*       pop 9,8 → 8*9=72   [5, 72]
+       pop 72,5 → 5+72=77 [77]
8       [77, 8]
-       pop 8,77 → 77-8=69 [69]

Result: 69

C Program — Infix to Postfix Conversion and Evaluation

#define SIZE 50
#include <ctype.h>
#include <stdio.h>

char s[SIZE];
int top = -1;

void push(char elem) {
    s[++top] = elem;
}

char pop() {
    return s[top--];
}

/* Returns operator precedence */
int pr(char elem) {
    switch (elem) {
        case '#': return 0;
        case '(': return 1;
        case '+':
        case '-': return 2;
        case '*':
        case '/': return 3;
    }
    return -1;
}

/* Removes spaces from a string in-place */
void remove_spaces(char *src) {
    char *i = src, *j = src;
    while (*j != 0) {
        *i = *j++;
        if (*i != ' ')
            i++;
    }
    *i = 0;
}

void infix_to_postfix(char *infix, char *postfix) {
    char ch, elem;
    int i = 0, k = 0;

    remove_spaces(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();   /* discard the '(' */
        } else {            /* operator */
            while (pr(s[top]) >= pr(ch))
                postfix[k++] = pop();
            push(ch);
        }
    }

    while (s[top] != '#')
        postfix[k++] = pop();

    postfix[k] = '\0';
}

int eval_postfix(char *postfix) {
    char ch;
    int i = 0, op1, op2;

    while ((ch = postfix[i++]) != '\0') {
        if (isdigit(ch))
            push(ch - '0');
        else {
            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];
}

int main() {
    char infx[50], pofx[50];

    printf("Enter infix expression: ");
    fgets(infx, 50, stdin);

    infix_to_postfix(infx, pofx);

    printf("Infix    : %s", infx);
    printf("Postfix  : %s\n", pofx);

    top = -1;   /* reset stack for evaluation */
    printf("Result   : %d\n", eval_postfix(pofx));

    return 0;
}

Code Explanation

  • Shared stack s[]: Used for both phases. After conversion, top is reset to -1 so the same array is reused cleanly for evaluation.
  • Sentinel '#': Pushed before scanning begins. Acts as a stack bottom marker with precedence 0, so the loop while (pr(s[top]) >= pr(ch)) always terminates safely without checking for an empty stack.
  • remove_spaces(): Strips spaces in-place so A + B and A+B are treated identically. Modifies the string character by character using two pointers.
  • Operand vs operator: isalnum(ch) covers both letters (variables) and digits. Single-digit numbers only — extend with a numeric stack for multi-digit support.
  • Evaluation — ch - '0': Converts a digit character to its integer value (e.g., '7' - '0' = 7). This works because digit characters are consecutive in ASCII.

Sample Input and Output

Enter infix expression: 5+((2+6)*9)-8

Infix    : 5+((2+6)*9)-8
Postfix  : 526+9*+8-
Result   : 69

Limitations of This Program

  • Single-digit operands only12 + 3 would treat 1, 2, and 3 as separate operands. Extend with an integer stack and string parsing for multi-digit numbers.
  • No error handling — mismatched parentheses or invalid characters cause undefined behavior.
  • Right-associative operators (like ^ for exponentiation) need a small tweak: use > instead of >= in the while loop when the current operator is right-associative.

Related Programs


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.

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.

Announcement

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 [email protected]. 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 [email protected]. 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 ‘’. So the value of ‘str’ is less than that of ‘least’. So the value of ‘least’ finally is 0.

Read more Similar C Programs 
Learn C Programming
C Aptitude
C Interview questions
 

You can easily select the code by double clicking on the code area above. 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 [email protected]. Thank you for visiting.

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

C Program to implement bucket sort

Write C program to implement bucket sort.
The idea of Bucket Sort is to divide the interval [0, 1] into n equal-sized sub intervals, or buckets, and then distribute the n input numbers into the buckets. To produce the output, we simply sort the numbers in each bucket and then go through the buckets in order, listing elements in each.
Bucket sort runs in linear time when the input is drawn from a uniform distribution. Read more about C Programming Language .
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
void Bucket_Sort(int array[], int n)
{   
 int i, j;   
 int count[n];  
 for(i=0; i < n; i++)
 {   
  count[i] = 0;   
 }     
 for(i=0; i < n; i++)
 {    
  (count[array[i]])++; 
 }     
 for(i=0,j=0; i < n; i++)
 {   
  for(; count[i]>0;(count[i])--) 
  {       
   array[j++] = i; 
  }  
 }   
}    
int main() 
{ 
 int array[100];   
 int num;   
 int i;  
 printf("Enter How many Numbers : ");    
 scanf("%d",&num);    
 printf("Enter the %d elements to be sorted:n",num);  
 for(i = 0; i < num; i++ )
 {   
  scanf("%d",&array[i]);  
 }   
 printf("nThe array of elements before sorting : n"); 
 for (i = 0;i < num;i++) 
 {    
  printf("%d ", array[i]);   
 }    
 printf("nThe array of elements after sorting : n");  
 Bucket_Sort(array, num);  
 for (i = 0;i < n;i++) 
 {     
  printf("%d ", array[i]);  
 }   
 printf("n");      
 return 0; 
} 

Read more Similar C Programs

Data Structures


C Sorting

You can easily select the code by double clicking on the code area above.

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 [email protected]. Thank you for visiting.

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

C Aptitude Questions and answers with explanation

C Aptitude 30
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 30.1

  main()
{
int i;
i = abc();
printf("%d",i);
}
abc()
{
_AX = 1000;
}

Answer:1000

Explanation: Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000.

C aptitude 30.2

   main( )
{
void *vp;
char ch = ‘g’, *cp = “goofy”;
int j = 20;
vp = &ch;
printf(“%c”, *(char *)vp);
vp = &j;
printf(“%d”,*(int *)vp);
vp = cp;
printf(“%s”,(char *)vp + 3);
}

Answer: g20fy

Explanation: Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper data type pointer. the output is ‘g’. Similarly the output from second printf is ‘20’. The third printf statement type casts it to print the string from the 4th value hence the output is ‘fy’.

C aptitude 30.3

     # include<stdio.h>
aaa() {
printf("hi");
}
bbb(){
printf("hello");
}
ccc(){
printf("bye");
}
main()
{
int (*ptr[3])();
ptr[0]=aaa;
ptr[1]=bbb;
ptr[2]=ccc;
ptr[2]();
}

Answer: bye

Explanation: ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc.

Read more Similar C Programs 
Learn C Programming
C Aptitude
C Interview questions
 

You can easily select the code by double clicking on the code area above.

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 [email protected]. Thank you for visiting.
(c) www.c-program-example.com

C Aptitude Questions and answers with explanation

C Aptitude 29
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 29.1

  enum colors {BLACK,BLUE,GREEN}
main()
{

printf("%d..%d..%d",BLACK,BLUE,GREEN);

return(1);
}

Answer: 0..1..2

Explanation: enum assigns numbers starting from 0, if not explicitly defined.

C aptitude 29.2

   void main()
{
char far *farther,*farthest;

printf("%d..%d",sizeof(farther),sizeof(farthest));

}


Answer: 4..2

Explanation: The second pointer is of char type and not a far pointer

C aptitude 29.3

     main()
{
int i=400,j=300;
printf("%d..%d");
}

Answer: 400..300

Explanation: printf takes the values of the first two assignments of the program. Any number of printf’s may be given. All of them take only the first two.

Read more Similar C Programs 
Learn C Programming
C Aptitude
C Interview questions
 

You can easily select the code by double clicking on the code area above.

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
(c) www.c-program-example.com

C Aptitude Questions and answers with explanation

C Aptitude 28
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.

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 28.1

 main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='') ++*p++;
printf("%s %s",p,p1);
}

Answer: ibj!gsjfoet

Explanation: ++*p++ will be parse in the given order
 *p that is value at the location currently pointed by p will be taken
  ++*p the retrieved value will be incremented
 when ; is encountered the location will be incremented that is p++ will be executed

Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘’ and p1 points to p thus p1doesnot print anything.

C aptitude 28.2

   #include <stdio.h>
#define a 10
main()
{
#define a 50
printf("%d",a);
}

Answer: 50

Explanation:The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

C aptitude 28.3

     
main()
{
printf("%p",main);
}


Answer:Some address will be printed.
Explanation: Function names are just addresses (just like array names are addresses). main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.

Read more Similar C Programs 
Learn C Programming
C Aptitude
C Interview questions
 

You can easily select the code by double clicking on the code area above. 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
(c) www.c-program-example.com

C Program to Delete a File Using remove() — Safe Code with Error Handling

The remove() function in C deletes a file from the filesystem. Defined in <stdio.h>, it works on both Windows and Linux — making it the standard, portable way to delete files from a C program.

Syntax

int remove(const char *filename);

filename is the path to the file — relative to the working directory (e.g. data.txt) or absolute (e.g. /tmp/data.txt on Linux, C:\temp\data.txt on Windows).

Return value: 0 on success, non-zero on failure. When it fails, the global variable errno is set to indicate the reason.

Example 1 — Delete a File (Hardcoded Path)

#include <stdio.h>

int main(void)
{
    const char *filename = "test.txt";

    if (remove(filename) == 0)
        printf("Deleted: %s\n", filename);
    else
        perror("Error");

    return 0;
}

perror() prints the system error message automatically. Instead of a vague “Error deleting file”, you get the actual reason — for example: Error: No such file or directory.

Example 2 — Delete a File Entered by the User

#include <stdio.h>
#include <string.h>

int main(void)
{
    char filename[256];

    printf("Enter file path to delete: ");
    if (fgets(filename, sizeof(filename), stdin) == NULL) {
        fprintf(stderr, "Input error\n");
        return 1;
    }

    /* Strip the trailing newline that fgets leaves in */
    filename[strcspn(filename, "\n")] = '\0';

    if (remove(filename) == 0)
        printf("Deleted: %s\n", filename);
    else
        perror(filename);

    return 0;
}

Why fgets() and Not gets()?

gets() was removed from the C standard in C11 because it has no bounds checking — a long filename silently overflows the buffer and corrupts memory. fgets(filename, sizeof(filename), stdin) reads at most sizeof(filename) - 1 characters, so the buffer is always safe regardless of input length.

Sample Output

Success

Enter file path to delete: /tmp/test.txt
Deleted: /tmp/test.txt

File does not exist

Enter file path to delete: /tmp/missing.txt
/tmp/missing.txt: No such file or directory

Permission denied

Enter file path to delete: /etc/hosts
/etc/hosts: Permission denied

Common errno Values When remove() Fails

errno value Meaning Common cause
ENOENT No such file or directory Wrong path or file never existed
EACCES Permission denied File is read-only or owned by another user
EISDIR Is a directory Path points to a directory — use rmdir() instead
EBUSY Device or resource busy File open by another process (Windows)

Bonus: rename() — Move or Rename a File

rename() is declared in the same <stdio.h> header. It moves or renames a file atomically (on the same filesystem):

#include <stdio.h>

int main(void)
{
    if (rename("old_name.txt", "new_name.txt") == 0)
        printf("File renamed successfully\n");
    else
        perror("rename");

    return 0;
}

Like remove(), it returns 0 on success and sets errno on failure. The atomic rename is useful for safe file replacement — write to a temp file, then rename over the target, so readers always see either the old file or the new one, never a partial write.

Key Points

  • Both remove() and rename() are in <stdio.h> — no extra headers needed
  • Always check the return value and call perror() when it fails
  • Use fgets() to read filenames from the user — gets() is unsafe and removed in C11
  • remove() only deletes files, not directories — use rmdir() for empty directories
  • Relative paths are resolved from the process’s current working directory, not the source file’s location

Related File Programs in C


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.