Darshi Innovations – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Sat, 05 Aug 2023 18:20:02 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Darshi Innovations – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Type Casting in C Programming https://shishirkant.com/type-casting-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=type-casting-in-c-programming Sat, 05 Aug 2023 18:19:57 +0000 https://shishirkant.com/?p=4049 Type Casting in C Language

In this article, I am going to discuss Type Casting in C Language with examples. Please read our previous article, where we discussed the Data Types in C Language. As part of this article, you will learn what is Type Casting in C, and why do we need Typecasting in C Language with examples.

Why do we need Type Casting in C?

If both data types are the same type then the return value will be the same. If both data types are different then among those two bigger ones will be the return type. When we are working with integral value with the combination of float then always return value will be float type. Let us understand this with an example.

#include <stdio.h>
int main()
{
   int i = 10000;
   long int l;
   float f;
   i = 32767 + 1;
   l = 32767 + 1;
   f = 32767.0f + 1;
   printf("%d %ld %f", i, l, f );
   return 0;
}

Output: 32768 32768 32768.000000

But what if you want to store a bigger value like a float in a smaller variable like int. Then in such cases, we need typecasting.

What is Type Casting in C Language?

It is a concept of converting one data type values into another data type. Typecasting is performing by using the cast operator. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to float. Casting allows you to make this type of conversion explicit, or to force it when it wouldn’t normally happen.

Type conversion in c can be classified into the following two types:

  • Implicit Type Conversion
  • Explicit Type Conversion
Syntax:
What is Type Casting in C Language
Example to Understand Type Casting in C Language:
#include <stdio.h>
int main ()
{
   float f = 10.25;
   int i; 
   i = (int) f;
   printf ("%d %f", i, f);
   return 0;
}
Output:

In the above C program, we are trying to store the floating value in an integer variable. So, we typecast it before storing it into the integer variable.

Note: It is best practice to convert lower data types to higher data types to avoid data loss. Data will be truncated when a higher data type is converted to lower. For example, if the float is converted to int, data that is present after the decimal point will be lost.

What is the cast operator in C?

Cast operator is a data type present in between parenthesis after the equal (=) operator and before the source variable.

Implicit Type Conversion or Implicit Type Casting in C:

When the type of conversion is performed automatically by the compiler without the programmer’s intervention, such type of conversion is known as implicit type conversion or type promotion.

It is the concept of converting lower data type values into higher data types. Implicit type casting is under the control of the compiler. So a programmer no needs to be considered the implicit type casting process. Let us see an example for a better understanding.

#include <stdio.h>
int main ()
{
   int i = 12345;
   long int l;
   l = (long)i; // Implicit casting from int to long int
   printf("%d %d", i,l);
   return 0;
}

Output: 12345 12345

Explicit Type Conversion or Explicit Type Casting in C:

The type conversion performed by the programmer by posing the data type of the expression of a specific type is known as explicit type conversion. The explicit type conversion is also known as typecasting.

It is a process of converting a higher data type value into a lower data type. Whenever the explicit type casting has occurred mandatory handling or else data overflow will occur. The typecasting in c is done in the following form:

(data_type) expression; where, data_type is any valid c data type, and expression may be constant, variable, or expression. Let us see a program for understanding this concept

#include <stdio.h>
int main ()
{
   double d = 12345.6789;
   int l;
   l = (int)d; //Explicit casting from double to int
   printf("%d %lf", l, d);
   return 0;
}

Output: 12345 12345.678900

Rules for Type Casting in C:

The following rules have to be followed while converting the expression from one type to another to avoid the loss of information:

  1. All integer types are to be converted to float.
  2. All float types are to be converted to double.
  3. All character types are to be converted to an integer.
Rules for Type Casting in C

Example:
int x=7, y=5;
float z;
z=x/y; /*Here the value of z is 1*/ 

If we want to get the exact value of 7/5 then we need explicit casting from int to float:

Example:
int x=7, y=5;
float z;
z = (float)x/(float)y; /*Here the value of z is 1.4*/

Inbuilt TypeCast Functions in C Language

There are many inbuilt typecasting functions available in C language which performs data type conversion from one type to another.

  • atof() Converts a string to float
  • atoi() Converts a string to int
  • atol() Converts a string to long
  • itoa() Converts int to string
  • ltoa() Converts long to string
atof() function in C:

The atof() function in the C language converts string data type to float data type. The “stdlib.h” header file supports all the typecasting functions in the C language.
Syntax: double atof (const char* string);

Example to understand the atof() function in C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
   char a[10] = "3.14";
   float pi = atof(a);
   printf("Value of pi = %f\n", pi);
   return 0;
}

Output: Value of pi = 3.140000

atoi() function in C:

The atoi() function in C language converts string data type to int data type.
Syntax: int atoi (const char * str);

Example to understand the C atoi() function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
   char a[10] = "100";
   int value = atoi(a);
   printf("Value = %d\n", value);
   return 0;
}

Output: Value = 100

atol() function in C:

The atol() function in C language converts string data type to long data type.
Syntax: long int atol ( const char * str );

Example to understand atol function in C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
   char a[20] = "100000000000";
   long value = atol(a);
   printf("Value = %ld\n", value);
   return 0;
}

Output: Value = 1215752192

itoa() function in C:

The itoa () function in the C language converts int data type to string data type.
Syntax: char *  itoa ( int value, char * str, int base );

Example to understand itoa function in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   int a=54325;
   char buffer[20];
   itoa(a,buffer,2); // here 2 means binary
   printf("Binary value = %s\n", buffer);
   itoa(a,buffer,10); // here 10 means decimal 
   printf("Decimal value = %s\n", buffer);
   itoa(a,buffer,16); // here 16 means Hexadecimal
   printf("Hexadecimal value = %s\n", buffer);
   return 0;
}
Output:
Example to understand itoa function in C

Note: “stdlib.h” header file supports all the typecasting functions in C language. But, it is a nonstandard function.

ltoa() function in C:

The ltoa() function in the C language converts long data type to string data type.
Syntax: char *ltoa(long N, char *str, int base);

Example to understand C ltoa function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   long a=10000000;
   char buffer[50];
   ltoa(a,buffer,2); // here 2 means binary
   printf("Binary value = %s\n", buffer);
   ltoa(a,buffer,10); // here 10 means decimal
   printf("Decimal value = %s\n", buffer);
   ltoa(a,buffer,16); // here 16 means Hexadecimal
   printf("Hexadecimal value = %s\n", buffer);
   return 0;
}
Output:
Example to understand C ltoa function
]]>
4049
Sizeof and Limits of Data Type in C Programming https://shishirkant.com/sizeof-and-limits-of-data-type-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=sizeof-and-limits-of-data-type-in-c-programming Sat, 05 Aug 2023 18:10:46 +0000 https://shishirkant.com/?p=4045 Sizeof and Limits of Data Type in C Language

In this article, I am going to discuss Sizeof and Limits of Data Types in C Language with Examples. In our last article, we discussed Character Data Type in C Language briefly. In this article, we are going to discuss two more concepts related to data type. The first one is the sizeof method or we can also call it sizeof operator and the second one is the limits of each data type.

Sizeof() Fucntion in C Language

The sizeof function is a predefined function just like the printf and scanf() functions.

What is the use of sizeof function in C?

The sizeof function in C Language is used to return the size of different things. So, what are the different things? The sizeof function returns the size of the following four things.

  1. Size of a variable.
  2. Size of a data type
  3. Size of an expression
  4. Size of a pointer

So, we can pass either variable, data type, expression, or pointer as an argument to the sizeof function. The sizeof function is a predefined function and that will return the size of different types of things. So, if you want to find out the size of any data type, we can go for a sizeof function. For better understanding, please have a look at the following diagram.

Sizeof and Limits of Data Type in C Language
Predefined sizeof function example in c language:

Please have a look at the following example which uses the predefined sizeof function.

#include<stdio.h>
#include<conio.h>
int main()
{
   char C;
   short S;
   printf("size of char : %d bytes(s)\n", sizeof(C));
   printf("size of short : %d bytes(s)\n", sizeof(S));
   printf("size of float : %d bytes(s)\n", sizeof(float));
   return 0;
}

In the above program, first, I am declaring two variables. One is of type character i.e. C and the second one is of type short i.e. s. Then I print the size of these two variables using the sizeof function.

What is the size? The size representation is always in the form of integers. So always use %d format specifier to show the size. Here, we are passing the variable names to the sizeof function. When we pass C variable name to the sizeof function, then it will return the size of the character. The size of the character is one byte. so it will print that value one.

Next, it will send the control to the next line. In the next line, we are printing the size of short, it is also %d because size is always in integers. And we know the size of the short is 2 bytes, so it will print 2 and send the control to the next line.

Whenever we are the calling sizeof function, we can pass either variable name, data type name, expression or pointer. In the next line, we are passing the data type float to the sizeof function. The size of the float is 4 bytes. So here it will print the value as 4 bytes.

So, when you run the above program, you will get the following output.

Predefined sizeof function example in c language

In our upcoming articles, we discuss how to pass expression and pointer to the sizeof function in C Language.

Limits of data type in C Language

Now we will understand the limits of a data type. What are the limits of a data type means we have one header file i.e. limits.h. The Limits.h header file contains n number of predefined variables and all these predefined variables are global variables. Global variable means we can access these variables from anywhere in any c application. These variables are also called constant variables. Constant variable means we cannot modify the values of these variables. We cannot modify limits.h header file. For better understanding, please have a look at the following diagram.

Limits of data type in C Language

Now we will see some programs on how to use a sizeof function and then we will see how to work with the limits.h variables.

Example to understand limits of data type in C Language:

Now, we will see how to print the limits of each data type. The Limits.h header file contain so many predefined constant variables i.e global variables. The limits.h header contains many predefined variables as shown in the below image,

Example to understand limits of data type in C Language

In any programming language, if you want to represent a constant variable. Then mostly, we are using capital letters only. All these variables are belonging to signed type and unsigned type.

The minimum range of every unsigned datatype starts with a zero. That is why they didn’t provide that info. All these variables are available in a limits.h, and all these are global variables. you can access anywhere in a C application and all these are constants.

Example:

Please have a look at the below program.

#include<stdio.h>
#include<limits.h>
int main()
{
   printf("Signed short MIN Value %d\n", SHRT_MIN);
   printf("Signed short Max Value %d\n", SHRT_MAX);
   printf("Unsigned short Max Value %d\n", USHRT_MAX)
   printf("Signed char MIN Value %d\n", SCHAR_MIN);
   printf("Signed char Max Value %d\n", SCHAR_MAX);
   printf("Unsigned char Max Value %d\n", UCHAR_MAX);
   return 0;
}

In the above program, we include the limits.h header file. This is because we are using some of the variables which are related to limits.h header file. Or else you will get an error message. When you run the above program, you will get the following output.

Sizeof and Limits of Data Type in C Language
]]>
4045
Character Data Types in C Programming https://shishirkant.com/character-data-types-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=character-data-types-in-c-programming Sat, 05 Aug 2023 18:07:38 +0000 https://shishirkant.com/?p=4041 Character Data Types in C Language with Examples

In this article, I am going to discuss Character Data Types in C Language with Examples. Please read our previous article where we discussed Integer Data Types in C Language. At the end of this article, you will understand everything about character data type in c language.

Character Data Types in C Language

The character data type is divided into two types one is signed data type and the second one is unsigned data type.

Character Data Types in C Language

Both Signed data type and unsigned data type occupy only one byte of memory. Unsigned means it will accept only positive values and the signed means it will accept both positive as well as negative values. Whatever the type either signed or unsigned, the character occupies only one byte.

Using 1 byte of memory what is the minimum and maximum value we can store?

To understand this, look at the memory allocation process. Here I am taking 1 byte of memory. 1 byte equals 8 bits. And it takes only binary values i.e. 0 and 1. Now, if we place zeros in all 8 places then the value will be zero which is the minimum we can store in a 1-byte memory location as shown in the below image.

Using 1 byte of memory what is the minimum and maximum value we can store?

If we place all ones in all the 8 bits, the value is 255. So, the maximum integer value we can store in 1 byte is 255 as shown in the below image.

Using 1 byte of memory what is the minimum and maximum value we can store?

So, using 1 byte of memory, the minimum integer value we can store is 0 and the maximum integer value we can store is 255.

Unsigned Character Range in C Language:

As we already discussed unsigned means it will accept only positive values. And the range 2equals 256. As positive value starts with 0, so, the unsigned character data type range is from 0 to 255.

Signed Character Range in C Language:

Now let us understand the range of Signed character data types. The signed data type accepts both positive as well as negative values. So, we need to divide 28 = 256 by 2. 256/2 the value is 128. So negative values start with -1, -2, and up to -128 and the positive values start from 0 up to 127.

We are using character data type to store symbols like a, b, A, B, or some special symbols. Then how can we represent such symbols in integers? Why character data type representation in integer. So, while working with Character Data Types in C Language, we need to understand the following four questions.

  1. Why does character limits representation in integers?
  2. How can we store symbols into one-byte memory nothing but why character occupies one-byte memory?
  3. What is a character system?
  4. What is ASCII?

Consider the below diagram. It is a simple program and we name this program as Program.c, and inside the main method, we are declaring one integer local variable and assigned with a value of 10 and the remaining instructions are also there as it is. We can call it source code.

Character Data Types in C Language with Examples

In our previous article, we already discussed that whatever program we have written using any high-level programming language that the system cannot understand. This is because the system can understand only binary language. But you have written an English statement. We should convert all these high-level instructions into low-level. Who will convert? The Answer is the compiler.

The compiler is a predefined program. We need to pass the source code to the compiler and the compiler will then generate the binary instructions code which is in the form of zeros and ones. So, the compiler needs to convert all these high-level instructions into machine level. Consider 10, it will convert into binary i.e. 1010 and this is possible by using the number system. So, using the number system concept we can convert the decimal value to binary value.

But here the problem is how it is converted #, <, >, a, I, A, etc. symbols into binary. If the decimal value is there, we can use a number system to convert it into binary. But how we can convert characters (a, b, A, B) and special symbols (#, <. >, etc.) into binary? The answer is the character system. Only for computer programming languages, the character system was introduced.

What is a character system?

Using a character system, we can represent one entire language into integer constants. For example, the English language contains capital letters, small letters, digits special symbols, etc., and using a character system we can represent all the above characters and symbols into integer constants. This is called a character system.

How many character systems are available?

A list will come if you search on google. A number of character systems are available. The first computer was introduced into the market by IBM. IBM is having its own character system. Now, the famous one is the ASCII character system, and every programming language follows the ASCII character system only. Let us see how using the ASCII character system, we can represent one particular language.

What is ASCII? What it stands for?

Now let us understand the English language ASCII Code. ASCII stands for Americans Standard Code for Information Interchange. A standard code means it is a fixed code, no one can change the value and no one can modify the value. It is used to interchange the information from high-level language to low-level language.

How ASCII represents?

To understand how ASCII represents the English language, please have a look at the below diagram,

What is ASCII? What it stands for?

As you can see in the above image, capital A is represented by a constant integer value 65 and this is the fixed value and no one can change this value. The next one is for capital B and is 66 and for capital C it is 67, so on and for capital Z it is 90. The value of small a is 97 and small B is 98 and so on up to small z whose value is 122.

For digit 0, the ASCII value is 48, for 1 the value is 49 and for 9, the ASCII value is 57. Using the digits 0 to 1, you can construct any number, so they have given ASCII for 0 to 9 only.

For special characters, if it is a space the value is 32, for #, the value is 35, and so on for every symbol. So, every character, digit, special symbol, is represented by a constant integer value in the character system. Not only in the ASCII character system but in any character system which is available in the market.

So, for every language like English, Hindi, Odia, there is a character system. Here, the above diagram representing the English language using the ASCII character system, and these are the standard values.

How can we store a symbol into one-byte memory?
How can we store a symbol into one-byte memory?

Just count all the values, so total will 26 capital alphabets we have in English and 26 small letters and next 10 numbers and not more than 150 special symbols. So here if you add all these, then this is less than 256. Any language you can take in this world, it is at most having 256 symbols. So, ASCII decided that if we assign the values for these symbols from 0 to 255, so you can represent any character in the language using one byte of memory.

How can we say that one-byte memory?

256 is nothing but a 2 power 8 value. 2 power 8 is nothing but a one-byte memory. This is the only reason every character we can represent using one byte of memory in a programming language.

Character Data Types Examples in C Language

Now we will see some of the examples on the character data type. First, let us understand the unsigned character and signed character in the form of circles.

Understanding signed char data type circle in c Language.

If it is a signed character the limits are from -128 to +127. Let us write all these limits in the form of a circle and based on these circles only we will see how programs will execute.

Either positive value or negative value always the counting starts with 0. Positive value counting starts from 0, 1, 2, and so on up to 127 in a clockwise direction, and here the maximum positive value is 127. Negative values counting starts from -1, -2, -3, and so in up to -128 in an anti-clockwise direction as shown in the below image.

Understanding signed char data type circle in c Language.

Note: In the declaration of variable if you are not specifying whether the variable is a signed variable or unsigned variable by default it is a signed variable and can accept both positive and negative values.

Understanding unsigned char data type circle in c Language.

If it is an unsigned character the limits are from 0 to 255 and the unsigned char data type accepts only positive values. In the case of unsigned char, the circle starts from 0, 1, 2, so on and ends with 255 i.e. the maximum positive value is 255 as shown in the below image.

Understanding unsigned char data type circle in c Language
Example to understand character data type in c language:

Following is a simple example of a c program using char data type. Here, inside the main function, we are declaring one character variable with the name CH (you can give any name as per your choice) and assigning this variable with the value A. In the C programming language, we are representing characters by using single quotes. Then we are printing the character in the console. To print the character in the console we need to use the format specifier as %c. %c is the format specifier for character and it will print the value A in the console. Next, we have also written the %d format specifier for the character variable CH. In this case what it will print? Here, it will print the corresponding ASCII value of character A which is nothing but 65.

#include <stdio.h>
int main()
{
  char CH = 'A';
  printf("%c", CH);
  printf(" %d", CH);
  return 0;
}

Output: A 65

Now we will see some tricky questions on character data type which are mostly asked in interviews.

#include <stdio.h>
int main()
{
   char CH = 258;
   printf("%c", CH);
   printf(" %d", CH);
   return 0;
}

In the above example, we have initialized the character variable CH with a value of 258. Yes, we can store integers on the character data type. The above CH variable is by default a signed character. So, to understand what value it will store we need to understand the signed char circle and see the actual value of 258. As 258 is a positive value, so the count will start from 0, 1, and so on in a clockwise direction. In the circle when it reached 127, the next value is -128 (in count it will be 128), the next is -127 (in count it will be 129), and in the same way, -1 will be for 255, the next value in the circle is 0 which is 256, 1 for 257, and 2 for 258. So, in the variable instead of 258, it will store.

Example to understand character data type in c language

So, in the output for %d format specifier, it will print 2 and for character specifier, it will print some unknown value i.e. 2 corresponding unknown characters it will print from the ASCII character system and when you run the above code, you will get the following output.

Example to understand character data type in c language

Now, we will see how to write a program in which we will input one character and it has to print that corresponding ASCII value. In this program, we are going to work with the scanner function. Using the scanf function, we are taking input from the end-user in the C programming language.

What is a console?

The console is where you can see the output and where we can give the input.

Write a program to display ASCII value of character input by end-user.

We want to read information from the end-user while the application is executing is our concept. We are reading information from end-user i.e. we are taking input from the end-user. Please have a look at the below program. Here, I am declaring one character variable with the name CH i.e. char CH; here, the variable CH gets memory allocation.

On the console first, we print a message and asking the end-user to enter a character. We are reading the end-user input using the scanner function. The scanner function is available in stdio.h header file.

What end-user want to do they cannot understand that, so that is the reason we need to provide some information. Best example atm application, whenever you enter into an atm center clear information it will show please choose one language, insert your atm card, insert your pin number and how much amount you want to withdraw. Information is very important, how good you are writing the logic is not at all matters. First, we are asking the message very clearly i.e. enter one character. Whatever the message you have written in the printf function, that will be written on the console. It will print that message enter a character.

Whenever the end-user will enter one character, for example, the end-user entered a character h. Then automatically system will print the ASCII value of h. h should be stored in some memory location. So here we need to provide a memory address. How to provide a memory address, who will provide a memory address? So, for the first time, we are using scanf function in C programming.

If you want to read only one character, so write one time %c format specifier. If you want to read ten characters then you have to write %c 10 times. But here it is only one character, so here we are specifying the character address by using the & address operator. It will return the address of the memory location of the CH variable. Whatever character we have given in the console will be stored in that location. h corresponding ASCII value will be converted into binary and then the binary value will go and store in that memory location. Now we want to print the ASCII value just printf “ASCII Value is %d” and output will be generated. Whatever we discussed above is given in the below example.

#include <stdio.h>
int main()
{
   char CH;
   printf("Enter a Character : ");
   scanf("%c", &CH);
   printf("ASCII Value is %d", CH);
   return 0;
}
Output:
Write a program to display ASCII value of character input by end-user.
]]>
4041
Integer Data Types in C Programming https://shishirkant.com/integer-data-types-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=integer-data-types-in-c-programming Sat, 05 Aug 2023 18:01:02 +0000 https://shishirkant.com/?p=4038 Integer Data Types in C Language with Examples

In this article, I am going to discuss Integer Data Types in C Language with examples. Please read our previous article where we discussed the basics of Data Types in C. We already discussed in our previous article that the Integer data type is divided into six classifications as shown in the below image.

Integer Data Types in C Language with Examples

The first classification is short type. Short again divided into two sub-classifications, it is signed short and unsigned short. Either it is a signed short or is unsigned short, it occupies two bytes of memory.

What is a signed data type?

Using signed data type both positive and negative values we can store.

What is the unsigned data type?

Using unsigned data types, we can store only positive values.

Using 2 bytes of memory what is the minimum and maximum value we can store?

To understand this, look at the memory allocation process. Here I am taking two bytes of memory. 1 byte equals 8 bits, so 2 bytes equals 16 bits. And it takes only binary values i.e. 0 and 1. Now, if we place zeros in all the 16 places then the value will be zero which is the minimum we can store in 2 bytes memory location as shown in the below image.

Using 2 bytes of memory what is the minimum and maximum value we can store?

If we place all ones in all 16 bits, the value is 65535. So, the maximum integer value we can store in 2 bytes is 65535 as shown in the below image.

Using 2 bytes of memory what is the minimum and maximum value we can store?

So, using 2 bytes of memory, the minimum integer value we can store is 0 and the maximum integer value we can store is 65535. Now, let us come to the signed and unsigned data type. 1 byte is 8 bits and 2 bytes is 16 bits. The unsigned short data type can store only positive integer values ranges from 0 to 65535 as shown in the below image.

Integer Data Types in C Language

The signed short data type can store both positive and negative values. So, here just divide the value by 2 i.e. 65536/2 which will result in 32768. The negative or minus value always starts from -1, -2, up to -32768. And the positive value starts from 0, 1, and up to 32767 for signed short as shown in the below image.

Integer Data Types in C Language
Declaration of signed short Data Type in C Language:

If you do not specify whether the variable is a signed variable or an unsigned variable, by default that is a signed variable and can accept both positive and negative values. Following are the examples of declaring signed short variables in c language

short a;
short int a;
signed short a;
signed short int a;

For All the above four signed declarations, the format specifier is %d. In these many ways, we can declare a signed variable in our C program.

Declaration of unsigned short Data Type in C Language:

In unsigned declarations, we must specify explicitly that these are unsigned declarations. Following are the two ways to declare unsigned short data type in c language.

unsigned short a;
unsigned short int a;

For these two unsigned declarations, the format specifier is %u. So, these are the total of six declarations about a short data type. First, four comes under the signed short declarations and the last two comes under the unsigned declarations. For better understanding, please have a look at the below image.

Declaration short Data Type in C Language
The next important thing is what is format specifier?

If you want to read the information or if you want to display the information, formatting is very important. In which format do you have to read information and in which format do you have to print the information. That you have to specify to the computer using a format specifier.

Example:

Now we will see some programs. I just want to print a small value on the console. We are writing the program and the execution starts from the main method. I am declaring one variable; it is a short variable and then prints it on the console.

#include <stdio.h>
#include <stdlib.h>
int main()
{
   short a = 10;
   system("cls");
   printf("%d", a);
   return 0;
}

Output: 10

In the above example, short a = 10; declaring a variable of type short and assigned with value 10. We want to print the value of the variable on the console, so here, we are using printf function which belongs stdio.h header file. Inside the double quotes, we have to write the format specifier. As variable a is a signed variable, so the format specifier is %d and we want to print the value of a. Value of a is 10, so program output will be 10.

Note: To clear the screen in the Linux system use system(“clear”) function which is included in stdlib.h, and if you use this in the window use the system(“cls”).

This is a very simple program and here, format specifier is very, very important. With the help of a format specifier only we are reading the elements and printing the elements.

Complex Examples using short Data Type in C Language:

Next, we will see some complex programs. Consider the limits of signed short data type in the form of a circle. The range of minimum and maximum values of signed short data type is -32768 to +32767 as shown in the below image.

Any value you want to count, whether +VE values and -VE values, the count is always going to start from 0. Positive values are going to be count in a clockwise direction and the maximum value is 32767. The negative values count is going to be the anti-clockwise direction and it will start from 0, -1, -2, up to -32768. For better understanding please have a look at the below diagram.

Complex Examples using short Data Type in C Language

Based on the above diagram we will see one program. I just want to print a big value on the console. We are writing the program and execution starts from the main method. I am declaring one short variable.

#include <stdio.h>
int main()
{
   short a = 32769;
   printf("%d", a);
   return 0;
}

Output: -32767

Why we are getting -32767, not 32769. As the value is a positive number so the count will start clockwise from 0 and reach the maximum value of 32767. Now, please observe, what is the next value of 32767 in clockwise direction, it is -32768 (32767+1 = 32768) and what the next value, it is -32767 (32768+1 = 32769) and that is printed on the console. So, in this case, when the value exceeds, it will print a garbage value. In this case, it is not giving any error instead it prints a garbage value.

Unsigned short Integer Data Type Example in C Language:

Now we will see one more program. Please have a look at the below example. Here, we are declaring a variable of unsigned short type but assigning a negative value i.e. -5. We know, unsigned short only take positive values. Let us first execute the program and see the output.

#include <stdio.h>
int main()
{
   unsigned short a = -5;
   printf("%d", a);
   return 0;
}

Output: 65531

To understand why we are getting 65531 in the output, we need to understand the unsigned short data type in the form of a circle. The range of minimum and the maximum values is 0 to 65535 for unsigned short and it moves in a clockwise direction for +VE values and anti-clockwise direction for -VE values as shown in the below image.

Unsigned short Integer Data Type Example in C Language

Now, as we are assigning -5 to the unsigned variable, so it will start counting in an anti-clockwise direction. So, it will start from 0, then 65535 for -1, 65534 for -2, 65533 for -3, 65532 for -4, and 65531 for -5 and it will store 65531 in the memory location, and that is what you can see in the memory output.

As we are using the %u format specifier, it will look into an unsigned circle diagram for the value of a. In the memory location, the value of a will be stored as 65531. Because -5 is not in the range of unsigned short variable, so it will look in an anti-clockwise direction.

Example: unsigned short Integer in C Language

Now we will see one more program. In the below program, we declare an unsigned variable and assigned it a value 65538.

#include <stdio.h>
int main()
{
   unsigned short a = 65538;
   printf("%u", a);
   printf(" %d", a);
   return 0;
 }

Output: 2 2

Let us understand why we are getting 2 as the output. To understand this, first, we need to understand what value is going to be stored in the memory location for the variable a. So, here, the variable a data type is unsigned, so it will check the unsigned circle which is start from 0 and ends with 65535 and counts the numbers in a clockwise direction. So, it will start from 0, and goes up to 65535 in the circle. What is the next value in the clockwise direction of 65535, it is 0. So, 0 for 65536, 1 for 65537, and 2 for 65538. So, in the memory location, it will store the value 2.

Now, in the first printf statement, we have used the %u format specifier, so it will check the unsigned short circle and found value 2 is therein and hence it will print that value. In the second printf statement, we have used %d format specifier, so it will check the signed short circle and found value 2 is therein and hence it will also print that value in the console.

Now we will see one more program. In the below program, we declare one unsigned short variable and assigned it with a value -32772.

#include <stdio.h>
int main()
{
   unsigned short a = -32772;
   printf("%u", a);
   printf(" %d", a);
   return 0;
}

Output: 32764 32764

]]>
4038
Data Types in C Programming https://shishirkant.com/data-types-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=data-types-in-c-programming Sat, 05 Aug 2023 17:55:33 +0000 https://shishirkant.com/?p=4035 Data Types in C Language with Examples

In this article, I am going to discuss Data Types in C Language with examples. Please read our previous article, where we discussed the Variables in the C Program. As part of this article, you will learn what are Data types in C, their type, and when and how to use Data Types in C Program with examples.

Data types are used to store data temporarily in the computer through the program. In the real world, we have different types of data like integer, floating-point, character, string, etc. To store all these types of data in the program to perform business required calculations and validations we need the concept data types.

How to Declare a Variable in C?

In the declaration of every variable, it is mandatory to specify its data type. If you just look at the syntax of the variable you will understand, the variable declaration is consisting of two parts i.e. the data type which is important followed by the identifier which is as follows.

Syntax: DataType Identifier;
Example: int a;

In the above variable declaration, a is the identifier and int is the data type.

What is a Data Type in C Language?

It is just a representation of data. That means how much memory is required to be allocated and what type of data is allowed to store. These two are represented by the data type in any programming language. Suppose I am declaring a variable of type integer

int a;

Here ‘a’ gets memory allocation at some location. We have already discussed; the memory address is a positive integer. So, every variable gets memory allocation and the integer variable occupies 2 bytes of memory. So, once the variable is ready, what type of data is allowed? Suppose, here, I am storing -15 which is a negative integer number, so it is allowed. Next, if we store 17 which is a positive integer, then also it is allowed in C language. But can we store 12.34? The answer is No. Decimal values are not allowed. For better understanding, please have a look at the following diagram.

What is a Data Type in C Language?

Simply datatype represents two things about a variable.

  1. What type of data is allowed to store?
  2. How much memory is required to store the data?

These two things are described by a data type.

How many types of data types are available in the C language?

Data types in C Language are classified into three types as follows.

  1. Primitive Data Types: Integer, character, float, void. All these are called primitive data types.
  2. Derived Data Types: Array, String, Pointer, etc. come under derived data types.
  3. User-Defined Data Types: Structure, union, typedef, enum, etc. are comes under user-defined data types.

For better understanding, please have a look at the below diagram which shows a high-level classification of C Language data types.

How many types of data types are available in the C language?

Note: We will discuss Derived and User-defined Data Types later as Array, Function, Pointer, Structure, and Union, etc. are separate concepts in C Language. Here, in this article, we just going to keep the focus on the Primitive Data Types.

Classification of Primitive Data Types in C Language:

As we already discussed the Primitive Data Types are classified into four types are as follows.

  1. Integer
  2. Character
  3. Float
  4. Void
Integer Data Type in C Language:

Again, Integer is divided into three types are as follows.

  1. Short
  2. Int
  3. Long

Again, the short data type is divided into two types i.e. signed short and unsigned short. Same for int and long i.e. signed int, unsigned int, signed long, and unsigned long. So, one integer data type is again subdivided into 6 types. For a better understanding of the integer data types, please have a look at the below image.

Integer Data Type in C Language
Why integer data type is classified into six types?

The basic advantages of classifying these many types of nothing but utilizing the memory more efficiently and increasing the performance. If you want to store one integer value, one integer data type is enough. It depends on the data and also depends on the size of the data. For example, department number is something like 10, 20, and 30, etc. To store such type of data, a very little integer is enough, so we can consider short data type. Consider I am trying to store a phone number or I am trying to store an account number, such type of things we can store with the help of long integer type.

Depending on the size of the data, we choose a particular datatype. Suppose to store the value 10, 1 Byte memory is required. then we should go for a data type in which it occupies only one byte of memory. In this case, if you are trying to choose a data type that occupies 4 bytes, then you are wasting 3 bytes of memory in your application. 3 bytes of memory we are wasting which will reduce the performance of the application.

Character Data Type in C Language:

The Character Data Type in C language is divided into two types. One is a signed character and the second one is an unsigned character. Both are of size 1 byte. For a better understanding of the Character data types, please have a look at the following image.

Character Data Type in C Language
Float Data Type in C Language

The Float Data Type in C language is divided into three types one is float type, the second one is double and the last one is long double. Float is of size 4 bytes; double is of size 8 bytes and long double is of size 10 byte. For better understanding, please have a look at the following diagram.

Float Data Type in C Language

Classification of Primitive Data Types in C Language
Which data Types take how many bytes of Memory in C Language?

If it is a short data type, either it is signed or unsigned, it occupies two bytes of memory. If it is an integer data type, either signed or unsigned, it will occupy two or four bytes of memory depending upon the compiler you are using. For long data type, either signed or unsigned it occupies 4 bytes of memory. For character data type, for signed and unsigned it will take 1 byte of memory. The float data type will take 4 bytes of memory; double will take 8 bytes of memory and long double will occupy 10 bytes of memory.

What is assigned and unsigned in c Language?
What is assigned and unsigned in c Language?

Using signed data type, we can store both positive or negative values. In our program, we are not always working with only positive values. Sometimes requirements will be there to store negative value. In that situation, we should go for the signed type because the signed data type will accept both positive and negative values. But if it is an unsigned type, the unsigned type strictly accepts only positive values. Negative values will not be accepted. This is the difference between signed datatype and unsigned datatype.

Integer Data Type in C

Int is used to define integer numbers. The size of the data type ‘int’ is 2 bytes or 16 bits. The minimum value for the signed ‘int’ data type is -32768. The maximum value for the signed ‘int’ data type is 32767. We can declare int data type as follows:

int c;
c=5;

Float Data Type in C

Float is used to define floating-point numbers. The size of the data type ‘float’ is 4 bytes or 32 bits. The minimum and maximum values for the ‘float’ data type are 3.4E-38 to 3.4E+38. We can declare a float data type as follows:

float Miles;
Miles=5.6;

Double Data Type in C

Double is used to define BIG floating-point numbers. It reserves twice the storage for the number. On PCs, this is likely to be 8 bytes. The size of the data type double is 4 bytes or 32 bits. The minimum and maximum values for the ‘double’ data type are 1.7E-308 to 1.7E+308. We can declare a double data type as follows:

double a;
a=2500;

Char Data Type in C

Char defines characters. The size of the data type char is 1 byte or 8 bits. The minimum and maximum values for the ‘char’ data type are -128 to 127. We can declare char data type as follows:

char Name;
Name=’x’;

Example to demonstrate the Built-in Data Types in C Language
#include <stdio.h>
int main()
{
   int a = 4000; // positive integer data type
   float b = 5.2324; // float data type
   char c = 'Z'; // char data type
   long d = 41657; // long positive integer data type
   long e = -21556; // long -ve integer data type
   int f = -185; // -ve integer data type
   short g = 130; // short +ve integer data type
   short h = -130; // short -ve integer data type
   double i = 4.1234567890; // double float data type
   float j = -3.55; // float data type
}
Modifiers in C Programming Language:

The amount of memory space to be allocated for a variable is derived by modifiers. Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of storage space allocated to a variable.

For example storage space for the int data type is 4 bytes for a 32-bit processor. We can increase the range by using long int which is 8 bytes. We can decrease the range by using short int which is 2 bytes.

There are 5 modifiers available in the C Programming language. They are,

  1. Short
  2. Long
  3. Signed
  4. Unsigned
  5. long
Modifiers in C Programming Language
Derived Data Types in C Language:

Derived data types in C Programming Language are those C data types which are derived from the fundamental data types using some declaration operators. The basic derived types that are available in C are:

  1. Array.
  2. Functions
  3. Pointers.
  4. Structures.
  5. Classes.
Array Derived Data Type in C

The arrays can be defined as a set of finite and homogeneous data elements. Each element of an array is referenced using an index.
Example: If the name of an array is A which has 4 elements then the array will be represented as A[0], A[1], A[2], A[3]. Here, these subscripts which are containing the digit are known as an index.

Function Derived Data Type in C

The function can be defined as a part of the program which is declared by the programmer in any part of the program and a function can be of any name depending upon the choice of the programmer. The function declared can be invoked from other parts of the program.

Pointer Derived Data Type in C

A pointer is a variable that holds the address of the memory space. If one variable can hold the address of another variable then it is said that the first variable is pointing to the second. Structure Derived Data Type in C

The structure can be defined as a collection or a group of variables that are referenced under one name. It is used to keep related information together. We use a ‘struct’ keyword to construct a structure.

Enumeration Data Type

Enumeration data type consists of named integer constants as a list. It starts with 0 (zero) by default and the value is incremented by 1 for the sequential identifiers in the list. Enum data type is a user-defined data type having a finite set of enumeration constants. The keyword ‘enum’ is used to create an enumerated data type.

Syntax: enum [data type] {const1, const2…., const n};

Example to Understand Enum in C:
#include <stdio.h>
int main()
{
   enum MONTH
   {
      Jan = 0, Feb, Mar
   };
   enum MONTH month = Mar;
   if(month == 0)
    printf("Value of Jan");
   else if(month == 1)
    printf("Month is Feb");
   if(month == 2)
    printf("Month is Mar");
}
Output:
Example to Understand Enum in C
Void Data Type in C Language:

The void is an empty data type that has no value and no operations. This can be used in functions and pointers. It’s a data type that represents the lack of a data type. Many programming languages need a data type to define the lack of return value to indicate that nothing is being returned.

Example: void f(void);

void f(); (accepts a constant but unknown number of arguments)

Uses of Void Data type in C:

When used as a function return type: the void keyword specifies that the function does not return a value.

void show()
{
   printf("This function has no return type");
}

When used for a function’s parameter list: void specifies that the function takes no parameters.

int sum(void)
{
   int a,b;
   printf("Enter Two number>> ");
   scanf("%d%d",&a,&b);
   return a+b;
}

When used in the declaration of a pointer: void specifies that the pointer is “universal.”

void main()
{
   void *p;
   int a=10;
   char b='A';
   float c=9.19;
   p=&a;
   printf("\nPrinting Integer data %d",(*(int *)p));
   p=&b;
   printf("\nPrinting character data %c",(*(char *)p));
   p=&c;
   printf("\nPrinting float data %f",(*(float *)p));
}
When to use which Data Types in C Language?
  • In implementation when we are required character operations then go for ‘char’ or ‘unsigned char’ data type.
  • For normal numeric operations go for the “int” data type. If there is no -ve representation then go for “unsigned int” data type like employee salary.
  • In implementation when we required the numeric values for the range of -128 to 127 then go for “char” data type in place of creating an “int” in this case we are required to use the %d format specifier.
  • In implementation when we required the numeric values from the range of “0 to 255” then go for an unsigned char data type in place of creating unsigned int. In this case, we are required to use the ”%u” format-specifier.
  • Signed, unsigned, short and long are called qualifiers and we need to apply these qualifiers to an integral type only i.e. we cannot apply to float, double, and long double type.
  • Signed, unsigned is called signed qualifiers.
  • Short and long are called size qualifiers.
  • By default any integral variable size is short and the sign is signed type.
In Short,

The data type determines the storage/value properties like

  1. Type of value
  2. No.of bytes
  3. Range

To store anything in our computer, we should have to reserve the memory. This memory size and other properties are decided by data type. C language provides 3 basic / fundamental data types.
1. int
2. float
3. Char

]]>
4035
Introduction to Functions in C Programming https://shishirkant.com/introduction-to-functions-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=introduction-to-functions-in-c-programming Sat, 05 Aug 2023 17:47:02 +0000 https://shishirkant.com/?p=4032 Introduction to Functions in C Programming Language

In this article, I am going to give a brief introduction to functions in C Programming Language, mainly what is function and functionality and how many types of function declarations present in C language. Please read our previous article where we discussed Variables in C Programming Language.

What is a function?

A function is a block of instructions (here we can write n number of valid instructions) having identity (the name is mandatory) and taking inputs (technically called as argument list) and processing the input and finally, it produced the output (technically we called it as return type). For better understanding, please have a look at the following diagram.

What is a function?
Understanding Function with an Example in C Language:

Let us see an example to get more clarity on function. Please have a look at the following diagram. Just consider the block of instructions and is identified by the name add. I want to perform the additional operation. If you want to perform an addition operation, what is the minimum input you have to pass, the minimum input is two integers? For example, take a calculator, I want to perform an addition operation, minimum of two numbers you have to press, or else it is not possible to perform an addition operation. So here are two numbers we are collecting into two variables i.e. int x and int y. Suppose if you type 10 and 20 then 10 will go and store into x and 20 will go and store into y. And in the processing logic, we are adding x and y and storing the result into the z variable. After processing the information, we are returning that value store in the z variable. The variable z is of integer type, so the return type of the add function is an integer.

Understanding Function with an Example in C Language

So, function means what, it is doing some tasks. The marker is functioning means what, it is doing something. What the marker is doing, it is writing. Mobile is functioning means what, so many functionalities are there. We are calling, we can message, we can play games, we browse the internet, etc. A person functioning means what, a person can teach, a person can walk, a person can speak, a person can eat, a person can play, etc. So, all these are coming under functionalities. So, what is a function means, is performing a particular task. So, in our example, the add function performing the addition of two numbers task,

So, finally, the definition of function is, block of instructions having an identity that is taking input, processing the input, and producing the output.

One more important point that you need to add to function is, only if you are writing the definition of a function, is no use. In every program along with the function definition, one more thing is also important i.e. function call.

For example, calculator, they already defined one functionality addition i.e. plus button they are given. In the entire lifetime of the calculator, if no one is using that identity nothing but no one is using that plus button, then what is the use of that. If one object is there nothing but one physical thing is there and it is having functionality means everyone should use that functionality at least once in its lifetime.

What is functionality?

So simply we can understand what is functionality means just consider one electronic device and the best example is television which we use in our daily life. In the background, one program is there which is running with the help of the program. They have already written one program, how they will write the program means to on the television one functionality is required, it is power on and to off the television another functionality is required i.e. power off. To change the channel functionality is there. And mostly one more functionality we are using every day is volume, so, volume is the functionality they have given. The logic they are already written. But see only functionality is of no use. If you just look at the TV, will it start automatically? Impossible right. Will it change the channels automatically? absolutely not. Along with the functionality i.e. along with the function definition, calling is also very important.

Another person nothing but another program. suppose take one person and the person is using the remote control. The remote controller is also a program and the person is also a program and the television is also a program. And they have to call the functions. One is on function, another off function as well as channel change function. They will do for example channel + + channel – -, volume + + volume – -, etc. So. another program (a person) should call the functionality of television from another place (remote controller). So, whenever they click on the ON function, then the corresponding logic executes and the system will on, and whenever they click on the OFF button then automatically off functionality executes. So, not only the definition is important, but function calling is also important. For better understanding please have a look at the below image.

What is functionality?
Classification of Functions in C Language:

Generally, only four method classifications are present, whatever the programming language you take. If you look at one particular method or one particular function, the function will belong to any one of these four classifications. There are generally 4 types namely:

  1. NO ARGS & NO RETURN
  2. WITH ARGS & NO RETURN
  3. WITH ARGS & WITH RETURN
  4. NO ARGS & WITH RETURN
NO ARGS & NO RETURN FUNCTION

The first classification is no argument and no return values. I am writing one function, this function name is fun, it is a block of instructions. The function is not taking anything i.e. taking no arguments. In this classification, there are no arguments, so here we need to write no arguments and no return values. For better understanding, please have a look at the below diagram. Void is representing no value and it means nothing. So, no arguments and no return values. This function is a block of instructions and it is not taking any arguments and not returning anything to anyone.

NO ARGS & NO RETURN FUNCTION IN C LANGUAGE
WITH ARGS & NO RETURN FUNCTION

Next comes the second classification, with arguments and no return values. We need to pass the arguments of values integers, float, double character, strings, etc. All these come under input types. For better understanding please have a look at the below diagram. Here, simply I am passing one integer to collect that. It will process that input with the predefined logic and finally, it will return the output. Output is a void because no return values mean it is not returning anything.

WITH ARGS & NO RETURN FUNCTION
WITH ARGS & WITH RETURN FUNCTION

The third classification is a function with arguments and also with return values. For better understanding, please have a look at the below image. Here, the function is taking arguments and we are passing characters. Any number of arguments we can pass. It has no limitations and depends on your application requirement; the function can take any number of arguments. Here, simply I am passing only one argument i.e. of type character and here it has return values. So, the return statement is mandatory. Return statement 13 means, it is returning value 13 and it is of integer data, so the return type is also an integer.

WITH ARGS & WITH RETURN FUNCTION
NO ARGS & WITH RETURN FUNCTION

No arguments and with return values means no arguments and with return values. For better understanding, please have a look at the below diagram. See here function fun is having no arguments means void. We need to write void with return values. What it is returning? Suppose here it is returning the value 34.56. it is of type float type or double. So here the return type is also float.

NO ARGS & WITH RETURN FUNCTION in C Programming Language

There is no such restriction that, what type of data we are taking, has to return the same type of data. For example, in the withdrawal operation in Bank. The input is a just pin number and how much amount you want to withdraw but the output is the amount of money. Take a deposit function input is the money and output is “Deposit Successful”. So, there is no relation between input and output. Any function can take different types of inputs and other types of outputs.

If only the function definitions are present then it is of no use. If functionality is there someone should call that functionality. If only functionality is there, it is of no use someone should call it from another place. The function should have a definition, along with the definition function call is also important. If a function call is not there then it is of no use.

How to call these functions?

Depends on the classification.

Calling No Args and No Return Function in C Language

Function calling is always a single statement. A single statement means it must end with a semicolon. For better understanding please have a look at the below image. Whenever you call this function, is it expecting anything?? Is it taking any input?? The answer is No. So, no need to pass anything here it is empty. Is it giving anything?? No. It is not returning anything, so here the return type is also empty. The function is not taking any input so no need to pass any input and it is not giving anything so no need to get anything.

Calling No Args and No Return Function in C Language
Calling With Args and No Return Function in C Language

Calling With Args and No Return Function in C Language
Calling With Args and With Return Function in C Language

Please have a look at the below diagram for a better understanding. In this case, what it is expecting?? It is expecting a character. In any programming language, we will represent characters using single quotes. If you want to pass character, any character you can pass. Here I am passing character ‘g’, we are placing in a single quote. So, whenever you call this function that ‘g’ will go and store into variable x. This is the value it will hold, and the output will be 13. We should collect them into another variable. Here it is returning 13, 13 is of type integer. So, we are collecting that result into an integer type variable only. For assignment operators always right-side data executes first. We are calling the function and we are passing the input character and it is returning something.

Calling With Args and With Return Function in C Language
Calling No Arg and With Return Function in C Language

For better understanding please have a look at the below diagram. Suppose we are calling the function fun. Is it expecting anything?? No. Type is a void type. So, no need to pass anything to anyone but here it is expecting something i.e. it is returning 34.56 of float type. So, we should collect that into a variable of float type. Whether you are passing some values and someone is giving some output, we should collect that into a variable. But here we need to declare a variable of type depending upon the return type.

Calling No Arg and With Return Function in C Language
Summary:
Functions in C Programming Language
]]>
4032
Types of Variables in C Programming https://shishirkant.com/types-of-variables-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=types-of-variables-in-c-programming Sat, 05 Aug 2023 17:42:49 +0000 https://shishirkant.com/?p=4027 Types of Variables in C Language:

In this article, I am going to discuss the Types of Variables in C Language with Examples. Please read our previous article where we discussed the basics of C Language Variables. Based on the scope and lifetime of a variable, variables are categorized into three types. They are as follows

  1. Local variable
  2. Global variable
  3. Environment variable

Note: The Scope tells about the visibility (i.e., from where this variable is visible), whereas the lifetime tells about the durability (i.e. how much time the value in the variable is valid).

Local Variables in C Language:

The variables declared inside a function are known as local variables in C. The scope of local variables in C will be within the function only i.e. we can’t access a local variable from outside the function in which it is declared. These variables are declared within the function and can’t be accessed outside the function.

The lifetime of a local variable is throughout the function i.e. memory to the local variables allocated when the function execution started and will become invalid once the function completes its execution.

Example to Understand Local Variables in C Language:

In the following example, m and n variables are having scope within the main function only. These are not visible to the test function. Likewise, a and b variables are having scope within the test function only. These are not visible to the main function.

include <stdio.h>
void test ();
int main()
{
   int m = 22, n = 44; // m, n are local variables of main function 
   /*m and n variables are having scope within this main function only. These are not visible to test function.*/
   /* If you try to access a and b in this function, you will get 'a' undeclared and 'b' undeclared error */

   printf ("\n values : m = %d and n = %d", m, n);
   test();
}
void test()
{
   int a = 50, b = 80; // a, b are local variables of test function 
   /* a and b variables are having scope within this test function only. These are not visible to main function.*/
   /* If you try to access m and n in this function, you will get 'm' undeclared and 'n' undeclared error */
   printf ("\n values : a = %d and b = %d", a, b);
}

Output:

Local Variables in C Language
Global Variables in C Language:

The variables which are declared outside the function are known as global variables in C. The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program.

The lifetime of a global variable is throughout the program, i.e. memory to the global variables will be allocated when the execution of the program is started and will become invalid after finishing the execution of the program.

Example to Understand Global Variables in C:

In the following example, the variables a, b, m, and n are declared outside the scope of any function. So, these variables are visible to the main function and all other sub-functions.

#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
   printf("All variables are accessed from main function");
   printf("\n values: m=%d: n=%d: a=%d: b=%d", m, n, a, b);
   test();
}
void test()
{
   printf("\n\n All variables are accessed from" \ " test function");
   printf("\n values: m=%d: n=%d: a=%d: b=%d", m ,n, a, b);
}
Output:
Global Variables in C
Environment Variables in C Language:

The environment variable is a variable that will be available for all C applications and C programs. We can access these variables from anywhere in a C program without declaring and initializing in an application or C program.

The inbuilt functions which are used to access, modify, and set these environment variables are called environment functions. There are 3 functions that are used to access, modify, and assign an environment variable in C. They are,

1. setenv()
2. getenv()
3. putenv()

getenv() Function in C Language:

This function gets the current value of the environment variable. Let us assume that the environment variable DIR is assigned to “/usr/bin/test/”.

Example to understand getenv() Function in Language
#include <stdio.h>
#include <stdlib.h>
int main() 
{
   printf("Directory = %s\n", getenv("DIR"));
   return 0;
}
Output:
getenv() Function in C Language
setenv() Function in C Language:

This function sets the value for the environment variable. Let us assume that the environment variable “FILE” is to be assigned “/usr/bin/example.c”.

Example to understand setenv() Function in Language
#include <stdio.h>
#include <stdlib.h>
int main()
{
   setenv("FILE","/usr/bin/example.c",50);
   printf("File = %s\n", getenv("FILE"));
   return 0;
}

Output: File = /usr/bin/example.c

putenv() Function in C Language:

This function modifies the value of the environment variable. The below example program shows how to modify an existing environment variable value.

Example to understand putenv() Function in Language
#include <stdio.h>
#include <stdlib.h>
int main()
{
   setenv("DIR","/usr/bin/example/",50);
   printf("Directory name before modifying = " \ "%s\n", getenv("DIR"));
   putenv("DIR=/usr/home/");
   printf("Directory name after modifying = " \ "%s\n", getenv("DIR"));
   return 0;
}

Output:
Directory name before modifying = /usr/bin/example/
Directory name after modifying = /usr/home/

Interview Questions on Variables in C Programming Language:

Question 1: What will be the output of the below program
#include <stdio.h>
int main()
{
   printf("%d", number);
   int number;
   return 0;
}

Output: Compilation Error. This is because the scope of the local variable starts from the point where we declared. In the above example, we are trying to access the variable before we are declaring it.

Question 2: What will be the output of the below program?
#include <stdio.h>
int main()
{
   int number = 10;
   int number = 20;
   printf("%d", number);
   return 0;
}

Output: Compilation Error. This is because Multiple declarations of the local variables with the same name and in the same scope are not allowed. In the above example, we are trying to declare a Local variable with the same name more than once

Question 3: What will be the output of the below program?
#include <stdio.h>
int main()
{
   printf("%d", number);
   return 0;
}
int number = 10;

Output: undeclared variable error. This is because the scope of the global variable also starts from the point where it is declared. In the above example, we are declaring the Global variable after we are using it in the “main” function.

Question 4: What will be the output of the below program?
#include <stdio.h>
int number = 10;
number = 20;
int main()
{
   printf("%d", number);
   return 0;
}

Output: re-definition error. This is because the Re-definition of Global variables is not allowed in the C language. In the above example, we are trying to redefine the Global variable with number= 20.

Question 4: What will be the output of the below program?

#include <stdio.h>

int number1 = 10;

int number2 = number1 ;

int main()

{

printf(“%d”, number1);

return 0;

}

Output: Compilation Error. This is because we cannot assign directly one “Global variable” to another “Global variable” outside the function. In the above example, we are trying to assign the Global variable number1 to another Global variable number2

]]>
4027
Variables in C Programing https://shishirkant.com/variables-in-c-programing/?utm_source=rss&utm_medium=rss&utm_campaign=variables-in-c-programing Sat, 05 Aug 2023 17:33:29 +0000 https://shishirkant.com/?p=4024 Variables in C Language with Examples

In this article, I am going to give a brief introduction to Variables in C Language with Examples. Mainly we will discuss how to represent variables and how to declare variables in the c language. As we already discussed in our previous article, the main things to writing a C Program are variables and methods. The reason is that if two programs want to communicate what we are using is called methods. Generally, we can call it functionality or functions also. And in the process of communication, what the program is sharing is nothing but variables. So, at the end of this article, you will understand the following pointers in detail.

  1. What is a variable?
  2. How do represent variables in C?
  3. How to declare variables?
  4. How to access Variables in C?
Understanding Variables in C Language:

Generally, if we want to execute a program, why we are executing a program means to process the information or process the data. Take an example of a bank application, communication is there. They are executing one program or one transaction. While executing the transaction, they are processing the data like processing the account number, account name, balance, etc.

For every computer application, we must store the information at a particular location. Every machine has memory locations, and every memory location is identified by an address. Just consider in a classroom or in a theater the seating arrangement, just consider the seating arrangement as a memory location.

Every memory location is identified by an address. For a better understanding, please have a look at the below image. As you can see in the below image, 128, 572, 1024, 5098, etc. are one-one memory addresses. We can treat all the addresses are positive integer values.

Understanding Variables in C Language
What is the relation between variable and memory locations?

Generally, if we want to store some information, suppose I want to store a value of 10 in the memory locations. Just consider a classroom, there is no restriction on the students where they can sit. That means the students will go and sit randomly at different locations. In the same way, the value 10 that we want to store will also go and be stored randomly at a particular memory location. For a better understanding, please have a look at the below image.

What is the relation between variable and memory locations?
How to access the data?

Now, I want to access the data, and I just want to print that information. Then how can we print? How we can print the data means we will face the problems. The reason is, in which memory locations the data has been stored that we cannot understand because of a random memory location. So, here accessing becomes very difficult after storing the information. So, what we should do before storing information is first, we need to set the identity to the memory location.

How we can set Identity to Memory Locations?

Before storing the information, first, we need to set the identity to the memory location. The following is the syntax to declare a variable by setting the identity of the memory location in the c language. First, we need to write the data type followed by the identifier.

Syntax: data_type Identifier;

Example: int a; //Here integer is the data type and identifier can be any name and here we set it as a. So, whenever we declare a variable, it gets memory allocated. To one memory location, the identity is set as shown in the below image.

How we can set Identity to Memory Locations?

Here “a” is a named memory location to the location 10344. Later when we are storing an element into a location that is identified by the identifier “a” as follows.

a = 10; //Here, the value is 10 and we are setting this value into a memory location which is identified by “a” as shown in the below image.

Variables in C Language with Examples

For example, in theater, every seat is having some unique number and when you are coming you will sit in a particular seat that is allocated to you. Later if they want to access it, easily they can access it.

What is a Variable in C Language?

A name that is given for any computer memory location is called a variable name. The purpose of the variable is to store some data. The user will access it by the variable name and the compiler will access it by the address. C variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable. The value of the C variable may get a change in the program. C variable might be belonging to any of the data types like int, float, char, etc.

Note: In C Language, variables are the data objects which are used to store a value. These values can be then manipulated during the execution of the program. You must declare the variable before using it in your program.

Rules for variable declaration in C:
  1. A variable name must begin with a letter or underscore.
  2. Variables are case sensitive
  3. They can be constructed with digits and letters.
  4. No special symbols are allowed other than underscores.
  5. sum, height, _value are some examples of the variable name
Declaring and Initializing C variable:
  • Variables should be declared in the C program before use.
  • Memory space is not allocated for a variable while declaration. It happens only on the variable definitions.
  • Variable initialization means assigning a value to the variable.
How to Declare a Variable in C?

Declaration tells the compiler about the data type and size of the variable. Variable can be declared many times in a program. The variable declaration specifies the name and type of the variable. 

Syntaxdata_type variable_name;
Example: int x, y, z;

Here x, y, and z are variable names and ‘int‘ is the data type that specifies that x, y, and z can only store integer type values. In our next article, we will discuss DataTypes in detail.

When we declare a variable in C#, by default it stores some garbage value. Here, garbage value means an unexpected value (it might be zero also). So after the declaration, when we assign some value to the variable. It is called Variable Initialization. Let us see how to initialize a variable in C.

Defining a Variable in C:

When we declare a variable in C#, by default it stores some garbage value. Here, garbage value means an unexpected value (it might be zero also). So after the declaration, when we assign some value to the variable. It is called Variable Initialization.

Syntax: data_type variable_name;
              variable_name = value;
Example: int x, y;
                x = 50, y = 30;   //Here x is defined with a value 50 and y is defined with a value 30

Why do we get garbage value by default in C?

Let us understand this with an example. When we declare an integer variable in C, then 4 bytes of memory will be allocated for it. If there were already 0’s in those 4 bytes then there will be no problem, else if the 4 bytes contain info that we have used earlier then it will be garbage. so we need to clear it. It can be done by initializing the variable with 0.

Variable initialization in C:

Syntax: data_type variable_name = value;
Example: int x = 0;

Note: It is always a good programming practice to initialize a variable with zero after declaration.

]]>
4024
Unary Operators in C Programming https://shishirkant.com/unary-operators-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=unary-operators-in-c-programming Sat, 05 Aug 2023 17:29:28 +0000 https://shishirkant.com/?p=4021 Unary Operator in C Programming Language

In this article, we are going to discuss a very important topic in C language i.e. how to work with Unary Operators or you can say how to work with increment and decrement operators in the c programming language. Please read our previous article, where we discussed the basics of Operators in C Language. In most of the technical interview questions, they will ask a number of questions about unary operators. So, at the end of this article, you will understand everything about the unary operators in the c language.

Unary Operator in C Programming Language

Unary operator means an operator can perform operations on a single operand only. That means one operand is enough to perform the operation is called a unary operator. Unary operators are briefly classified into two types. They are as follows:

  1. Increment Operators: Increment Operators in C Language are again divided into two types i.e. pre-increment and post-increment.
  2. Decrement Operators: Decrement Operators in C Language are again divided into two types i.e. pre-decrement and post decrement.
How to use Unary Operators in C Programming Language?
  1. Pre increment: It is placed before the variable. For example, ++a will increase the value of the variable a by 1.
  2. Post increment: It is placed after the variable. For example, a++ will also increase the value of the variable a by 1.
  3. Pre decrement: It is placed before the variable. For example, –a will decrease the value of the variable a by 1.
  4. Post decrement: It is placed after the variable. For example, a– will also decrease the value of the variable a by 1.

For a better understanding of the types of Unary Operators and usage, please have a look at the following image.

How to use Unary Operators in C Programming Language?

Note: Increment Operator means to increment the value of the variable by 1 and Decrement Operator means to decrement the value of the variable by 1.

Now, the question is when should Pre-Increment and post-increment increases the value, and similarly when should Pre-decrement and post-decrement decreases the value. To understand this concept very clearly, we need to understand five simple steps. First, we will see the five steps and then based on these steps we will see some examples to understand this concept clearly.

Five Steps to Understand the Unary Operators in C Language:

If there is some pre-increment or pre decrement in the expression, that should execute first. The second step is to substitute the values in the expression. Once we substitute the values, in the third step we need to evaluate the expression. Followed by the Evaluation, an Assignment needs to be performed and the final step is post-increment or post decrement.

Five Steps to Understand the Unary Operators in C Language

Now, if you have any doubt about the above five steps, then don’t worry we will see some examples to understand this step in a better way.

Example: Pre-Increment

First, let us see a basic example that shows the basic difference between pre-increment and post-increment. Please have a look at the following program.

#include<stdio.h>
int main()
{
   int x = 10, y;
   y = ++x;
   printf("%d %d", x, y);
   return 0;

}

Let us understand the above program execution step by step by following the five steps. Here we are declaring two variables x=10 and y; First, the execution starts from the main method, and then the first statement executes i.e. int x = 10, y; Here, the variables x and y get memory allocation at some location, and variable x is initialized with a value of 10 and variable y will store some garbage value why because we are not initializing y variable and as it is a local variable so, by default, y is going to store some garbage value.

The next statement is expression evaluation and the statement is y = ++ x;. So, what is the first step? The first step is pre-increment and pre-decrement. Is there any pre-increment or pre-decrement in the expression? Yes, there is a pre-increment. So, execute the pre-increment i.e. ++x and this pre-increment will increase the variable x value by 1 and it becomes 11 and also this value is updated in the memory location of the x variable.

The next step is substitution. That is ++x will be substituted or replaced with 11. The third step is evaluation and, in our expression, there is nothing to evaluate, so ignore it. The fourth step is assignment i.e. assigning the value (11) to the left-hand side variable i.e. y. So, the garbage value stored initially in the y memory location will be replaced by 11. And the last step is post-increment and post-decrement. Is there any post-increment and post-decrement in the expression? No, so ignore it. So, five steps are completed means expression evaluation is completed.

In the next statement, we are printing the value of x and y and it will print 11 and 11. So, when you run the above program, you will get the output as 11 and 11. For a better understanding, please have a look at the below image.

Pre-Increment Operator Example in C Programming Language
Example: Post Increment

Consider the below program. This is the same as the previous example, the only difference here is that we use the post-increment operator i.e. y = x++; instead of pre-increment.

#include<stdio.h>
int main()
{
   int x = 10, y;
   y = x++;
   printf("%d %d", x, y);
   return 0;
}

Let us understand the above program execution step by step by following the same five steps as we followed in our previous example. Here we are also declaring two variables x=10 and y; Here, the variables x and y get memory allocation at some location and variable x is initialized with a value of 10 and variable y will store some garbage value.

The next statement is expression evaluation and the statement is y = x++, And we need to evaluate this expression using the same five steps. So, what is the first step? The first step is pre-increment and pre-decrement. Is there any pre-increment or pre-decrement in the expression? No, so, ignore the first step.

The next step is substitution. That is x++ will be substituted or replaced with 10. The third step is evaluation and, in our expression, there is nothing to evaluate, so ignore it. The fourth step is assignment i.e. assigning the value (10) to the left-hand side variable i.e. y. So, the garbage value stored initially in the y will be replaced by 10. And the last step is post-increment and post-decrement. Is there any post-increment and post-decrement in the expression? Yes, there is post-increment. So, execute the post-increment i.e. x++ and this post-increment will increase the variable x value by 1 and it becomes 11, also this value is updated in the memory location of the x variable. All five steps are completed. Yes, that means the expression evaluation is completed.

In the next statement, we are printing the value of x and y and it will print 11 and 10. So, when you run the above program, you will get the output as 11 and 10.

So, the simple difference between pre-increment/pre-decrement and post-increment/post-decrement is that pre-increment/pre-decrement execute first and post-increment/post-decrement execute last and that is the only difference.

Complex Examples of Increment and Decrement Operators in C Language:

Let us see some more complex examples to understand this concept. Please have a look at the following example. Here, we are declaring three variables x, y, and z, and then evaluating the expression as z = x++ * –y; finally, we are printing the value of x, y, and z in the console.

#include<stdio.h>
int main()
{
   int x = 10, y=20, z;
   z = x++ * --y;
   printf("%d %d %d", x, y, z);
   return 0;
}

Let us evaluate the expression z = x++ * –y; by following the 5 steps:

  1. The First step is pre-increment or pre-decrement. Is there any pre-increment or pre-decrement in the expression? There is no pre-increment but there is a pre-decrement in the expression i.e. –y. So, execute that pre-decrement which will decrease the value of y by 1 i.e. y becomes 19.
  2. The second step is substitution. So, substitute the values of x and y. That means x will be substituted by 10 and y will be substituted by 19.
  3. The third step is evaluation. So, evaluate the expression i.e. 10 * 19 = 190.
  4. The fourth step is the assignment. So, assign the evaluated value to the given variable i.e. 190 will be assigned to z. So, now the z value becomes 190.
  5. The last step is post-increment and post-decrement. Is there any post-increment or post-decrement in the expression? There is no post-decrement but there is a post-increment in the expression i.e. y++. So, execute that post-increment which will increase the value of x by 1 i.e. x becomes 11.

So, when you will execute the above program it will print the x, y, and z values as 11, 19, and 190 respectively. For, a better understanding, please have a look at the below image.

Complex Examples of Increment and Decrement Operators in C Language
Example:

#include<stdio.h>
int main()
{
   int x = 5;
   x = ++x + x++;
   printf("%d", x);
   return 0;

}

The expression x = ++x + x++; will be evaluated based on below 5 steps:

  1. The First step is pre-increment and pre-decrement. Is there any pre-increment or pre-decrement in the expression? There is no pre-decrement but there is a pre-increment in the expression i.e. ++x. So, execute that pre-increment which will decrease the value of x by 1 i.e. x becomes 6.
  2. The second step is substitution. So, substitute the values of x. That means x will be substituted by 6.
  3. The third step is evaluation. So, evaluate the expression i.e. 6 + 6 = 12.
  4. The fourth step is the assignment. So, assign the evaluated value to the given variable i.e. 12 will be assigned to x. So, now the x value becomes 12.
  5. The last step is post-increment and post-decrement. Is there any post-increment or post-decrement in the expression? There is no post-decrement but there is a post-increment in the expression i.e. x++. So, execute that post-increment which will increase the value of x by 1 i.e. x becomes 13.

So, when you will execute the above program, it will print the x value as 13. For a better understanding, please have a look at the below image.

Unary Operators in C Programming Language

Note: The pre-increment operator and the + operators have equal precedence. That means which one is done first is completely compiler-dependent. This is called undefined behavior and these types of statements should be avoided at all costs.

Example:

Consider the below example. Here, we are declaring two variables a and a, and initializing variables a and a with the values 2 and 3 respectively. Then we have three expressions to evaluate the value of a and b and finally, we are printing the value of a and b on the console.

#include<stdio.h>
int main()
{ 
  int a = 2, b = 3; 
  b = a++ + b--;
  a = a-- + ++b;
  b = ++a + --b;
  printf("%d %d", a, b);
  return 0;
}

All three expressions will be evaluated using the same 5 steps:

Expression1: b = a++ + b–;
  1. The First step is pre-increment and pre-decrement and there is no pre-increment and pre-decrement in the expression. So, ignore this step.
  2. The second step is substitution. So, substitute the values of a and b. That means a and b will be substituted by 2 and 3 respectively.
  3. The third step is evaluation. So, evaluate the expression i.e. 2 + 3 = 5.
  4. The fourth step is the assignment. So, assign the evaluated value to the given variable i.e. 5 will be assigned to b. So, now the b value becomes 5.
  5. The last step is post-increment and post-decrement. Is there any post-increment or post-decrement in the expression? Yes, both are present. So, execute the post-increment i.e. a++ and post-decrement i.e. b– which will increase the a value by 1 i.e. a becomes 3, and decrease the b value by 1 i.e. b becomes 4.

So, at the end of this expression, the latest a value is 3, and the b value is 4.

Expression2: a = a– + ++b;
  1. The First step is pre-increment and pre-decrement and there is one pre-increment in the expression i.e. ++b. So, execute the pre-increment which will increase the b value by 1 i.e. b becomes 5.
  2. The second step is substitution. So, substitute the values of a and b. That means a and b will be substituted by 3 and 5 respectively.
  3. The third step is evaluation. So, evaluate the expression i.e. 3 + 5 = 8.
  4. The fourth step is the assignment. So, assign the evaluated value to the given variable i.e. 8 will be assigned to a. So, now a value becomes 8.
  5. The last step is post-increment and post-decrement. Is there any post-increment or post-decrement in the expression? Yes, Post-decrement is there. So, execute the post-decrement i.e. a– which will decrease the a value by 1 i.e. a becomes 7.

So, at the end of this expression, the latest a value is 7, and the b value is 5.

Expression3: b = ++a + –b;
  1. The First step is pre-increment and pre-decrement and both pre-increment (++a) and pre-decrement (–b) is present in the expression. So, execute the pre-increment which will increase a value by 1 i.e. a becomes 8. Similarly, execute the pre-decrement which will decrease b value by 1 i.e. b becomes 4
  2. The second step is substitution. So, substitute the values of a and b. That means a and b will be substituted by 8 and 4 respectively.
  3. The third step is evaluation. So, evaluate the expression i.e. 8 + 4 = 12.
  4. The fourth step is the assignment. So, assign the evaluated value to the given variable i.e. 12 will be assigned to b. So, now the b value becomes 12.
  5. The last step is post-increment and post-decrement. Is there any post-increment or post-decrement in the expression? No, so ignore this step.

So, at the end of this expression, the latest a value is 8, and the b value is 12, and that you will see when you run the above program.

As already discussed, the pre-increment (++var) operator and the + operators have equal precedence. So, which operator will execute first will completely depend on the compiler. This is called undefined behavior and these types of statements should be avoided at all costs. So, when you execute the above program, based on your compiler you may get a different output.

Example:

Consider the below example.

#include<stdio.h>
int main()
{
  int a = 5;
  a = a+++a;
  printf("%d", a);
  return 0;
}

The Unary operator has a priority greater than the arithmetic operator, so the compiler will execute the unary operator first. The Compiler will give priority to the unary operator because it has higher priority, that is why we will get output as 11. For better understanding, please have a look at the below diagram.

Unary Operator in C Programming Language with examples
]]>
4021
Operators in C Programming https://shishirkant.com/operators-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=operators-in-c-programming Sat, 05 Aug 2023 17:23:32 +0000 https://shishirkant.com/?p=4018 Operators in C Language with Examples

In this article, I am going to discuss Operators in C Language with Examples. Please read our previous article, where we discussed the Constants in C program. As part of this article, you will learn what are Operators in C, their type, and when and how to use different types of Operators in the C Language with examples.

C Language Operators:

Operators in C Language are the special kind of symbols that performs certain operations on the data. The collection of operators along with the data or operands is known as expression. C language supports various types of operators but depends on the number of operands, operators are classified into 3 types:

  • Unary Operator
  • Binary Operator
  • Ternary Operator
C Language Operators

When we are evaluating any expression with input data we are passing on it is called operands, which symbol we are using is called operators.

Unary Operators in C Language:

Unary means consisting of a single component or element. A Unary Operator in C is an operator that takes a single operand in an expression or a statement. Here + & – operators will indicate the sign of operand like +5, -3, -45.

Types of Unary Operators are:

Increment operators (++): Example: (++x)
Decrement operators (–): Example: (–x)

Increment Operators in C Language:

Increment Operators is a unary operator. It takes one value at a time. It is classified into two types:

  • Post Increment Operator
  • Pre Increment Operator

Post Increment Operators are the operators that are a suffix to its variable. It uses the value present inside the variable. It increments the value present inside the variable by ‘1’ and updates it.

Syntax: Variable++;
Example: x++;

Pre Increment Operators are the operators which is a prefix to their variable. It increments the value present inside the variable by ‘1’ and updates it then it uses the value present inside the variable.

Syntax: ++Variable;
Example: ++x;

Program:
#include<stdio.h>

int main()

{

int x, y, z;

x = 5;

y = x++;

printf ("x: %d y: %d", x, y);

z = ++y;

printf ("y: %d z:%d", x, y);

}

Output:

Increment Operators in C Language
Steps to Follow:

First, take the memory block.

Types of Unary Operators in C Language

Write down the expression.
    y=x++;
    z=++y;
If the expression contains the post operator removes the post and writes down the expression again.
     y=x;
Then assign priority.
     y=x;
Finally, update the post values into variables (memory block).

Decrement Operators in C Language:

Decrement Operators is a unary operator. It takes one value at a time. It is classified into two types:

  • Post Decrement Operator
  • Pre Decrement Operator

Post Decrement Operators are the operators that are a suffix to its variable. It uses the value present inside the variable. It decrements the value present inside the variable by ‘1’ and updates it.

Syntax: Variable–;
Example: x–;

Pre Decrement Operators are the operators that are a prefix to their variable. It decrements the value present inside the variable by ‘1’ and updates it then it uses the value present inside the variable.

Syntax: –Variable;
Example: –x;

Example to understand Increment and Decrement Operators in C:
#include<stdio.h>
int main()
{
int x, y, z;
x=5;
y=x--;
printf("x: %d y: %d", x, y);
z=--y;
printf("y: %d z:%d", x, y);
}
Output:
Decrement Operators in C Language
Steps to Follow:

First, take the memory block.

Types of Unary Operators in C Language

Write down the expression.
    y=x–;
    z=–y;
If the expression contains a post operator removes the post and writes down the expression again.
    y=x;
Then assign priority.
    y=x;
Finally, update the post values into variables (memory block).

Binary Operators in C Language:

Types of Binary Operators are:

  1. Arithmetic operators
  2. Logical operators
  3. Relational operators
  4. Bit-wise operators
  5. Assignment operators
Arithmetic operators in C Language:

These operators are used to perform arithmetic/mathematical operation and give us results accordingly.

  1. + (Plus) – Give sum as a result. Example: 3+2=5
  2. – (Minus) – Give the difference as a result. Example: 4-2=2
  3. * (Asterisk) – Used for multiplication and given the product as a result. Example: 4*2=8
  4. / (Forward slash) – Used for division and give quotient as a result. Example: 4/2=2

% (modulus) – Give the remainder as a result. Example: 7%2=1

Example to understand Arithmetic Operators in C Language
#include<stdio.h>
int main()
{
int a = 11, b = 4; // Declare and initialize variable a and b
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b); // because both operands are integer result will be an integer
printf("a %% b = %d\n", a % b); // % operator returns the remainder of 11/4 i.e 3
// Signal to operating system everything works fine
return 0;
}
Output:
Arithmetic operators in C Language
Logical Operators in C Language:

Logical Operators are operators that determine the relation between 2 or more operands and return a specific output as a result of that relation. They had usually worked with Boolean (true/false) values.

NOT (!) – Used to negate a Boolean statement.
Example: NOT (!)
If A=1 and B=0, It is used to reverse the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.
!(A && B) is true.

AND (&&) and OR (||) – Used to combine simple relational statements into more complex Expressions.
Example: AND (&&)
If A=1 and B=0, If both the operands are non-zero, then the condition becomes true.
(A && B) is false.

Example: OR (||)
If A=1 and B=0, If any of the two operands are non-zero, then the condition becomes true.
(A || B) is true.

Example to understand the Logical Operators in C Language
#include <stdio.h>
int main()
{
 int a = 5;
 int b = 20;
int c;
if (a && b)
{
printf ("Line 1 - Condition is true\n");
}
if (a || b)
{
printf ("Line 2 - Condition is true\n");
}

/* lets change the value of a and b */
a = 0;
b = 10;
if (a && b)
{
printf ("Line 3 - Condition is true\n");
}
else
{
printf ("Line 3 - Condition is not true\n");
}
if (!(a && b))
{
printf ("Line 4 - Condition is true\n");
}
}

Output:

Logical Operators in C Language
Relational Operators in C Language:

These Operators are used to check the relationship between the two operands. If the relation is true, it returns 1; if the relation is false, it returns the value 0. Relational operators are used in decision-making and loops. Programming language like C which doesn’t support Boolean data type return result as 1 or 0. Here 1->True and 0->False. Following are the different types of relational operators supported in C Programming Language.

  1. Greater than (>) – Returns true when the left operand value is greater than the right operand value. Example: 5 > 3 is evaluated to 0.
  2. Less than (<) – Returns true when the left operand value is less than the right operand value. Example: 5 < 3 is evaluated to 0.
  3. Greater than or equal to (>=) – Return true when the left operand value is greater than or equal to the right operand. Example: 5 >= 3 is evaluated to 0.
  4. Less than or equal to (<=) – Return true when the left operand value is less than or equal to the right operand. Example: 5 <= 3 is evaluated to 0.
  5. Equal to (==): – Returns true when left operand value is equal to right operand value. Example: 5 == 3 is evaluated to 0.

Not Equal to (!=): – Return true when left operand value is not equal to right operand. Example: 5 != 3 is evaluated to 0.

Example to Demonstrate the Relational Operators in C Language
#include<stdio.h>
int main()
{
int x = 12, y = 13;
printf("x = %d\n", x);
printf("y = %d\n\n", y); // Is x is greater than y?
printf("x > y : %d\n", x > y); // Is x is greater than or equal to y?
printf("x >= y : %d\n", x >= y); // Is x is smaller than y?
printf("x < y : %d\n", x < y); // Is x is smaller than or equal to y?
printf("x <= y : %d\n", x <= y); // Is x is equal to y?
printf("x == y : %d\n", x == y); // Is x is not equal to y?
printf("x != y : %d\n", x != y); // Signal to operating system everything works fine
return 0;
}
Output:
Relational Operators in C Language
Bitwise Operators in C Language:

Bitwise Operators in C Programming Language are used for performing bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits. Bitwise operators always evaluate both operands. Bitwise operators work on bits and perform bit-by-bit operations. The following are the different types of bitwise operators supported in C Programming Langauge.

  1. & (AND): Example: a & b
  2. |(OR): Example: a | b
  3. ^(Exclusive OR (XOR)): Example: a ^ b
  4. ~(One’s Complement (NOT)): Example: ~a
  5. >> (Shift Right): Example: a >> 1
  6. << (Shift Left): Example: a << 1
Example to understand the Bitwise Operators in C Language:
#include<stdio.h>
int main( )
{
int a=9 , b=65;
printf("Bitwise AND Operator a & b =%d\n", a & b);
printf("Bitwise OR Operator a | b =%d\n", a | b);
printf("Bitwise XOR Operator a ^ b =%d\n", a ^ b);
printf("Bitwise NOT Operator ~a =%d\n", ~ a);
printf("SHIFT RIGHT Operator a >> 1 =%d\n", b >> 1);
printf("SHIFT LEFT Operator a << 1 =%d\n", a << 1);
return 0;
}
Output:
Bitwise Operators in C Language
Assignment Operators in C Language:

Assignment Operators in C Language are the operator which is used to assign a new value to a variable. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands. The following are the different types of Assignment Operators supported in C Language.

  1. = : Simple assignment operator. Assigns values from right side operands to left side operands. Example: C = A + B will assign the value of A + B to C
  2. += :Add AND assignment operator. It adds the right operand to the left operand and assigns the result to the left operand. Example: C += A is equivalent to C = C + A
  3. -+: Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. Example: C -= A is equivalent to C = C – A
  4. *=: Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. Example: C *= A is equivalent to C = C * A
  5. /= :Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. Example: C /= A is equivalent to C = C / A
  6. %=: Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. Example: C %= A is equivalent to C = C % A
Example to demonstrate Assignment Operators in C Language:
#include<stdio.h>
int main( )
{
int a=5, c;
c = a; // c is 5
printf(“c = %d \n” , c);
c += a; // c is 10
printf(“c = %d \n” , c);
c -= a; // c is 5
printf(“c = %d \n” , c);
c *= a; // c is 25
printf(“c = %d \n” , c);
c /= a; // c is 5
printf(“c = %d \n” , c);
c %= a; // c = 0
printf(“c = %d \n” , c);
return 0;
}
Output:
Assignment Operators in C Language
Ternary Operator or Conditional Operator in C Language:

This is an operator that takes three arguments. The first argument is a comparison argument, the second is the result of a true comparison, and the third is the result of a false comparison. If it helps you can think of the operator as a shortened way of writing an if-else statement.

?: Ternary or Conditional Operator. Example: (a>b)? c : d ;

(a>b) is a condition where if the condition is true the variable “c” in the operator which acts as an operand will be executed if not Operand “d” will be executed.

Example to Understand Ternary Operator in C Language:
#include <stdio.h>
main ()
{
int a, b;
a = 10;
printf ("Value of b is %d\n", (a == 1) ? 20 : 30);
printf ("Value of b is %d\n", (a == 10) ? 20 : 30);
}
Output:
Ternary Operator or Conditional Operator in C Language
]]>
4018