Basic programs of C language | Data input with scanf() function | Data output with printf() function

Contents in this blog:-

1. Data output with printf() function

  • Sample C program

2. Backslash Character

  • Modified Sample Program
  • Simplr Interest Program

3. Data Input with scanf() Function

  • Simple Interest Calculation
  • Compound Interest Calculation
  • Program for salary Calculation
  • Real Roots of Quadratic Equation
  • clrscr() Function
  • getchch() Function  


Data Output With printf() Function 





printf() is an output function present in the standard library header file "stdio.h". This function is used to print the output result on the output screen (computer screen). 

The output result may involve the variables, constants as required by the user. The printf() function can be used in several formats in a C-program to produce different outputs on the screen. 

The different formats of printf() function are as follows - 

 

printf("Output Message"); 

printf("<Format Specifiers>",  <list of variables>);

printf("Output Message  <Format Specifiers>",  <list of variables>);


The format specifiers are the code-representation of the data types for variables. The formal specifiers of different data types are as follows - 

Data Type              Format Specifier
signed char, unsigned char        %c
short signed int          %d
short unsigned int        %u
long signed int        %ld
long unsigned int        %lu
float        %f
double        %lf
long double        %Lf


Besides these basic format specifiers for basic datatypes, some other format specifiers are used for other types of data as follows -

Data Type             Format Specifier
String         %s
Floating point number         %e, %g, %E
Short integer         %h
Octal integer         %o
Hexadecimal integer         %x or %X
Decimal, Octal or Hexadecimal integer         %i


Example : 

A sample C-Program showing use of printf(). 

/* Sample C-Program */ 

#include<stdio.h> 

main() 

{

int x, y; 

x = 10; 

y = 20; 

printf("This is my First C Program"); 

printf("The value of x = % d", x); 

printf("y = %d", y): 

printf("End of Program !");

}


Output : 

This is my First C Program 

The value of    x = 10 

                        y = 20. 

End of Program ! 


In this program, we have used all the different formats of printf) function. There are four output instructions written with printf() to print those four outputs on the computer screen. But, the output of the program shows all the output statements in a single line. 

This is not the appropriate output of the program, because the output is not shown in separate lines. The output to next line is enforced by the new line character ("In'), Which is lying under the special category of characters constants as "Backslash characters".


Backslash Characters 

C-language provides some special backlash character constants. These character constants are used to make the output more better. So these are always to be used with output functions. 

Each backslash character constant consists of one backslash and one character enclosed in single quotes. But each one represents only one character because the presence of backslash is escaped. So these characters are also known as Escape Sequences. The list of backslash character constants is as follows -

Backslash Character Constant     Work for
'\a'             Beep sound (audible bell)
'\b'         Back space
'\f'         Form feed
'\n'         New line
'\r'         Carriage return
'\t'         Horizontal tab
'\v'         Vertical tab
'\"         Single quote
'\" '         Double quotes
'\?'         Question Mark
'\\'         Back slash character
'\0'         Null character


Example : 

We can modify the output of the program by using the backslash characters such as with the program of example as follows: 


    

/*Modified Sample  Program * /

     #include<stdio.h> 

    main()

    {

    int x, y: 

    x = 10;

    y = 20; 

    printf("\n This is my First C Program"); 

    printf("\n The value of  x = t%d",  x): 

    printf("\n\ty  =  \t%d",  y); 

    printf("\n End of Program !"); 

    }


Output : 

This is my First C Program 

The Value of  x = 10

                       y = 20 

End of Program ! 


Example :

Calculation of simple interest for the given amount Rs. 4500, rate of interest 4.5% and duration 5 years. 

    /* Program for Simple Interest calculation */ 

    #include<stdio.h> 

    main() 

    {

    int amount  =  4500,  year = 5; 

    float int_rate  =  4.5, simple_int; 

    simple_int  =  (amount"year'int_rate)/100;

    printf("\n Amount = %d  Rs.", amount); 

    printf("\n Rate of Interest = %f", int_rate); 

    printf("\n Duration = %d years ", year); 

    print("\n The Simple Interest calculated is = Rs. %f", simple_int);

    }

Output : 

Amount = 4500 Rs. 

Rate of Interest= 4.5 

Duration = 5 years 

The Simple Interest calculated is = Rs. 1012.450000


Data Input with scanf() Function 

In a C-program, the variables require data value for processing. So the value assignment should be done before processing. The value assignment of the variables is done by using assignment operator in the beginning of program or at run time of the program. 

When the program requires some input at run time, the input data is provided from the standard input device (such as key-board) and this data value is sent to the variables by a standard library function of C named scanf() function. The scanf() function can be used to take different types of input like numerical values, single character or string etc. The general format of scanf() function is as follows -

 scanf("<Format specifiers>", <Address of variable, > ); 


Example  : 

Calculate simple interest by input data. 

        /* Simple Interest Calculation */ 

        #include<stdio.h> 

        main()

        {

        int amount, year; 

        float int_rate, simple_int; 

        printf ("\n Enter amount, rate of interest and duration:"); 

        scanf ("%d%f%d", &amount, &int_rate, &year); 

        simple_int = (amount*int_rate"year)/100; 

        printf ("n Simple Interest Calculated = %f", simple_int); 

        


Output : 

Enter amount, rate of interest and duration : 5000 

                         4.5 

                        5

Simple Interest calculated = 1125.000000 


In the above example, we have used a special symbol (&) with the variable name in the input instruction with scanf() function. 

The symbol (&) is known as the Address Operator In C-programming language. This Address operator is used to send the input data value to the specified variables at specific memory locations.


Example 

Calculate compound interest on the given amount for given duration. 

     

     /* Compound Interest Calculation */ 

          #include<stdio.h> 

          #include<math.h> 

          main() 

        {

        float p, r, y. i, a; 

        /* input data */ 

        printf("n Enter the principal amount (p):"); 

        scanf("%f", &p); 

        printf("n Enter Interest Rate (r):"); 

        scanf("%f", &r); 

        printf("n Enter number of years (y):"); 

        scanf("%l", &y): 

        /* Calculate compound interest */

        i = r/100; 

        a = p"pow((1+i),y)' 

        /* writing output */ 

        printf("\n The final amount after interest = f", a); 

        }


Output : 

Enter the principal amount (p) : 1000 

Enter Interest Rate (r) : 10 

Enter number of years (y) : 2 

The final amount after interest = 1210.000000 


In this example , we have used a special function pow( ) and for this, the header file "math.h" is included in the beginning of program. This function is used to calculate the result of raising given power to the given number. 

pow() function: This function is present in the standard library of C-language named "math.h". This function facilitates the calculation of x to the power n without any extra instruction. The syntax used for solution is :

pow(x,n); 

For example :   pow(2,3) evaluates 8. 


Example  : 

Calculate net salary of the employee, whose basic salary is input through keyboard. TA= 15% and DA = 41% of basic salary is to be calculated. 

         /* Program for salary Calculation */ 

#include<stdio.h> 

#include<conio.h> 

main() 

float bs, ta, da, ns; 

clrscr(): 

printf("\n Enter Basic Salary of the Employee (bs):"); 

scanf("%f", &bs): /* Calculations */ 

ta = (bs*15)/100; 

da = (bs*41)/100; 

ns = bs+ta+da; 

printf("\n TA = %f \n D.A. = %f", ta, da); 

printf("\n Net Salary Calculated is = %f", ns); 

printf("\n Press any key to continue..."); 

getch(); 

}


Output : 

Enter Basic Salary of Employee (bs):1000 

TA. = 150.000000 

DA = 410.000000 

Net salary Calculated is = 1560.000000 

Press any key to continue... 


This example has used two new functions - 

clrscr() and getch(). We have not discussed about these functions so far. These functions are used to make the program output better, user friendly and interactive. Both the functions are provided in the standard library header file named "conio.h" (console Input/Output). 

clrscr() function : This function is used to clear the output screen during progrm execution. It activates   the operating system to clear the output screen. This function can be used anywhere in the program as required for the interactive output.
getch() function : This function gets a character from the keyboard and so directs the program to wait for a key press. Its use is to stop the program output on the output screen for a white. The program execution resumes after pressing a key. We can use this function anywhere in the program where wait is required.


It is not necessary to use these two functions in a C-program. But their presence effect the output of program. When we execute a C-program, the control immediately transfers from the output screen to program screen. Then, getch() function is useful for seeing the output properly because execution waits for a key press by keyboard. 


Example : 

Calculate Real Roots of Quadratic Equation 

/* Real Roots of Quadratic Equation */ 

#include<stdio.h> 

#include<conio.h> 

#include<math.h> 

main()

{

float a,b,c,d,x1,x2;

clrscr();


/* data input */ 

printf("\n Enter the values of a,b,c:\n"); 

scanf("%f%f%f", &a, &b, &c); 

/* Calculations */ 

d = sqrt (b*b-4*a*c);

x1 = (-b+d)/(2*a);

x2 = (-b-d)/(2*a);

/* Result Display */ 

printf("\n First Root X1 = %e \n Second Root X2 = %e", x1, x2); 

getch(); 

}

Output : 

Enter the values of a,b,c : 

                3   10   3 

First Root X1       =   -33 

Second Root X2  =   -3 


Input-Output Manipulations 

In a program of C-language, we take the input data from printf() function and send the output to output screen by scanf() function generally. There are different format specifiers used for data input and output. 

The integer number requires the format specifier as "%d". This format is used to input/output a numeric value but the number of digits in the number depends on the range of integer. But we can manipulate the data input or output as follows: 

Integer Format          -     %wd 

Float Format             -     %wf   or   %w.pf 

Character Format     -     %wc

String Format           -     %s   or    %ws


Example  : 

An Example of string manipulations. 

/* Input-Output manipulations */

#include<stdio.h> 

#include<conio.h>

main()

{

int a,b;

float  c, d, char x;

clrscr();

a = 123;

c = 16.4358;

x = 'A';

printf("\ n Enter a number;"); 

scanf("%2d", &b); 

printf("\n Enter a floating point number:"); 

scanf("%f", &d);

printf("\n A  =  %2d  \nB  =  %2s", a,b); 

printf("\n C  =  %f  \n D    = %f", c,d); 

printf("\n C = %2f  \n  D   =  %3f",  c,d); 

printf("\n  %C \n  %3c \ n  %5c", x, x, x); 

printf("\n %3c  \n  %c". x,x); 

getch(); 

}

Output :

Enter a number : 6536 

Enter a floating point number : 63.43 

A = 12 

B = 65 

C = 16.435800 

D= 63.430000 

C = 16.43 

D = 63.43 

                   A

                                A

                                                A

                                A

                     A


Related Posts :-

Post a Comment

Previous Post Next Post