Tips

You specify

Allow user to specify the number of decimal digits needed:                         

                   What shall we do when we want to display the “number of digits after decimal point” specified by the user? We can get the number from the user, put it in switch() and give for each individual number.


int num ;
float pi = 3.14 ;
printf ( “\nEnter the number of decimal digits to be shown: “ ) ;
scanf ( “%d”, &num ) ;
switch ( num )
{
case 1: printf ( “%0.1f”, pi ) ; break ;
case 2 : printf ( “%0.2f”, pi ) ; break ;
...................
}

                    But, is it possible to give for each and every number? Moreover, this is not the correct way of programming. Use it in a single statement, instead of switch.


int num ;
float pi = 3.14 ;
printf ( “\nEnter the number of decimal digits to be shown: “ ) ;
scanf ( “%d”, & num ) ;
printf ( “%*.*f”, 0, num, val ) ;
 
This is equivalent to “%0.<num>f”, val.



A C program without semicolon

C program to display “India” without using ';' in the whole program:

                           For writing this program, we should first understand what printf returns and its prototype. The function declaration of printf is
int printf ( const char *, ... ) ;
                          It takes variable number of arguments, displays the string till a NULL character is found and returns the number of characters
printed.

Now, the program:
#include<stdio.h>
void main()
{
    if ( printf ( “India” ) )
    {
    }
}

The printf () returns 5 in this case. Hence, the 'if' condition is true, but, we are not doing anything even if the condition is true.


What's wrong

Why only one input?
                                  Usually in C programming, whatever we type first gets stored in the keyboard buffer (temporary storage) and then the CPU takes input from the buffer. Whenever we input a number (int, float or double), we give the number and press enter to specify that our input is ready to be taken. Both (number and enter) are stored in the buffer. 
                                       After enter is pressed, the number gets stored in the (int, float or double) variable. But, where does the enter go? Yes, it remains in the buffer. Next time when a character or string is to be given as input, this enter will be taken directly from the keyboard buffer and we will not be prompted to input the character or string.

Example:
1.#include<stdio.h>
2.
3.int main()
4.{
5.          int num ;
6.          char ch ;
7.          printf ( "Number: " ) ;
8.          scanf ( "%d", &num ) ;
9.          printf ( "\nCharacter: " ) ;
10.        scanf ( "%c", &ch ) ;
11.        printf ( "%cBye", ch ) ;
12.        return 0 ;
13. }

Output:
Number: 2
Character:
Bye

Explanation:
2 is stored in num and '\n' ( enter ) is stored in ch.

Solution 1:
To get rid of this let us use getchar() before the second scanf(), that is at line number 10. getchar() takes the enter from the buffer. But, since we didn't assign it to any variable, it gets wasted (removed from the buffer).

Solution 2:
Instead of using getchar(), we may get the character twice, that is use scanf ( "%c %c", &ch, &ch ) ; instead of scanf ( "%c", &ch ) ; In this case, first enter is stored in ch and later, the input we give replaces it.


Significant Digits

The '%g' format specifier:
 
             In C++ programming, if we give the statements,

float pi = 3.140f ;
cout<<pi ;

only 3.14 ( significant digits ) will be shown. 
          
             But, in C program , if we give
float pi = 3.140f ;
printf ( “%f”, pi ) ;

3.140000 will be displayed. 
                   
       Of course we can use %0.2f. But, how do we know that how many significant ( valid ) decimal digits are there ? In such situations we can make use of %g,


float pi = 3.140f ;
printf ( “%g”, pi ) ;

will print 3.14.

The main advantage is that if
float val = 3.0 ;
printf ( “%1.0f”, val ) ;   shows 3.
printf ( “%g”, val ) ;        shows 3 ( without decimal point )



 Delimiter problem

Use scanf() as a substitite for gets():

              If gets() is used in C programs, some compilers like “gcc” produce warnings. Though the program runs successfully, sometimes the results are not as expected. Instead of gets(), scanf () can be used effectively with the same functionality. The main difference between gets() and scanf () is that scanf() cannot be used to store a string with a blank space ( if %s is used as the format specifier ).

Eg: If we give scanf ( “%s”, name ) ; and if the input is “Yashavant Kanetkar”, only “Yashavant” is stored in name. ( Note: Here name is a character array )

               The scanf() treats <space> as delimiter ( one which terminates the input ). Instead what if we make scanf() to treat “Enter(\n)” as delimiter ? There is an option for it in C program. 
 
                  Give scanf ( “%[^\n]”, name ) ; - This will treat \n as delimiter
( stores “Yashavant Kanetkar” in name ). Similarly, scanf ( “%[^.]”, name ) ; will treat '.' as delimiter and stores everything typed before '.' in name. In general whatever is given after '^' in the format specifier %[^], will be taken as delimiter.


No main ??!!
  

A C program without main: 

               As soon as you see the title, you might be wondered whether this is possible. But, it's actually possible.  


#include<stdio.h>

#define modify(t, r, a, i, n, s) i ## t ## a ## r
#define change modify(a, n, i, m, a, l)

int change()
{
    printf("C without main!\n");
    return 0;
}


            If you still don't trust this program, compile and execute it. Shocked ? In fact, there is a main in this program, but hidden. This is based on the concept of token pasting. What happens here is, change is initially replaced by modify(a, n, i, m, a, l). The arguments are then replaced as follows
t = a
r = n
a = i
i = m
n = a
s = l

           The statement i ## t ## a ## r gets changed to m ## a ## i ## n, which is then concatenated as main. Eventually, 'change' is changed to 'main'. 


Toggle Case

Simple way to toggle case:
                                  If you want to toggle case (interchange lower case letter to upper case and vice versa), it can of course be done with a comparison with the 'if' statement and adding or subtracting 32 (97 - 65) as follows.


for(int i = 0; i < strlen(str); i++)

{
if(a[i] >= 'a' && a[i] <= 'z')
a[i] -= 32;
else if(a[i] >= 'A' && a[i] <= 'Z')
a[i] += 32;
}


But, if you know the speciality of 32 and bitwise EXOR operator, the code within the loop can be replaced by a single statement as follows.

for(int i = 0; i < strlen(str); i++)
{
a[i] ^= 32;
}


6 comments:

  1. it was a nice thing.i learnt many concepts

    ReplyDelete
  2. Useful tips...
    thank you...

    ReplyDelete
  3. It gives more knowledge.. Thank u so much..

    ReplyDelete
  4. useful tips..thanks

    ReplyDelete
  5. informative concepts,thank you

    ReplyDelete
  6. i need still more concepts about c to develop a new programs easily





    ReplyDelete