Part 2: C programming Build-in Function Constants and Literals

C Programming

Build-in Function Constants and Literals

C  programming  Build-in Function will focus here with printf and scanf, Such as:

C printf and scanf functions: printf() and scanf() functions are inbuilt library functions in C programming language which are available in C library by default. These functions are declared and related macros are defined in “stdio.h” which is a header file in C language.

We have to include “stdio.h” file as shown in below C program to make use of these printf() and scanf() library functions in C language.

1. PRINTF() FUNCTION IN C LANGUAGE:

In C programming language, printf() function is used to print the (“character, string, float, integer, octal and hexadecimal values”) onto the output screen. We use printf() function with %d format specifier to display the value of an integer variable. Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal variable.

To generate a newline,we use “\n” in C printf() statement.

EXAMPLE PROGRAM FOR C PRINTF() FUNCTION:

#include <stdio.h>
#include <math.h>
int main()
{
char ch = 'A';
char str[20] = "draftsbook.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}

OUTPUT

Character is A 
String is draftsbook.com 
Float value is 10.234000 
Integer value is 150
Double value is 20.123456 
Octal value is 226 
Hexadecimal value is 96

2. SCANF FUNCTION IN C LANGUAGE:

In C programming language, scanf() function is used to read character, string, numeric data from keyboard
Consider below example program where user enters a character. This value is assigned to the variable “ch” and then displayed. Then, user enters a string and this value is assigned to the variable “str” and then displayed.

EXAMPLE PROGRAM FOR C PRINTF AND SCANF FUNCTIONS IN C :

#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}

OUTPUT :
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

The format specifier %d is used in scanf() statement. So that, the value entered is received as an integer and %s for string.

Function #include What It Does
sqrt() math.h Calculates the square root of a floating-point value
pow() math.h Returns the result of a floating-point value raised to a
certain power
abs() stdlib.h Returns the absolute value (positive value) of an integer
floor() math.h Rounds up a floating-point value to the next whole number
(nonfractional) value
ceil() math.h Rounds down a floating-point value to the next whole
number

EXAMPLE: Program for Math function  in C

#include <stdio.h>
#include <math.h>
int main()
{
float result,value;
printf("Input a float value: ");
scanf("%f",&value);
result = sqrt(value);
printf("The square root of %.2f is %.2f\n",
value,result);
result = pow(value,3);
printf("%.2f to the 3rd power is %.2f\n",
value,result);
result = floor(value);
printf("The floor of %.2f is %.2f\n",
value,result);
result = ceil(value);
printf("And the ceiling of %.2f is %.2f\n",
value,result);
return(0);
}

OUTPUT:

Input a float value: 4
The square root of 4.00 is 2.00
4.00 to the 3rd power is 64.00
The floor of 4.00 is 4.00
And the ceiling of 4.00 is 4.00

Write a C program to find distance travel by an object. ( s=ut+1/2at^2 )

#include <stdio.h>
#include <math.h>

void main()
{

        float s;
        int u, t, a;
        printf("Please enter the initial velocity = ");
        scanf("%d",&u);
         printf("Please enter the time = ");
        scanf("%d",&t);
         printf("Please enter acceleration = ");
        scanf("%d",&a);
        s=(u*t)+(0.5*a*t*t);
        printf("Total distance is %f",s);
        
}

OUTPUT

Please enter the initial velocity = 10
Please enter the time = 3
Please enter acceleration = 2
Total distance is 39.000000

Write a C program to find distance travel by an object where initial velocity is zero. ( s=vt)

#include <stdio.h>

int main()
{  
  float s;
  int v, t; 
  printf("Please enter the initial velocity = ");
  scanf("%d",&v); 
  printf("Please enter the time = "); 
  scanf("%d",&t);
  s=(v*t); 
  printf("Total distance is %f",s);     
  return 0;  
    
}

OUTPUT:

Please enter the initial velocity = 10
Please enter the time = 5
Total distance is 50.000000

Constants and Literals

Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.

Integer Literals

An integer literal can be a decimal, octal, or hexadecimal constant. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.

Here are some examples of integer literals −

212         /* Legal */
215u        /* Legal */
0xFeeL      /* Legal */
078         /* Illegal: 8 is not an octal digit */
032UU       /* Illegal: cannot repeat a suffix */

Following are other examples of various types of integer literals −

75         /* decimal */
0223       /* octal */
0x2b       /* hexadecimal */
40         /* int */
40u        /* unsigned int */
40l        /* long */
40ul       /* unsigned long */

Floating-point Literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. The signed exponent is introduced by e or E.

Here are some examples of floating-point literals −

3.14159       /* Legal */
314159E-5L    /* Legal */
510E          /* Illegal: incomplete exponent */
210f          /* Illegal: no decimal or exponent */
.e55          /* Illegal: missing integer or fraction */

Character Constants

  • Character literals are enclosed in single quotes, e.g., ‘x’ can be stored in a simple variable of char type.
  • A character literal can be a plain character (e.g., ‘x’), an escape sequence (e.g., ‘\t’), or a universal character (e.g., ‘\u02C0’).
  • There are certain characters in C that represent special meaning when preceded by a backslash for example, newline (\n) or tab (\t).
#include <stdio.h> 
int main() 
{
 printf("Hello\tWorld\n\n"); 
return 0; 
}

 

When the above code is compiled and executed, it produces the following result −

Hello World

String Literals

String literals or constants are enclosed in double quotes “”. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using white spaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

Defining Constants

There are two simple ways in C to define constants −

  • Using #define preprocessor.
  • Using const keyword.

The #define Preprocessor

Given below is the form to use #define preprocessor to define a constant −

#define identifier value

The following example explains it in detail:

#include <stdio.h> 
#define LENGTH 10 
#define WIDTH 5 
#define NEWLINE '\n' 
int main() { 
int area; 
area = LENGTH * WIDTH; 
printf("value of area : %d", area);
 printf("%c", NEWLINE); return 0;
 }

When the above code is compiled and executed, it produces the following result :

value of area : 50

The const Keyword

You can use const prefix to declare constants with a specific type as follows −

const type variable = value;

The following example explains it in detail :

#include <stdio.h> 
int main() {
 const int LENGTH = 10;
 const int WIDTH = 5; 
const char NEWLINE = '\n';
 int area;
 area = LENGTH * WIDTH; 
printf("value of area : %d", area);
 printf("%c", NEWLINE); return 0; 
}

When the above code is compiled and executed, it produces the following result:

value of area : 50

Note that it is a good programming practice to define constants in CAPITALS.

 

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program −

  • auto
  • register
  • static
  • extern

The auto Storage Class

The auto storage class is the default storage class for all local variables.

{
   int mount;
   auto int month;
}

The example above defines two variables with in the same storage class. ‘auto’ can only be used within functions, i.e., local variables.

The register Storage Class

The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can’t have the unary ‘&’ operator applied to it (as it does not have a memory location).

{
   register int  miles;
}

The register should only be used for variables that require quick access such as counters. Variable MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. In C programming, when static is used on a global variable, it causes only one copy of that member to be shared by all the objects of its class.

#include <stdio.h> 
/* function declaration */ 
void func(void); static int count = 5; 
/* global variable */ 
main() {
 while(count--) {
 func(); 
} 
return 0; 
}
 /* function definition */ 
void func( void ) {
 static int i = 5;
 /* local static variable */
 i++; 
printf("i is %d and count is %d\n", i, count); 
}

When the above code is compiled and executed, it produces the following result −

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class

When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.

The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.

First File: main.c

#include <stdio.h> 
int count ; 
extern void write_extern();
 main() {
 count = 5; 
write_extern(); 
}

Second File: support.c

#include <stdio.h> 
extern int count; 
void write_extern(void) { 
printf("count is %d\n", count);
 }

Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows −

$gcc main.c support.c

It will produce the executable program a.out. When this program is executed, it produces the following result −

count is 5

0 Comments

You may find interest following article