Comparing Floating Point Variable With a Value In C Programming

In this video tutorial lets see how we can compare a floating point variable with a constant value, and lets see the result.

Related Read:
Sizeof Operator in C Programming Language
C Program To Convert Decimal Number To Binary Number, using While Loop

The Problem

If you assign 0.7 to a floating point variable num and then inside if condition you check if num == 0.7, it returns false. Because here variable num is of data type float and the constant value 0.7 is considered as double type data.

Comparison

Video Tutorial: Comparing Floating Point Variable With a Value In C Programming


[youtube https://www.youtube.com/watch?v=DXh6TsxLTME]

YouTube Link: https://www.youtube.com/watch?v=DXh6TsxLTME [Watch the Video In Full Screen.]

Source Code: Comparing Floating Point Variable With a Value In C Programming

#include<stdio.h>

int main()
{
    float num = 0.7;

    if(num == 0.7)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Not True

Some of you might get surprised with the result. But there is nothing to be surprised. It’s working the way it is intended to work.

Reason

We need to keep the basics in mind. When we input decimal numbers, it gets converted into Binary number system and then the further calculation occurs.

Now getting back to our problem: value present in floating point variable num is converted to its binary equivalent. But float has 4 bytes of memory storage.

#include<stdio.h>

int main()
{
    float num = 0.7;

    printf("%d\n", sizeof(num));
    printf("%d\n", sizeof(0.7));

    return 0;
}

Output:
4
8

Next the constant value 0.7 is converted into its binary equivalent. Since its data type is double, it has 8 Bytes of memory for storage. Hence it can store higher precision number.

Now the comparison between these two binary number occurs. Inside double, the binary number has more precision compared to floating point variable – due to available memory for each data type.

For Example:

#include<stdio.h>
int main()
{
    float PI = 3.14;
    double M_PI = 3.14159265358979323846;

    if(PI == M_PI)
        printf("YES\n");
    else
        printf("NO\n");

    return 0;
}

Output:
NO

Even though both variable PI and M_PI has value of PI in it, they’re not equal.

Quick Fix

There are 2 quick fixes for this bug:

1. Typecast constant value to float.
2. Declare double type variable instead of floating point variable.

1. Typecast constant value to float.

#include<stdio.h>
int main()
{
    float num = 0.7;

    if(num == 0.7f)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Yes, true

Inside if condition, we’ve converted double value 0.7 into floating point data, by appending f to it.

2. Declare double type variable instead of floating point variable.

#include<stdio.h>

int main()
{
    double num = 0.7;

    if(num == 0.7)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Yes, true

Best Example:

We had written a C program to Find Grade of Steel. One of our reader reported this comparison bug, and we fixed it using above method mentioned in this video.

Purposefully we’ve not altered the old code. We’ve preserved both old and new code, so that people can learn from our mistake. Take a look at: C Program To Find Grade of Steel

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Size of Pointer Variables

Lets write a C program to find out the size or the number of bytes occupied by pointer variables of different data type in your computers memory.

Related Read:
Sizeof Operator in C Programming Language
Basics of Pointers In C Programming Language

Video Tutorial: C Program To Find Size of Pointer Variables


[youtube https://www.youtube.com/watch?v=_EaAZYSvBog]

YouTube Link: https://www.youtube.com/watch?v=_EaAZYSvBog [Watch the Video In Full Screen.]


Source Code: C Program To Find Size of Pointer Variables

#include<stdio.h>

int main()
{
    printf("Size of int pointer = %d bytes.\n", sizeof(int*));
    printf("Size of char pointer = %d bytes.\n", sizeof(char*));
    printf("Size of float pointer = %d bytes.\n", sizeof(float*));
    printf("Size of double pointer = %d bytes.\n", sizeof(double*));
    printf("Size of long int pointer = %d bytes.\n", sizeof(long*));
    printf("Size of short int pointer = %d bytes.\n", sizeof(short*));

    return 0;
}

Output:
Size of int pointer = 4 bytes.
Size of char pointer = 4 bytes.
Size of float pointer = 4 bytes.
Size of double pointer = 4 bytes.
Size of long int pointer = 4 bytes.
Size of short int pointer = 4 bytes.

If you observe the output of above C program you can see that pointer variables, irrespective of their data type, consume 4 bytes of data in the memory.

Note: “But the number of bytes allocated for different data types and pointer variables are machine dependent. 16-bit, 32-bit, 64-bit computers allocate different bytes of memory. But pointer variables of any data type will always have same number of bytes occupied in the memory. For Example, if the computer allocates 2 bytes for pointer variable, then all the pointer variables, irrespective of their data type, will occupy 2 bytes in the memory.”

A pointer variable of type float holds only the address of floating point variable. A char pointer variable holds only the address of char type variable. But still the address of all these type of pointer variable is number. Addresses are always numbers and it can’t be a character, a string or real/floating/double numbers.

Also note that addresses are unique. There can’t be 2 location in your computers memory with same address.

Note: Observe that I’m using %d as format specifier while printing the size of data type, that’s because sizeof() function/method returns integer type data i.e., number of bytes occupied in the computers memory.

Note: sizeof() method takes a single argument and it is not a function whose value is determined at run time, but rather an operator whose value is determined by compiler – so it’s called as compile time unary operator.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Using Scanf in C Program

In our previous video tutorial you learnt about Integers, Float and Character data types and their format specifier. In today’s video lets see an example of using all 3 data types along with strings.

You’ll also learn to get user input from console using scanf function/method present in stdio.h header file.

Example: int, float, char

 
#include< stdio.h >

int main()
{
    int a;
    float b;
    char ltr;

    printf("Enter 2 numbers and a single character\n");
    scanf("%d %f %c", &a, &b, <r);

    printf("\nYou entered %d, %f and %c", a, b, ltr);

    return 0;
}

Output:
Enter 2 numbers and a single character
1 2 i

You entered 1, 2.000000 and i

Example for string type

 
#include < stdio.h >

int main()
{
    char c[10];

    printf("Enter a company name\n");
    scanf("%s", c);

    printf("\nYou entered %s", c);

    return 0;
}

Output:
Enter a company name
Microsoft
You entered Microsoft

Using Scanf() To Read Int, Float, Char and String Data Type: C Programming


[youtube https://www.youtube.com/watch?v=myqWGZePUgg]

YouTube Link: https://www.youtube.com/watch?v=myqWGZePUgg [Watch the Video In Full Screen.]


Keyword for Integer is int and its format specifier is %d.
Keyword for Float is float and its format specifier is %f.
Keyword for Character is char and its format specifier is %c.

Note 1: If you input decimal value for a integer variable, it only stores integer part of the value and discards the decimal value.

Note 2: printf and scanf are kind of opposite. Because printf converts all the numbers, characters etc and displays everything in text format on to the console. While, scanf takes all the text entered by the user in the console and converts them into respective data type based on the format specifier present in scanf statement.

Keywords, Constants, Variables: C

Computers do not understand English language. It can only understand machine code, a binary stream of 1s and 0s.

Learning The Building Blocks of C programming Language

To learn any language we need to first learn alphabets, then we learn to write sentences and then to write paragraphs. Similarly, in learning C programming language, we first learn about the Character Set(Alphabets, Digits, Special Symbols), next we learn words(keywords, variables, constants), and then we learn statements(C programming instructions), and then we write C programs.

Keywords, Identifiers And Literals: C


[youtube https://www.youtube.com/watch?v=D4ePj0ill5k]

YouTube Link: https://www.youtube.com/watch?v=D4ePj0ill5k [Watch the Video In Full Screen.]


Keywords

Every word in a C program is classified as either a keyword or an identifier. All keywords have fixed meanings predefined in the language and these meanings can not be changed.

Identifier / Literals

In programming languages, constants are usually called as literals and variables are called as identifiers.

Constants / Variables

As name suggests, a constant is an entity whose value doesn’t change during the course of program execution. A variable, on the other hand, is an entity whose value may change during the course of program execution.



C Constants

C Constants can be divided into 2 categories.
1. Primary Constants.
2. Secondary Constants.

Primary Constants are further divided into Integer Constants, Real Constants and Character constants.

Keyword for Integer is int and the format specifier is %d.
Keyword for Real is float or double and the format specifier is %f.
Keyword for Character is char and the format specifier is %c.

 
#include < stdio.h >
int main()
{
    const int a = 5;

    a = a + 1;

    printf("Value of a is %d", a);
}

Output:
error: Assignment of read-only variable ‘a’.

a is a constant variable and thus its value can not be changed through the course of program execution.

 
#include < stdio.h >
int main()
{
    int a = 5;

    a = a + 1;

    printf("Value of a is %d", a);
}

Output:
Value of a is 6

Note: Literals are constant values and not constant variables.