0% found this document useful (0 votes)
2 views

Unit-1(Programming in c Notes)

The document provides an overview of the character set in the C programming language, detailing its types, uses, and importance. It explains the ASCII character set, character representation, and the types of characters including alphabets, digits, special characters, and whitespace. Additionally, it covers character set conversion functions and includes sample C programs to print characters from the character set.

Uploaded by

Pat Rick
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit-1(Programming in c Notes)

The document provides an overview of the character set in the C programming language, detailing its types, uses, and importance. It explains the ASCII character set, character representation, and the types of characters including alphabets, digits, special characters, and whitespace. Additionally, it covers character set conversion functions and includes sample C programs to print characters from the character set.

Uploaded by

Pat Rick
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

UNIT-1

Introduction

In C programming language, a character set is defined as a set of characters that can be used to write
the source code. This blog will discuss the types and importance of character set in C, followed by
their conversion. Later we will also print all the characters in the C character set with the help of a C
program.

What is Character Set in C?

In C, a character set refers to a predefined collection of characters recognized by the language. This
set typically includes the alphabet (both lowercase and uppercase), digits, special symbols, and
control characters. The most commonly used character set in C is ASCII (American Standard Code for
Information Interchange), which assigns numeric codes to characters. These codes are used to
represent characters in memory and facilitate operations involving characters, such as input/output
operations, string manipulation, and comparison.

ASCII value Context

32 space

48-57 0-9

65-90 A-Z

97-122 a-z

Use of Character Set in C

It is used to specify the acceptable characters that can be inserted into the source code or
interpreted while the programme is executing.

In C, the character set is applied in the following ways:

 Character representation: The character set represents characters in the source programme.
The ASCII code 65, for instance, is used to represent the letter A.

 To represent special symbols: In the source programme, special symbols are represented by
the character set. For instance, addition in C is denoted by the symbol +.
 To create words and phrases: In the source programme, words and expressions are created
using the character set. For instance, the letters h, e, l, and o combine to make the word
hello.

 Types of Character set in C


C programming language supports four types of characters:

 Alphabets

 Digits

 Special characters

 White space

Alphabets

The C programming language allows for all upper- and lower-case alphabets in its programs.

Lower Case alphabets: a-z (26 characters)

Upper case alphabets: A-Z (26 characters)

Digits

The C programming language also supports digits for building numeric expressions.

Digits: 0-9 (10 characters)

Special Characters

Certain special characters are used in C programs in arithmetic expressions, punctuation marks,
conditional operators, etc. These characters can also be used in defining the attributes of a program
in a better way.

Special Characters: ` ~ @ ! $ # ^ * % & ( ) [ ] { } < > + = _ – | / \ ; : ‘ “ , . ?

White spaces

The white space characters in C refer to vertical and horizontal spaces in the source code.

White spaces: Blank Spaces, Tab, Carriage Return, New Line, horizontal tab, vertical tab, null

Special Characters in C

In C programming, special characters are often used to represent control characters or to format
output. Here are some commonly used special characters:

1. \n: Represents a newline character.

2. \t: Represents a tab character.

3. \b: Represents a backspace character.

4. \r: Represents a carriage return character.

5. \: Represents a backslash character.

6. ': Represents a single quote character.


7. ": Represents a double quote character.

The various character sets that can be used with the C language are shown in the following table:

Type of Character Description

Uppercase Alphabets A-Z (26 characters)

Lowercase Alphabets a-z (26 characters)

Digits 0-9 (10 characters)

White spaces Blank Spaces, Tab, Carriage Return, New Line, horizontal tab, vertical tab, null

Special Characters @!$#^*%&()[]{}<>+=_–|/\;:‘“,.?

Character set conversion in C

The conversion of a string or a character from one character set to another is called charset
conversion in C. This conversion is useful when the programmer works with data involving different
character sets while reading and writing text files.

The standard library offering functions for character set conversion in C are iconv(), wcstombs(),
mbstowcs(). While iconv() performs conversions between different character sets in C, wcstombs()
and mbstowcs() perform conversions between wide characters and multibyte character strings,
respectively,

These libraries make managing and performing operations on multilingual text data easier.

How to Print Characters of the C Charset

The programs below would help you print all the characters of the C charset.

C Program to print Characters from 0-9 using ASCII value


Code:

 C

#include <stdio.h>

int main()

int j;

printf("ASCII ==> character\n");

// loop to print all ASCII values from 48 to 57

for(int j = 48; j <= 57; j++)

// display the ASCII value to the corresponding j value


printf("%d ==> %c\n", j, j);

return 0;

Run Code

Output:

ASCII ==> character

48 ==> 0

49 ==> 1

50 ==> 2

51 ==> 3

52 ==> 4

53 ==> 5

54 ==> 6

55 ==> 7

56 ==> 8

57 ==> 9

C Program to print Characters from A-Z using ASCII value


Code:

 C

#include <stdio.h>

int main()

int j;

printf("ASCII ==> character\n");

// loop to print all ASCII values from 65 to 90

for(int j = 65; j <= 90; j++)

// display the ASCII value to the corresponding j value

printf("%d ==> %c\n", j, j);

return 0;
}

Run Code

Output:

ASCII ==> character

65 ==> A

66 ==> B

67 ==> C

68 ==> D

69 ==> E

70 ==> F

71 ==> G

72 ==> H

73 ==> I

74 ==> J

75 ==> K

76 ==> L

77 ==> M

78 ==> N

79 ==> O

80 ==> P

81 ==> Q

82 ==> R

83 ==> S

84 ==> T

85 ==> U

86 ==> V

87 ==> W

88 ==> X

89 ==> Y
90 ==> Z

C Program to print Characters from a-z using ASCII value


Code:

 C

#include <stdio.h>

int main()

int j;

printf("ASCII ==> character\n");

// loop to print all ASCII values from 97 to 122

for(int j = 97; j <= 122; j++)

// display the ASCII value to the corresponding j value

printf("%d ==> %c\n", j, j);

return 0;

You can also try this code with Online C Compiler

Run Code

Output:

ASCII ==> character

97 ==> a

98 ==> b

99 ==> c

100 ==> d

101 ==> e

102 ==> f

103 ==> g

104 ==> h

105 ==> i

106 ==> j
107 ==> k

108 ==> l

109 ==> m

110 ==> n

111 ==> o

112 ==> p

113 ==> q

114 ==> r

115 ==> s

116 ==> t

117 ==> u

118 ==> v

119 ==> w

120 ==> x

121 ==> y

122 ==> z

Importance of Character Set in C

The importance of the Character set in C are:

 Character set in C allows programmers to compose the program statements.

 The Character set in C supports different languages and scripts, thus allowing programmers
to work with multilingual text data.

 Character set conversion is very useful for reading and writing different text files.

 Communication between different networks involves dealing with different character sets.
Thus charset conversion plays an important part here for encoding and decoding purposes.

What is a special symbol in C?


In C programming, a special symbol refers to characters like +, -, *, /, =, etc., used
for arithmetic operations, assignment, or comparison.
What are the special characters?
Special characters in C include newline (\n), tab (\t), backslash (\), single quote ('),
double quote (") used for formatting and representing non-printable characters.
How to find special characters in a string in C?
To find special characters in a string in C, you can iterate through the string using a
loop and check each character against a list of special characters using conditional
statements or functions like isalpha() or isdigit().
Keywords in C

Keywords in C are reserved words that have predefined meanings and are part of the C language
syntax. These keywords cannot be used as variable names, function names, or any other identifiers
within the program except for their intended purpose. They are used to define the structure flow and
behavior of a C program.

The compiler recognizes a defined set of keywords in the C programming language. These keywords
have specialized purposes and play critical roles in establishing the logic and behavior of a program.
Here are some characteristics of C keywords:

o Reserved: The C language reserves keywords are those keywords that cannot be used as
identifiers in programs. Using a keyword as a variable name or other identifier will cause
a compilation error.

o Predefined Meaning: Each keyword has a specific meaning that is assigned by the C
language. These meanings are built into the C language's grammar and syntax and the
compiler interprets them accordingly.

o Specific Use: Keywords are designed for specific purposes and contexts within the C
language. They define control structures, data types, flow control, and other language
constructs. Attempting to use a keyword outside of its intended purpose will result in a
compilation error.

o Standardized: C language keywords are standardized across different compilers and


implementations. It ensures the consistency and portability of C programs across different
platforms and environments.

A list of 32 keywords in the c language is given below:

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

Here is a brief explanation of each keyword in the C language along with their syntax and an
example:

o auto: This keyword declares an automatic variable with a local scope.

Syntax:

It has the following syntax:


1. auto data_type variable_name;

Example:

1. auto int count;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. auto int count = 10;

5. printf("Count: %d\n", count);

6.

7. {

8. auto int count = 5;

9. printf("Inner Count: %d\n", count);

10. }

11.

12. printf("Count: %d\n", count);

13.

14. return 0;

15. }

Output:

Count: 10

Inner Count: 5

Count: 10

o break: It is used to terminate the execution of a loop or switch statement.

Syntax:

It has the following syntax:

1. break;

Code:

1. #include <stdio.h>
2.

3. int main() {

4. for (inti = 0; i< 10; i++) {

5. if (i == 5) {

6. break;

7. }

8. printf("%d ", i);

9. }

10.

11. return 0;

12. }

Output:

01234

o case: It is used in a switch statement to define different cases.

Syntax:

It has the following syntax:

1. case constant_expression:

Code:

1. #include <stdio.h>

2.

3. int main() {

4. int choice = 2;

5. switch (choice) {

6. case 1:

7. printf("You chose option 1.\n");

8. break;

9. case 2:

10. printf("You chose option 2.\n");

11. break;
12. default:

13. printf("Invalid choice.\n");

14. }

15.

16. return 0;

17. }

Output:

You chose option 2.

o char: This keyword is used to declare a character data type.

Syntax:

It has the following syntax:

1. char variable_name;

Example:

1. char grade = 'A';

Code:

1. #include <stdio.h>

2.

3. int main() {

4. char grade = 'A';

5. printf("Grade: %c\n", grade);

6.

7. return 0;

8. }

Output:

Grade: A

o const: It is used to declare constants, whose values cannot be modified.

Syntax:
It has the following syntax:

1. const data_type constant_name = value;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. constint MAX_SIZE = 100;

5. printf("Max Size: %d\n", MAX_SIZE);

6.

7. return 0;

8. }

Output:

Max Size: 100

o continue: It is used to skip the remaining statements in a loop and continue with the next
iteration.

Syntax:

It has the following syntax:

1. continue;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. for (inti = 0; i< 10; i++) {

5. if (i == 5) {

6. continue;

7. }

8. printf("%d ", i);

9. }
10.

11. return 0;

12. }

Output:

012346789

o default: It is used in a switch statement as the default case when no other cases match.

Syntax:

It has the following syntax:

1. efault:

Code:

1. #include <stdio.h>

2.

3. int main() {

4. int choice = 3;

5. switch (choice) {

6. case 1:

7. printf("You chose option 1.\n");

8. break;

9. case 2:

10. printf("You chose option 2.\n");

11. break;

12. default:

13. printf("Invalid choice.\n");

14. }

15.

16. return 0;

17. }

Output:
Invalid choice.ax: default:

o do: It is used to create a do-while loop, which executes a block of code repeatedly until
a condition is met.

Syntax:

It has the following syntax:

1. do {

2. // code to be executed

3. } while (condition);

Code:

1. #include <stdio.h>

2.

3. int main() {

4. inti = 0;

5. do {

6. printf("%d ", i);

7. i++;

8. } while (i< 5);

9.

10. return 0;

11. }

Output:

01234

o double: This keyword is used to declare a double-precision floating-point data type.

Syntax:

It has the following syntax:

1. double variable_name;

Example:

1. double pi = 3.14159;
-

Code:

1. #include <stdio.h>

2.

3. int main() {

4. double pi = 3.14159;

5. printf("Pi: %lf\n", pi);

6.

7. return 0;

8. }

Output:

Pi: 3.141590

o else: It is used in an if statement to specify the block of code to be executed when the
condition is false.

Syntax:

It has the following syntax:

1. if (condition) {

2. // code to be executed if the condition is true

3. } else {

4. // code to be executed if the condition is false

5. }

Code:

1. #include <stdio.h>

2.

3. int main() {

4. int age = 20;

5. if (age >= 18) {

6. printf("You are an adult.\n");

7. } else {
8. printf("You are not an adult.\n");

9. }

10.

11. return 0;

12. }

Output:

You are an adult.

o enum: It is used to define an enumeration, which is a set of named values.

Syntax:

It has the following syntax:

1. enum enum_name {

2. value1,

3. value2,

4. //...

5. };

Code:

1. #include <stdio.h>

2.

3. enum Days {

4. Monday,

5. Tuesday,

6. Wednesday,

7. Thursday,

8. Friday,

9. Saturday,

10. Sunday

11. };

12.

13. int main() {


14. enum Days today = Tuesday;

15. printf("Today is day number %d\n", today);

16.

17. return 0;

18. }

Output:

Today is day number 1

o extern: It is used to declare a variable or function that is defined in another file or external
to the current scope.

Syntax:

It has the following syntax:

1. extern data_type variable_name;

Code:

1. #include <stdio.h>

2.

3. extern int global_variable;

4.

5. int main() {

6. global_variable = 10;

7. printf("Global variable: %d\n", global_variable);

8.

9. return 0;

10. }

11.

12. int global_variable;

Output:

Global variable: 10

o float: This keyword is used to declare a single-precision floating-point data type.


Syntax:

It has the following syntax:

1. float variable_name;

Example:

1. float weight = 65.5;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. float weight = 65.5;

5. printf("Weight: %.2f\n", weight);

6.

7. return 0;

8. }

Output:

Weight: 65.50

o for: It is used to create a for loop, which repeatedly executes a block of code based on a
specified condition.

Syntax:

It has the following syntax:

1. for (initialization; condition; increment/decrement) {

2. // code to be executed

3. }

Example:

1. for (int i = 0; i< 5; i++) {

2. printf("%d ", i);

3. }
-

Code:

1. #include <stdio.h>

2.

3. int main() {

4. for (inti = 0; i< 5; i++) {

5. printf("%d ", i);

6. }

7. printf("\n");

8.

9. return 0;

10. }

Output:

01234

o goto: It is used to transfer control to a labeled statement within the same function.

Syntax:

It has the following syntax:

1. goto label_name;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. for (inti = 0; i< 10; i++) {

5. if (i == 5) {

6. goto end;

7. }

8. printf("%d ", i);

9. }

10.
11. end:

12. printf("Loop ended.\n");

13.

14. return 0;

15. }

Output:

01234

Loop ended.

o if: It is used to create an if statement to perform a certain action based on a condition.

Syntax:

It has the following syntax:

1. if (condition) {

2. // code to be executed if the condition is true

3. }

Code:

1. #include <stdio.h>

2.

3. int main() {

4. int x = 5;

5. if (x > 0) {

6. printf("x is a positive number.\n");

7. }

8.

9. return 0;

10. }

Output:

x is a positive number.

o int: This keyword is used to declare an integer data type.


Syntax:

It has the following syntax:

1. int variable_name;

Example:

1. int number = 10;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. int number = 10;

5. printf("Number: %d\n", number);

6.

7. return 0;

8. }

Output:

Number: 10

o long: This keyword is used to declare a long integer data type.

Syntax:

It has the following syntax:

1. long variable_name;

Example:

1. long population = 1000000;

Code:

1. #include <stdio.h>

2.

3. int main() {
4. long population = 1000000;

5. printf("Population: %ld\n", population);

6.

7. return 0;

8. }

Output:

Population: 1000000

o register: It is used to declare a register variable, which suggests the compiler to store the
variable in a register for faster access.

Syntax:

It has the following syntax:

1. register data_type variable_name;

Example:

1. register int x = 5;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. register intreg_var = 5;

5. printf("Register Variable: %d\n", reg_var);

6.

7. return 0;

8. }

Output:

Register Variable: 5

o return: It is used to exit a function and return a value (if any) to the calling code.

Syntax:
It has the following syntax:

1. return expression;

Code:

1. #include <stdio.h>

2.

3. int square(intnum) {

4. return num * num;

5. }

6.

7. intmain() {

8. int result = square(5);

9. printf("Square: %d\n", result);

10.

11. return 0;

12. }

Output:

Square: 25

o short: This keyword is used to declare a short integer data type.

Syntax:

It has the following syntax:

1. short variable_name;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. short temperature = -10;

5. printf("Temperature: %d\n", temperature);

6.
7. return 0;

8. }

Output:

Copy code

Temperature: -10

o signed: It is used to declare a signed data type, which can represent


both positive and negative values.

Syntax:

It has the following syntax:

1. signed data_type variable_name;

Example:

1. signed int balance = -100;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. signed int balance = -100;

5. printf("Balance: %d\n", balance);

6.

7. return 0;

8. }

Output:

Balance: -100

o sizeof: It is used to determine the size in bytes of a data type or variable.

Syntax:

It has the following syntax:

1. sizeof(data_type); or sizeof(variable);
-

Code:

1. #include <stdio.h>

2.

3. int main() {

4. int size = sizeof(int);

5. printf("Size of int: %d bytes\n", size);

6.

7. return 0;

8. }

Output:

Size of int: 4 bytes

o static: It is used to declare a variable or function that retains its value or scope even after the
block in which it is defined has exited.

Syntax:

It has the following syntax:

1. static data_type variable_name;

2. static return_type function_name(arguments);

Code:

1. #include <stdio.h>

2.

3. void increment() {

4. static int count = 0;

5. count++;

6. printf("Count: %d\n", count);

7. }

8.

9. int main() {

10. increment();
11. increment();

12.

13. return 0;

14. }

Output:

Count: 1

Count: 2

o struct: It is used to define a user-defined data type called a structure, which can
hold multiple variables of different data types.

Syntax:

It has the following syntax:

1. struct struct_name {

2. data_type member1;

3. data_type member2;

4. //...

5. };

Code:

1. #include <stdio.h>

2. #include <string.h>

3.

4. struct Person {

5. char name[20];

6. int age;

7. };

8.

9. int main() {

10. struct Person student;

11. strcpy(student.name, "John");

12. student.age = 20;


13. printf("Name: %s, Age: %d\n", student.name, student.age);

14.

15. return 0;

16. }

Output:

Name: John, Age: 20

o switch: It is used to create a switch statement, which allows multiple execution paths based
on different cases.

Syntax:

It has the following syntax:

1. switch (expression) {

2. case constant1:

3. // code to be executed if expression matches constant1

4. break;

5. case constant2:

6. // code to be executed if expression matches constant2

7. break;

8. //...

9. default:

10. // code to be executed if expression does not match any constant

11. }

Code:

1. #include <stdio.h>

2.

3. int main() {

4. int choice = 2;

5. switch (choice) {

6. case 1:

7. printf("You chose option 1.\n");


8. break;

9. case 2:

10. printf("You chose option 2.\n");

11. break;

12. default:

13. printf("Invalid choice.\n");

14. }

15.

16. return 0;

17. }

Output:

You chose option 2.

o typedef: It is used to create a new name (alias) for an existing data type.

Syntax:

It has the following syntax:

1. typedef existing_data_type new_data_type;

Code:

1. #include <stdio.h>

2.

3. typedef int marks;

4.

5. int main() {

6. marks math_marks = 95;

7. printf("Math Marks: %d\n", math_marks);

8.

9. return 0;

10. }

Code:
Math Marks: 95

o union: It is used to define a user-defined data type called a union, which can hold different
data types but only one member at a time.

Code:

1. #include <stdio.h>

2.

3. union Number {

4. int integer;

5. float floating_point;

6. };

7.

8. int main() {

9. union Number num;

10. num.integer = 10;

11. printf("Integer: %d\n", num.integer);

12.

13. return 0;

14. }

Output:

Integer: 10

o unsigned: It is used to declare an unsigned data type, which can represent only positive

Syntax:

It has the following syntax:

1. unsigned data_type variable_name;

Code:

1. #include <stdio.h>

2.

3. int main() {

4. unsigned int count = 100;


5. printf("Count: %u\n", count);

6.

7. return 0;

8. }

Output:

Count: 100

o void: This keyword is used to indicate the absence of a specific type or to define functions
that do not return a value.

Syntax:

It has the following syntax:

1. For function return type: void function_name(arguments);

2. As a data type: void variable_name;

Code:

1. #include <stdio.h>

2.

3. void printMessage() {

4. printf("Hello, World!\n");

5. }

6.

7. int main() {

8. printMessage();

9.

10. return 0;

11. }

Output:

Hello, World!

o volatile: It is used to declare a variable that can be modified externally and should not be
optimized by the compiler.

Syntax:
It has the following syntax:

1. volatile data_type variable_name;

Example:

1. volatile int sensor_reading;

2. // Access and modify the sensor_reading variable in an interrupt service routine

Code:

1. #include <stdio.h>

2.

3. int main() {

4. volatile int sensor_reading = 0;

5.

6. // Simulating sensor reading update

7. for (inti = 0; i< 10; i++) {

8. sensor_reading = i;

9. printf("Sensor Reading: %d\n", sensor_reading);

10. }

11.

12. return 0;

13. }

Output:

Sensor Reading: 0

Sensor Reading: 1

Sensor Reading: 2

Sensor Reading: 3

Sensor Reading: 4

Sensor Reading: 5

Sensor Reading: 6

Sensor Reading: 7
Sensor Reading: 8

Sensor Reading: 9

o while: It is used to create a while loop, which repeatedly executes a block of code based on
a specified condition.

Syntax:

It has the following syntax:

1. while (condition) {

2. // code to be executed

3. }

Code:

1. #include <stdio.h>

2.

3. int main() {

4. inti = 0;

5. while (i< 5) {

6. printf("%d ", i);

7. i++;

8. }

9. printf("\n");

10.

11. return 0;

12. }

Output:

01234

C Identifiers

C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase, lowercase
letters, underscore, digits, but the starting letter should be either an alphabet or an underscore. If
the identifier is not used in the external linkage, then it is called as an internal identifier. If the
identifier is used in the external linkage, then it is called as an external identifier.
We can say that an identifier is a collection of alphanumeric characters that begins either with an
alphabetical character or an underscore, which are used to represent various programming elements
such as variables, functions, arrays, structures, unions, labels, etc. There are 52 alphabetical
characters (uppercase and lowercase), underscore character, and ten numerical digits (0-9) that
represent the identifiers. There is a total of 63 alphanumerical characters that represent the
identifiers.

Rules for constructing C identifiers

o The first character of an identifier should be either an alphabet or an underscore, and then it
can be followed by any of the character, digit, or underscore.

o It should not begin with any numerical digit.

o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.

o Commas or blank spaces cannot be specified within an identifier.

o Keywords cannot be represented as an identifier.

o The length of the identifiers should not be more than 31 characters.

o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifiers

1. total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

1. 2sum (starts with a numerical digit)

2. int (reserved word)

3. char (reserved word)

4. m+n (special character, i.e., '+')

Types of identifiers

o Internal identifier

o External identifier

Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal identifier. The
internal identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier. The external
identifiers can be function names, global variables.
Differences between Keyword and Identifier

Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It can be written in both lowercase and uppercase


It must be written in a lowercase letter.
letters.

Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.

It is a combination of alphabetical characters. It is a combination of alphanumeric characters.

It does not contain the underscore character. It can contain the underscore character.

Let's understand through an example.

1. int main()

2. {

3. int a=10;

4. int A=20;

5. printf("Value of a is : %d",a);

6. printf("\nValue of A is :%d",A);

7. return 0;

8. }

Output

Value of a is : 10

Value of A is :20

The above output shows that the values of both the variables, 'a' and 'A' are different. Therefore, we
conclude that the identifiers are case sensitive.

Constants in C

In programming languages like C, constants are essential because they give you a mechanism to
store unchanging values that hold true throughout the course of the program. These numbers may
be used for several things, such as creating mathematical constants or giving variables set values.
We will discuss the idea of constants in C, their syntax, how to declare and use them and give
illustrated examples along with their anticipated results in this blog article. By the end of this article,
you'll have a firm grasp of constants and their importance in C programming.
A constant in C is a value that doesn't change as the program runs. Integers, floating-point numbers,
characters, and strings are just a few of the several types of constants that may be employed. When
a constant has a value, it cannot be changed, unlike variables. They may be utilized in various
operations and computations and serve as the program's representation of fixed values.

Advantages of C Constants:

There are several advantages of C Constants. Some main advantages of C Constants are as follows:

1. Programmers may use constants to provide names that have meaning to fixed numbers,
which makes the code simpler to comprehend and update.

2. Constants assist in avoiding the usage of magic numbers, which are hard-coded values, in the
code. Instead, constants offer named representations of such values, enhancing the code's
readability.

3. Constants are reusable throughout the program, allowing for constant values in various
locations and lowering the possibility of errors brought on by typos or inconsistent values.

4. Calculations or processes inside the program can be optimized by using certain constants,
such as mathematical or physical constants.

5. A constant is a value or variable that can't be changed in the program, for example: 10, 20,
'a', 3.4, "c programming", etc.

There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

2 ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword

2. #define preprocessor
1) C const keyword

The const keyword is used to define constant in C programming.

1. const float PI=3.14;

Now, the value of PI variable can't be changed.

1. #include<stdio.h>

2. int main(){

3. const float PI=3.14;

4. printf("The value of PI is: %f",PI);

5. return 0;

6. }

Output:

The value of PI is: 3.140000

If you try to change the the value of PI, it will render compile time error.

1. #include<stdio.h>

2. int main(){

3. const float PI=3.14;

4. PI=4.5;

5. printf("The value of PI is: %f",PI);

6. return 0;

7. }

Output:

Compile Time Error: Cannot modify a const object

2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define preprocessor
directive.

Types of constant:

There are different types of Constants in C. Some of them are as follows:

Decimal Constant
A whole number represented in base 10 is known as a decimal constant. It has digits that range
from 0 to 9. Declaring a decimal constant has a simple syntax that just requires the value to be
written.

Example:

1. #include <stdio.h>

2.

3. int main() {

4. int decimal = 42;

5. printf("The decimal constant is: %d\n", decimal);

6. return 0;

7. }

Output:

The decimal constant is: 42

Real or Floating-Point Constant:

A fractional component or exponentiation of a number is represented by a real or floating-point


constant. It can be expressed with a decimal point, the letter "E", or the symbol "e" in exponential or
decimal notation.

Example:

1. #include <stdio.h>

2.

3. int main() {

4. float real = 3.14;

5. printf("The real constant is: %f\n", real);

6. return 0;

7. }

Output:

The real constant is: 3.140000

Octal Constant:

A base 8 value is represented by an octal constant. It is prefixed with a '0' (zero) to show that it is an
octal constant and has digits ranging from 0 to 7.

Example:
1. #include <stdio.h>

2.

3. int main() {

4. int octal = 052; // Octal representation of decimal 42

5. printf("The octal constant is: %o\n", octal);

6. return 0;

7. }

Output:

The octal constant is: 52

Hexadecimal Constant:

A base-16 value is represented by a hexadecimal constant. It uses letters A to F (or a to f) and


numbers 0 to 9 to represent values from 10 to 15. It is prefixed with '0x' or '0X' to identify it as a
hexadecimal constant.

Example:

1. #include <stdio.h>

2.

3. int main() {

4. int hexadecimal = 0x2A; // Hexadecimal representation of decimal 42

5. printf("The hexadecimal constant is: %x\n", hexadecimal);

6. return 0;

7. }

Output:

The hexadecimal constant is: 2a

Character Constant

A character constant represents a single character that is enclosed in single quotes.

Example:

1. #include <stdio.h>

2.

3. int main() {

4. char character = 'A';


5. printf("The character constant is: %c\n", character);

6. return 0;

7. }

Output:

The character constant is: A

String Constant:

A series of characters wrapped in double quotes is represented by a string constant. It is a character


array that ends with the null character \0.

Example:

1. #include <stdio.h>

2.

3. int main() {

4. char string[] = "Hello, World!";

5. printf("The string constant is: %s\n", string);

6. return 0;

7. }

Output:

The string constant is: Hello, World!

Rules for constructing constants:

The creation of constants must follow specified guidelines. These guidelines specify the format that
constants of various kinds must follow in order for the compiler to accept them as legitimate. The
guidelines for creating constants in C are as follows:

Integer Constants:

1. The digits of an integer constant can range from 0 to 9.

2. A decimal point should not be present in an integer constant.

3. Positive or negative integer constants are also possible.

4. You can add a suffix to a constant's name to define its type. 'U' or 'u' stands for unsigned,
'L' or 'l' for long, or 'LL' or 'll' for long long.

Floating-Point Constants:

1. A decimal point, an exponent, or digits can all be found in floating-point constants.


2. Either exponential notation or decimal notation can be used to write them.

3. 'E' or 'e' can be used to denote an exponent.

4. You can add a suffix to a constant's name to define its type. For instance, "F" or "f" stands
for float and "L" or "l" for long double.

Octagonal Constants

1. Base 8 is used for writing octal constants.

2. They are made up of the numerals 0 through 7.

3. A '0' (zero) should come before any octal constants.

Hexadecimal Constants:

1. Constants in hexadecimal are expressed in base 16.

2. To represent numbers from 10 to 15, they are made up of numerals 0 to 9 and letters A to F
(or a to f).

3. Prefixing a hexadecimal constant with '0x' or '0X' is appropriate.

Character Constants:

1. Individual characters are represented as character constants when they are in single quotes.

2. A single letter or an escape sequence, such as "n" for newline or "t" for tab, can be used as
these characters.

String Constants:

1. A series of characters surrounded in double quotes is represented by string constants.

2. They are essentially character arrays that are closed with the null character "0".

Conclusion:

As a result of their representation of fixed values that don't change during the course of the
program, constants are crucial in C programming. By following the rules for making constants,
programmers may create reliable and practical representations of data in their programs.

By giving descriptive names to fixed values, minimizing the usage of "magic


numbers", and encouraging self-documenting code, constants improve the readability of code. By
offering a central area to edit constant values, facilitating simple modifications, and lowering the
possibility of mistakes, they also aid in the maintainability of the code.

As constants may be used and referenced several times throughout the program, using them in C
programs also increases code reuse. When utilizing the same value again, it assures consistency and
lessens the possibility of adding errors or mistakes.

Constants can also improve computations and processes, particularly when physical or mathematical
constants are involved. Programmers can create code that is more effective and optimized by
utilizing constants rather than hard-coding variables.

Variables in C
A variable is the name of the memory location. It is used to store information. Its value can be
altered and reused several times. It is a way to represent memory location through symbols so that it
can be easily identified.

Variables are key building elements of the C programming language used to store and modify data in
computer programs. A variable is a designated memory region that stores a specified data type
value. Each variable has a unique identifier, its name, and a data type describing the type of data it
may hold.

Syntax:

The syntax for defining a variable in C is as follows:

1. data_type variable_name;

Here,

o data_type: It represents the type of data the variable can hold. Examples of data types in C
include int (integer), float (a floating-point number), char (character), double (a double-
precision floating-point number),

o variable_name: It is the identifier for the variable, i.e., the name you give to the variable to
access its value later in the program. The variable name must follow specific rules, like
starting with a letter or underscore and consisting of letters, digits, and underscores.

For example, to declare the integer variable age:

1. int age;

It declares an integer variable named age without assigning it a specific value. Variables can also be
initialized at the time of declaration by assigning an initial value to them. For instance:

1. int count = 0;

Here, the variable count is declared an integer and initialized with 0.

Note: Variables should be defined before they are used within the program. The scope of a variable
determines where it is accessible. Variables declared inside a function or block are considered local
variables, while declared outside any function are considered global variables.

Syntax:

Let us see the syntax to declare a variable:

1. type variable_list;

An example of declaring the variable is given below:

1. int a;
2. float b;

3. char c;

Here, a, b, and c are variables. The int, float, and char are the data types.

We may also provide values while defining variables, as shown below:

1. int a=20,b=30;//declaring 2 variable of integer type

2. float f=20.9;

3. char c='A';

Rules for defining variables

In C, Variable names must follow a few rules to be valid. The following are the rules for naming
variables in C:

o Allowed Characters:

Variable names include letters ( uppercase and lowercase ), digits, and underscores. They must start
with a letter (uppercase or lowercase) or an underscore.

o Case Sensitivity:

C is a case-sensitive programming language. It means that uppercase and lowercase letters are
considered distinct.

For example, myVar, MyVar, and myvar are all considered different variable names.

o Keywords:

Variable names cannot be the same as C keywords (reserved words), as they have special meanings
in the language.

For example, you cannot use int, float, char, for, while, etc., as variable names.

o Length Limitation:

There is no standard limit for the length of variable names in C, but it's best to keep them reasonably
short and descriptive.

Some compilers may impose a maximum length for variable names.

o Spaces and Special Characters:

Variable names cannot contain spaces or special characters (such as !, @, #, $, %, ^, &, *, (, ), -, +, =,


[, ], {, }, |, \, /, <, >,., ?;, ', or ").

Underscores are the only allowed special characters in variable names.

o Reserved Identifiers:
While not strictly a rule, it is advisable to avoid specific patterns or identifiers common in libraries or
standard usage.

For example, variables starting with __ (double underscores) are typically reserved for system
or compiler-specific usage.

Valid examples of variable names:

1. int age;

2. float salary;

3. char _status;

4. double average_score;

5. int studentCount;

Invalid examples of variable names:

1. int 1stNumber; // Starts with a digit

2. float my-salary; // Contains a hyphen (-)

3. char int; // Same as a C keyword

4. int double; // Same as a C keyword

5. float my$var; // Contains an unsupported special character

Following these rules ensures that your variable names are valid and conform to the C language's
syntax and conventions. Choosing meaningful and descriptive names for variables is essential to
enhance the readability and maintainability of your code.

The three components of declaring a variable

Let us explain the three aspects of defining a variable: variable declaration, variable definition, and
variable initialization, along with examples.

1. Variable Declaration:

The process of telling the compiler about a variable's existence and data type is known as variable
declaration. It notifies the compiler that a variable with a specific name and data type will be used in
the program. Still, no memory for the variable is allocated at this moment. It is usually seen at the
start of a function or block before the variable is utilized.

The general syntax for variable declaration is

1. data_type variable_name;

Example of variable declaration:

1. #include <stdio.h>
2.

3. int main() {

4. // Variable declaration

5. int age;

6. float salary;

7. char initial;

8.

9. return 0;

10. }

2. Variable Definition:

The process of reserving memory space for the variable to keep its contents during program
execution is known as a variable definition. It is based on the data type and connects the variable
name with a particular memory address of sufficient size.

A variable in C can be declared and defined in the same statement, although they can also be
separated if necessary.

Example of variable definition:

1. #include <stdio.h>

2.

3. int main() {

4. // Variable definition

5. int age = 25;

6. float salary = 2500.5;

7. char initial = 'J';

8.

9. return 0;

10. }

3. Variable Initialization:

Variable declaration is the act of informing the compiler about the existence and data type of a
variable. It informs the compiler that a variable with a specific name and data type will be used in the
program, but that memory for the variable still needs to be allocated.
Not explicitly initialized variables will contain garbage/random data that may result in unexpected
program behavior.

Example of variable initialization:

1. #include <stdio.h>

2. int main() {

3. // Variable definition and initialization

4. int age = 25;

5. float salary = 2500.5;

6. char initial = 'J';

7. // Later in the program, you can change the value of the variable

8. age = 30;

9. salary = 3000.0;

10.

11. return 0;

12. }

In the example above, we have variable age, salary, and initial declarations. After that, we define
these variables and initialize them with initial values (e.g., age = 25). Later in the program, we can
modify the values of these variables (e.g., age = 30).

Types of Variables in C

There are many types of variables in c:

1. local variable

2. global variable

3. static variable

4. automatic variable

5. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

1. void function1(){

2. int x=10;//local variable

3. }
-

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called a global variable. Any function can
change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

1. int value=20;//global variable

2. void function1(){

3. int x=10;//local variable

4. }

Static Variable

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

1. void function1(){

2. int x=10;//local variable

3. static int y=10;//static variable

4. x=x+1;

5. y=y+1;

6. printf("%d,%d",x,y);

7. }

If you call this function many times, the local variable will print the same value for each function
call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in each function
call, e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that are declared inside the block, are automatic variables by default. We can
explicitly declare an automatic variable using auto keyword.

1. void main(){

2. int x=10;//local variable (also automatic)

3. auto int y=20;//automatic variable

4. }
-

External Variable

We can share a variable in multiple C source files by using an external variable. To declare an external
variable, you need to use extern keyword.

myfile.h

1. extern int x=10;//external variable (also global)

-program1.c

1. #include "myfile.h"

2. #include <stdio.h>

3. void printValue(){

4. printf("Global variable: %d", global_variable);

5. }

Conclusion:

Variables are critical components in C that store and manipulate data in the memory. They act
as named placeholders for memory regions, making identifying and retrieving stored data simple.
The syntax for creating a variable in C includes the following:

o Declaring the data type.

o Specifying the data that the variable may carry.

o Giving the variable a unique name.

Following specific rules, such as starting with a letter, underscore, and avoiding reserved keywords,
ensures valid variable names. Variables can be declared without initialization or assigned an initial
value at the time of declaration. Once the variable is declared, variables can be used throughout the
program to store and manipulate data. They can be reassigned with new values as needed during
program execution.

Data Types in C

A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767


signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

Int:

Integers are entire numbers without any fractional or decimal parts, and the int data type is used to
represent them.

It is frequently applied to variables that include values, such as counts, indices, or other numerical
numbers. The int data type may represent both positive and negative numbers because it is signed
by default.

An int takes up 4 bytes of memory on most devices, allowing it to store values between around -2
billion and +2 billion.

Char:

Individual characters are represented by the char data type. Typically used to hold ASCII or UTF-8
encoding scheme characters, such as letters, numbers, symbols, or commas. There are 256
characters that can be represented by a single char, which takes up one byte of memory. Characters
such as 'A', 'b', '5', or '$' are enclosed in single quotes.

Float:

To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.

The float type is usually used for variables that require very good precision but may not be very
precise. It can store values with an accuracy of about 6 decimal places and a range of about 3.4 x
1038 in 4 bytes of memory.

Double:

Use two data types to represent two floating integers. When additional precision is needed, such as
in scientific calculations or financial applications, it provides greater accuracy compared to float.

Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places, yields
larger values. C treats floating point numbers as doubles by default if no explicit type is supplied.

1. int age = 25;

2. char grade = 'A';

3. float temperature = 98.6;

4. double pi = 3.14159265359;

In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two variables for
the number pi.

Derived Data Type

Beyond the fundamental data types, C also supports derived data types, including arrays, pointers,
structures, and unions. These data types give programmers the ability to handle heterogeneous data,
directly modify memory, and build complicated data structures.

Array:

An array, a derived data type, lets you store a sequence of fixed-size elements of the same type. It
provides a mechanism for joining multiple targets of the same data under the same name.

The index is used to access the elements of the array, with a 0 index for the first entry. The size of the
array is fixed at declaration time and cannot be changed during program execution. The array
components are placed in adjacent memory regions.

Here is an example of declaring and utilizing an array:

1. #include <stdio.h>

2.

3. int main() {

4. int numbers[5]; // Declares an integer array with a size of 5 elements


5.

6. // Assign values to the array elements

7. numbers[0] = 10;

8. numbers[1] = 20;

9. numbers[2] = 30;

10. numbers[3] = 40;

11. numbers[4] = 50;

12.

13. // Display the values stored in the array

14. printf("Values in the array: ");

15. for (int i = 0; i < 5; i++) {

16. printf("%d ", numbers[i]);

17. }

18. printf("\n");

19.

20. return 0;

21. }

Output:

Values in the array: 10 20 30 40 50

Pointer:

A pointer is a derived data type that keeps track of another data type's memory address. When
a pointer is declared, the data type it refers to is stated first, and then the variable name is
preceded by an asterisk (*).

You can have incorrect access and change the value of variable using pointers by specifying the
memory address of the variable. Pointers are commonly used in tasks such as function pointers,
data structures, and dynamic memory allocation.

Here is an example of declaring and employing a pointer:

1. #include <stdio.h>

2.

3. int main() {

4. int num = 42; // An integer variable


5. int *ptr; // Declares a pointer to an integer

6.

7. ptr = # // Assigns the address of 'num' to the pointer

8.

9. // Accessing the value of 'num' using the pointer

10. printf("Value of num: %d\n", *ptr);

11.

12. return 0;

13. }

Output:

Value of num: 42

Structure:

A structure is a derived data type that enables the creation of composite data types by allowing the
grouping of many data types under a single name. It gives you the ability to create your own unique
data structures by fusing together variables of various sorts.

1. A structure's members or fields are used to refer to each variable within it.

2. Any data type, including different structures, can be a member of a structure.

3. A structure's members can be accessed by using the dot (.) operator.

A declaration and use of a structure is demonstrated here:

1. #include <stdio.h>

2. #include <string.h>

3. // Define a structure representing a person

4. struct Person {

5. char name[50];

6. int age;

7. float height;

8. };

9.

10. int main() {

11. // Declare a variable of type struct Person

12. struct Person person1;


13.

14. // Assign values to the structure members

15. strcpy(person1.name, "John Doe");

16. person1.age = 30;

17. person1.height = 1.8;

18.

19. // Accessing the structure members

20. printf("Name: %s\n", person1.name);

21. printf("Age: %d\n", person1.age);

22. printf("Height: %.2f\n", person1.height);

23.

24. return 0;

25. }

Output:

Name: John Doe

Age: 30

Height: 1.80

Union:

A derived data type called a union enables you to store various data types in the same memory
address. In contrast to structures, where each member has a separate memory space, members of a
union all share a single memory space. A value can only be held by one member of a union at any
given moment. When you need to represent many data types interchangeably, unions come in
handy. Like structures, you can access the members of a union by using the dot (.) operator.

Here is an example of a union being declared and used:

1. #include <stdio.h>

2. // Define a union representing a numeric value

3. union NumericValue {

4. int intValue;

5. float floatValue;

6. char stringValue[20];

7. };
8. int main() {

9. // Declare a variable of type union NumericValue

10. union NumericValue value;

11. // Assign a value to the union

12. value.intValue = 42;

13. // Accessing the union members

14. printf("Integer Value: %d\n", value.intValue);

15. // Assigning a different value to the union

16. value.floatValue = 3.14;

17. // Accessing the union members

18. printf("Float Value: %.2f\n", value.floatValue);

19.

20. return 0;

21. }

Output:

Integer Value: 42

Float Value: 3.14

Enumeration Data Type

A set of named constants or enumerators that represent a collection of connected values can be
defined in C using the enumeration data type (enum). Enumerations give you the means to give
names that make sense to a group of integral values, which makes your code easier to read and
maintain.

Here is an example of how to define and use an enumeration in C:

1. #include <stdio.h>

2.

3. // Define an enumeration for days of the week

4. enum DaysOfWeek {

5. Monday,

6. Tuesday,

7. Wednesday,

8. Thursday,
9. Friday,

10. Saturday,

11. Sunday

12. };

13.

14. int main() {

15. // Declare a variable of type enum DaysOfWeek

16. enum DaysOfWeek today;

17.

18. // Assign a value from the enumeration

19. today = Wednesday;

20.

21. // Accessing the enumeration value

22. printf("Today is %d\n", today);

23.

24. return 0;

25. }

Output:

Today is 2

Void Data Type

The void data type in the C language is used to denote the lack of a particular type.

C Expressions

An expression is a formula in which operands are linked to each other by the use of operators to
compute a value. An operand can be a function reference, a variable, an array element or a constant.

Let's see an example:

1. a-b;

In the above expression, minus character (-) is an operator, and a, and b are the two operands.

There are four types of expressions exist in C:

o Arithmetic expressions
o Relational expressions

o Logical expressions

o Conditional expressions

Each type of expression takes certain types of operands and uses a specific set of operators.
Evaluation of a particular expression produces a specific value.

For example:

1. x = 9/2 + a-b;

The entire above line is a statement, not an expression. The portion after the equal is an expression.

Arithmetic Expressions

An arithmetic expression is an expression that consists of operands and arithmetic operators. An


arithmetic expression computes a value of type int, float or double.

When an expression contains only integral operands, then it is known as pure integer expression
when it contains only real operands, it is known as pure real expression, and when it contains both
integral and real operands, it is known as mixed mode expression.

Evaluation of Arithmetic Expressions

The expressions are evaluated by performing one operation at a time. The precedence and
associativity of operators decide the order of the evaluation of individual operations.

When individual operations are performed, the following cases can be happened:

o When both the operands are of type integer, then arithmetic will be performed, and the
result of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the
fractional part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the result
of the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.

o If one operand is of type integer and another operand is of type real, then the mixed
arithmetic will be performed. In this case, the first operand is converted into a real operand,
and then arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0
as the first value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.

Let's understand through an example.

6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.

6*2/8 + 8 * 2 8 is divided by 4, giving value 2.

12/8 +8 * 2 6 is multiplied by 2, giving value 12.

1+8*2 12 is divided by 8, giving value 1.

1 + 16 8 is multiplied by 2, giving value 16.

17 1 is added to 16, giving value 17.

Relational Expressions

o A relational expression is an expression used to compare two operands.

o It is a condition which is used to decide whether the action should be taken or not.

o In relational expressions, a numeric value cannot be compared with the string value.

o The result of the relational expression can be either zero or non-zero value. Here, the zero
value is equivalent to a false and non-zero value is equivalent to true.

Relational Expression Description


This condition is used to check whether the x is an even
number or not. The relational expression results in
x%2 = = 0
value 1 if x is an even number otherwise results in value
0.

It is used to check whether a is not equal to b. This


a!=b relational expression results in 1 if a is not equal to b
otherwise 0.

It is used to check whether the expression "a+b" is


a+b = = x+y
equal to the expression "x+y".

It is used to check whether the value of a is greater


a>=9
than or equal to 9.

Let's see a simple example:

1. #include <stdio.h>

2. int main()

3. {

4.

5. int x=4;

6. if(x%2==0)

7. {

8. printf("The number x is even");

9. }

10. else

11. printf("The number x is not even");

12. return 0;

13. }

Output
Logical Expressions

o A logical expression is an expression that computes either a zero or non-zero value.

o It is a complex test condition to take a decision.

Let's see some example of the logical expressions.

Logical Expressions Description

It is a test condition to check whether the x is greater


( x > 4 ) && ( x < 6 ) than 4 and x is less than 6. The result of the condition is
true only when both the conditions are true.

It is a test condition used to check whether x is greater


than 10 or y is less than 11. The result of the test
x > 10 || y <11
condition is true if either of the conditions holds true
value.

It is a test condition used to check whether x is not


! ( x > 10 ) && ( y = = 2 ) greater than 10 and y is equal to 2. The result of the
condition is true if both the conditions are true.

Let's see a simple program of "&&" operator.

1. #include <stdio.h>

2. int main()

3. {

4. int x = 4;

5. int y = 10;

6. if ( (x <10) && (y>5))

7. {
8. printf("Condition is true");

9. }

10. else

11. printf("Condition is false");

12. return 0;

13. }

Output

Let's see a simple example of "| |" operator

1. #include <stdio.h>

2. int main()

3. {

4. int x = 4;

5. int y = 9;

6. if ( (x <6) || (y>10))

7. {

8. printf("Condition is true");

9. }

10. else

11. printf("Condition is false");

12. return 0;

13. }

-
Output

Conditional Expressions

o A conditional expression is an expression that returns 1 if the condition is true otherwise 0.

o A conditional operator is also known as a ternary operator.

The Syntax of Conditional operator

Suppose exp1, exp2 and exp3 are three expressions.

exp1 ? exp2 : exp3

The above expression is a conditional expression which is evaluated on the basis of the value of the
exp1 expression. If the condition of the expression exp1 holds true, then the final conditional
expression is represented by exp2 otherwise represented by exp3.

Let's understand through a simple example.

1. #include<stdio.h>

2. #include<string.h>

3. int main()

4. {

5. int age = 25;

6. char status;

7. status = (age>22) ? 'M': 'U';

8. if(status == 'M')

9. printf("Married");

10. else

11. printf("Unmarried");

12. return 0;

13. }

Output
C Operators

An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

o Arithmetic Operators

o Relational Operators

o Shift Operators

o Logical Operators

o Bitwise Operators

o Ternary or Conditional Operators

o Assignment Operator

o Misc Operator

Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to left.

Let's understand the precedence by the example given below:

1. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive
operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity


Postfix () [] ->. ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Arithmetic Operators:

Arithmetic operators carry out fundamental mathematical operations. The arithmetic operators in C
are as follows:

Addition Operator (+): The addition operator adds two operands together.

Syntax:

It has the following syntax:

1. result = operand1 + operand2;

-
Example:

1. int a = 5;

2. int b = 3;

3. int result = a + b;

Output:

result = 8

Subtraction Operator (-): The second operand is subtracted from the first operand via
the subtraction operator.

Syntax:

It has the following syntax:

1. result = operand1 - operand2;

Example:

1. int a = 8;

2. int b = 3;

3. int result = a - b;

Output:

result = 5

Multiplication Operator (*): This operator is used to multiply the two operands.

Syntax:

It has the following syntax:

1. result = operand1 * operand2;

Example:

1. int a = 4;

2. int b = 5;

3. int result = a * b;

Output:
result = 20

Division Operator (/): The first operand and the second operand are divided using the division
operator.

Syntax:

It has the following syntax:

1. result = operand1 / operand2;

Example:

1. int a = 10;

2. int b = 2;

3. int result = a / b;

Output:

result = 5

Modulus Operator (%): The modulus operator determines the remainder of the division between
two operands.

Syntax:

It has the following syntax:

1. result = operand1 % operand2;

Example:

1. int a = 10;

2. int b = 3;

3. int result = a % b;

Output:

result = 1

Relational Operators:

Relational operators assess the relationship between values by comparing them. They return
either true (1) or false (0). The relational operators in C are as follows:

Equality Operator (==): If two operands are equal, the equality operator verifies this.

Syntax:
It has the following syntax:

1. result = operand1 == operand2;

Example:

1. int a = 5;

2. int b = 5;

3. int result = a == b;

Output:

result=1 (true)

Inequality Operator (!=): The inequality operator determines whether two operands
are equal or not.

Syntax:

It has the following syntax:

1. result = operand1 != operand2;

Example:

1. int a = 5;

2. int b = 3;

3. int result = a != b;

Output:

result=1 (true)

Greater than Operator (>): The greater than operator determines if the first operand exceeds the
second operand.

Syntax:

It has the following syntax:

1. result = operand1 > operand2;

Example:

1. int a = 7;

2. int b = 4;
3. int result = a > b;

Output:

result=1 (true)

Less than Operator (<): The less-than operator determines if the first operand less is than the
second operand.

Syntax:

It has the following syntax:

1. result = operand1 < operand2;

Example:

1. int a = 2;

2. int b = 6;

3. int result = a < b;

Output:

result=1 (true)

Greater than or Equal to Operator (>=): The greater than or equal to operator determines if the first
operand is more than or equal to the second operand.

Syntax:

It has the following syntax:

1. result = operand1 >= operand2;

Example:

1. int a = 5;

2. int b = 5;

3. int result = a >= b;

Output:

result=1 (true)

Less than or Equal To Operator (<=): The less than or equal to operator determines if the first
operand must be less than or equal to the second operand.
Syntax:

It has the following syntax:

1. result = operand1 <= operand2;

Example:

1. int a = 3;

2. int b = 6;

3. int result = a <= b;

Output:

result=1 (true)

Shift Operators:

A binary number's bits can be moved to the left or right using shift operators. The C shift workers are
listed below:

Left Shift Operator (<<): The left shift operator moves the bits of the first operand to the left by the
number of places indicated by the second argument.

Syntax:

It has the following syntax:

1. result = operand1 << operand2;

Example:

1. unsigned int a = 5; // 0000 0101 in binary

2. int result = a << 2;

Output:

result = 20 // 0001 0100 in binary

Right Shift Operator (>>): The right shift operator shifts the bits of the first operand to the right by
the number of positions specified by the second operand.

Syntax:

It has the following syntax:

1. result = operand1 >> operand2;

-
Example:

1. unsigned int a = 20; // 0001 0100 in binary

2. int result = a >> 2;

Output:

result = 5 // 0000 0101 in binary

Logical Operators:

Logical operators perform logical operations on boolean values and return either true (1) or false
(0). Here are the logical operators in C:

Logical AND Operator (&&): The logical AND operator returns true if both operands are true.

Syntax:

It has the following syntax:

1. result = operand1 && operand2;

Example:

1. int a = 5;

2. int b = 3;

3. int result = (a > 3) && (b < 5);

Output:

result = 1 (true)

Logical OR Operator (||): The logical OR operator returns true if at least one of the operands is true.

Syntax:

It has the following syntax:

1. result = operand1 || operand2;

Example:

1. int a = 5;

2. int b = 3;

3. int result = (a > 3) || (b > 5);

-
Output:

result = 1 (true)

Logical NOT Operator (!): The logical NOT operator negates the value of the operand.

Syntax:

It has the following syntax:

1. result = !operand;

Example:

1. int a = 5;

2. int result = !(a > 3);

Output:

result = 0 (false)

Bitwise Operators:

Bitwise operators perform operations on individual bits of the operands. Here are the bitwise
operators in C:

Bitwise AND Operator (&): The bitwise AND operator performs a bitwise AND operation on the
corresponding bits of the operands.

Syntax:

It has the following syntax:

1. result = operand1 & operand2;

Example:

1. unsigned int a = 5; // 0000 0101 in binary

2. unsigned int b = 3; // 0000 0011 in binary

3. int result = a & b;

Output:

result = 1 // 0000 0001 in binary

Bitwise OR Operator (|): The bitwise OR operator performs a bitwise OR operation on the
corresponding bits of the operands.

Syntax:
It has the following syntax:

1. result = operand1 | operand2;

Example:

1. unsigned int a = 5; // 0000 0101 in binary

2. unsigned int b = 3; // 0000 0011 in binary

3. int result = a | b;

Output:

result = 7 // 0000 0111 in binary

Bitwise XOR Operator (^): The bitwise XOR operator performs a bitwise exclusive OR operation on
the corresponding bits of the operands.

Syntax:

It has the following syntax:

1. result = operand1 ^ operand2;

Example:

1. unsigned int a = 5; // 0000 0101 in binary

2. unsigned int b = 3; // 0000 0011 in binary

3. int result = a ^ b;

Output:

result = 6 // 0000 0110 in binary

Bitwise NOT Operator (~): The bitwise NOT operator flips each bit of the operand.

Syntax:

It has the following syntax:

1. result = ~operand;

Example:

1. unsigned int a = 5; // 0000 0101 in binary

2. int result = ~a;


-

Output:

result = -6 // 1111 1001 in binary (assuming 8-bit representation)

Ternary or Conditional Operator: The ternary or conditional operator allows you to assign a value
based on a condition.

Syntax:

It has the following syntax:

1. result = condition ? value1 : value2;

Example:

1. int a = 5;

2. int b = 3;

3. int result = (a > b) ? a : b;

Output:

result = 5

Assignment Operator:

Assignment operators are used to assign values to variables. Here is some of the assignment
operator in C:

Simple Assignment Operator (=): The simple assignment operator assigns the value from
the right side operands to the left side operands.

Syntax:

It has the following syntax:

1. variable = value;

Example:

1. int a;

2. a = 5;

Output:

No output. The value 5 is assigned to variable 'a'.

Miscellaneous Operator:
The sizeof operator and the comma operator fall under the miscellaneous operator category.

sizeof Operator: The sizeof operator returns the size, in bytes, of a variable or a data type.

Syntax:

It has the following syntax:

1. result = sizeof(variable / data type);

Example:

1. int a;

2. int size = sizeof(a);

Output:

size = 4 // Assuming int occupies 4 bytes

Comma Operator (,): The comma operator evaluates multiple expressions and returns the value of
the last expression.

Syntax:

It has the following syntax:

1. makefileCopy code

2. result = (expression1, expression2,..., expressionN);

Example:

1. int a = 5, b = 3;

2. int result = (a += 2, b *= 2, a + b);

Output:

result = 15 // a = 7, b = 6, a + b = 13

Uses of Operators:

The following are some common uses for the various kinds of operators in C:

o Calculations in fundamental mathematics are performed using the addition and subtraction
operators (+ and -).

o If the user wants to do some multiplication and division operations, utilize the multiplication
and division operators (* and /).

o The remainder of a division operation is obtained using the modulus operator (%).
o Equality and inequality operators (== and!=) are needed to compare values and determine
whether they are equal or not.

o Use the greater than and less than operators (>and <) to compare values and determine if
one value is larger than or less than

o A value's relationship to another value may be determined using the larger than or equal
to and less than or equal to operators (>= and <=).

o A binary number's bits are shifted to the left using the left shift operator (<<).

o A binary number's bits can be shifted to the right using the right shift operator (>>).

o Use the logical AND operator (&&) to combine many criteria and determine if each
condition is true.

o When combining several criteria, the logical OR operator (||) is used to determine if at least
one of the conditions is true.

o The logical NOT operator (!) is used to negate a condition's value.

o When two numbers' individual bits are involved, the bitwise AND operator (&) is utilized to
accomplish the action.

o The bitwise OR operator (|) is employed when two numbers' individual bits are involved.

o Bitwise exclusive OR operator is performed on individual bits of two integers using


the bitwise XOR operator ().

o Use the bitwise NOT operator () to flip or invert the bits of an integer.

o Use the ternary operator (?:) to assign a value depending on a condition in a compact form.

o A value is assigned to a variable using the simple assignment operator (=).

o The sizeof operator is used to calculate a variable's or data type's size in bytes.

o When evaluating several expressions, the comma operator (,) returns the result of the last
expression that was evaluated.

Increment and Decrement Operators in C

Last Updated : 28 Aug, 2023

The increment ( ++ ) and decrement ( — ) operators in C are unary operators for incrementing and
decrementing the numeric values by 1 respectively. The incrementation and decrementation are one
of the most frequently used operations in programming for looping, array traversal, pointer
arithmetic, and many more.

In this article, we will discuss the increment operator and decrement operator, both their prefix and
postfix applications, and the difference between them.
Increment Operator in C

The increment operator ( ++ ) is used to increment the value of a variable in an expression by 1. It


can be used on variables of the numeric type such as integer, float, character, pointers, etc.

Syntax of Increment Operator

Increment Operator can be used in two ways which are as follows:

// AS PREFIX

++m

// AS POSTFIX

m++

where m is variable.

How to use the increment operator?

Both pre-increment and post-increment increase the value of the variable but there is a little
difference in how they work.

1. Pre-Increment

In pre-increment, the increment operator is used as the prefix. Also known as prefix increment, the
value is incremented first according to the precedence and then the less priority operations are
done.

Example

result = ++var1;

The above expression can be expanded as

var = var + 1;

result = var;

2. Post-Increment

In post-increment, the increment operator is used as the suffix of the operand. The increment
operation is performed after all the other operations are done. It is also known as postfix increment.

Example

result = var1++;

The above expression is equivalent

result = var;
var = var + 1;

Example of Increment Operator

 C

// C Program to illustrate the increment of both type

#include <stdio.h>

void increment()

int a = 5;

int b = 5;

// PREFIX

int prefix = ++a;

printf("Prefix Increment: %d\n", prefix);

// POSTFIX

int postfix = b++;

printf("Postfix Increment: %d", postfix);

// Driver code

int main()

increment();

return 0;

Output

Prefix Increment: 6
Postfix Increment: 5

As we can see in postfix, the value is incremented after the assignment operator is done.

Note: The post-increment have higher precedence that pre-increment as it is postfix operator while
pre-increment comes in unary operator category.

Decrement Operator in C

The decrement operator is used to decrement the value of a variable in an expression. In the Pre-
Decrement, the value is first decremented and then used inside the expression. Whereas in the Post-
Decrement, the value is first used inside the expression and then decremented.

Syntax

Just like the increment operator, the decrement operator can also be used in two ways:

// AS PREFIX

--m

// AS POSTFIX

m--

where m is variable.

1. Pre-Decrement Operator

The pre-decrement operator decreases the value of the variable immediately when encountered. It
is also known as prefix decrement as the decrement operator is used as the prefix of the operand.

Example

result = --m;

which can be expanded to

m = m - 1;

result = m;

2. Post-Decrement Operator

The post-decrement happens when the decrement operator is used as the suffix of the variable. In
this case, the decrement operation is performed after all the other operators are evaluated.

Example

result = m--;
The above expression can be expanded as

result = m;

m = m-1;

Example of Decrement Operator

 C

// C program to illustrate the decrement operator of both

// types

#include <stdio.h>

void decrement()

int a = 5;

int b = 5;

// PREFIX

int prefix = --a;

printf("Prefix = %d\n", prefix);

// POSTFIX

int postfix = b--;

printf("Postfix = %d", postfix);

// Driver code

int main()

decrement();

return 0;
}

Output

Prefix = 4

Postfix = 5

Differences between Increment And Decrement Operators

The following table list the difference between the increment and decrement operators:

Increment Operator Decrement Operator

Decrement Operator subtracts 1 from the


Increment Operator adds 1 to the operand.
operand.

The Postfix increment operator means the The Postfix decrement operator means the
expression is evaluated first using the original expression is evaluated first using the original
value of the variable and then the variable is value of the variable and then the variable is
incremented(increased).The decremented(decreased).

Prefix decrement operator means the


Prefix increment operator means the variable is
variable is decremented first and then the
incremented first and then the expression is
expression is evaluated using the new value
evaluated using the new value of the variable.
of the variable.

Generally, we use this in decision-making and This is also used in decision-making and
looping. looping.

Special operators:

Comma Operator

The comma operator is utilized to evaluate multiple expressions and return the value of the last
expression.

Syntax:

The syntax of the comma operator is as follows:

1. expression1, expression2, ..., expressionN;

-
Example:

Here's an example that demonstrates how to use the comma operator to increment two variables:

1. #include <stdio.h>

2.

3. int main() {

4. int a = 2, b = 3;

5.

6. a++, b++;

7.

8. printf("a = %d, b = %d\n", a, b);

9.

10. return 0;

11. }

Output

a = 3, b = 4

Explanation:

In this example, the comma operator is used to increment the values of a and b by one. The
expressions a++ and b++ are evaluated from left to right, and the value of the last expression (b++) is
returned.

Moreover, special operators can also help in enhancing the code performance by decreasing the
number of lines of code and improving its readability. For instance, using the ternary operator
instead of an if-else statement can make the code shorter and easier to understand. Similarly, the
use of bitwise operators can lead to faster execution times when working with large sets of binary
data.

It is important to understand the syntax and functionality of these special operators to use them
effectively. By using them correctly, programmers can simplify their code and make it more efficient.
Special operators are a powerful tool in the arsenal of any C programmer, and their mastery can
greatly improve one's programming skills.

Math Functions in C:

Trigonometry, exponentiation, logarithms, rounding, and other mathematical operations are


available in the Cs math library. These approaches are more suited for complex calculations than
simple arithmetic programming. The header file <math.h> offers methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor(), etc.

C Math Functions:
There are various math methods.h header file. The commonly used functions of math.h header files
are given below.

Here are some examples of common math function categories in C:

No. Function Description

rounds up the given number. It


returns the integer value which is
1) ceil(number)
greater than or equal to given
number.

rounds down the given number. It


2) floor(number) returns the integer value which is
less than or equal to given number.

returns the square root of given


3) sqrt(number)
number.

4) pow(base, exponent) returns the power of given number.

returns the absolute value of given


5) abs(number)
number.

C Math Example

Let's see a simple example of math functions found in math.h header file.

1. #include<stdio.h>

2. #include <math.h>

3. int main(){

4. printf("\n%f",ceil(3.6));

5. printf("\n%f",ceil(3.3));

6. printf("\n%f",floor(3.6));

7. printf("\n%f",floor(3.2));

8. printf("\n%f",sqrt(16));

9. printf("\n%f",sqrt(7));

10. printf("\n%f",pow(2,4));

11. printf("\n%f",pow(3,3));

12. printf("\n%d",abs(-12));
13. return 0;

14. }

15. </math.h></stdio.h>

Output:

4.000000

4.000000

3.000000

3.000000

4.000000

2.645751

16.000000

27.000000

12

Trigonometric Functions:

The trigonometric functions are also used in the math function. The sine, cosine, and tangent of an
angle are calculated using the functions sin(), cos(), and sin().

Other known mathematical functions besides trigonometric functions are:

o exp(): returns a number's exponential value (ex).

o log() calculates a number's natural logarithm (base e).

o log10() computes a number's common logarithm (base 10).

o pow() raises a number to a given power.

Rounding Functions:

Following are some rounding functions that used in math function:

o ceil() rounds a number up to the nearest integer.

o floor () reduces a number to the nearest integer.

o round() returns the nearest integer to a floating-point number.

Other Mathematical Functions:

Following are some other mathematical functions that used in math function:

o sqrt() calculates the square root of a number.

o fabs() returns the absolute value of a number.


o fmod() calculates the remainder of the division between two numbers.

<math.h> Header:

If you want to utilize these arithmetic functions in your C application, include the <math.h>
header at the start of your source code. The header file provides the function prototypes and the
math function definitions. You can use the following directive to incorporate the math. In your C
application, include the following header: h>

1. #include <math.h>

After including this header, you can utilize the math functions in your program as necessary.

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {

5. double x = 2.0;

6. double result = sqrt(x);

7. printf("The square root of %.2f is %.2f\n", x, result);

8. return 0;

9. }

10. </math.h></stdio.h>

Output:

The square root of 2.00 is 1.41

Explanation:

In this example, the <math.h> header lets you use the sqrt() function to calculate the square root of
a value.

Note: Remember the potential precision difficulties in floating-point computations while working
with math functions that generate floating-point numbers.

1. sqrt() - Square Root Function

sqrt() function determines an integer's square root.

Example:

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

3.

4. int main() {

5. double x = 25.0;

6. double result = sqrt(x);

7. printf("The square root of %.2f is %.2f\n", x, result);

8. return 0;

9. }

10. </math.h></stdio.h>

Output:

The square root of 25.00 is 5.00

2. pow() - Exponential Power Function

The pow() function raises a number to a given power.

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {

5. double base = 2.0;

6. double exponent = 3.0;

7. double result = pow(base, exponent);

8. printf("%.2f raised to the power of %.2f is %.2f\n", base, exponent, result);

9. return 0;

10. }

11. </math.h></stdio.h>

Output:

2.00 raised to the power of 3.00 is 8.00

3. sin(), cos(), and tan() - Trigonometric Function

These formulas calculate an angle's sine,cosine, and tangent in radians.


Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {

5. double angle = 1.0; // in radians

6. double sin_val = sin(angle);

7. double cos_val = cos(angle);

8. double tan_val = tan(angle);

9.

10. printf("For angle %.2f:\n", angle);

11. printf("Sine: %.2f\n", sin_val);

12. printf("Cosine: %.2f\n", cos_val);

13. printf("Tangent: %.2f\n", tan_val);

14.

15. return 0;

16. }

17. </math.h></stdio.h>

Output:

For angle 1.00:

Sine: 0.84

Cosine: 0.54

Tangent: 1.56

4. exp() - Exponential Function

The exp() function determines the number's exponential value (ex).

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {
5. double x = 2.0;

6. double result = exp(x);

7. printf("e raised to the power of %.2f is %.2f\n", x, result);

8. return 0;

9. }

10. </math.h></stdio.h>

Output:

e raised to the power of 2.00 is 7.39

5. log() and log10() - Logarithmic Functions

The log() function calculates the natural logarithm (base e) of a number, while log10() calculates
the common logarithm (base 10).

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {

5. double x = 100.0;

6. double natural_log = log(x);

7. double common_log = log10(x);

8.

9. printf("Natural logarithm of %.2f is %.2f\n", x, natural_log);

10. printf("Common logarithm of %.2f is %.2f\n", x, common_log);

11. return 0;

12. }

13. </math.h></stdio.h>

Output:

Natural logarithm of 100.00 is 4.61

Common logarithm of 100.00 is 2.00

6. ceil() and floor() - Rounding Functions


The ceil() function rounds a number up to the nearest integer, while floor() rounds it down.

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {

5. double x = 3.7;

6. double y = -2.3;

7.

8. printf("Ceil of %.2f is %.2f\n", x, ceil(x));

9. printf("Floor of %.2f is %.2f\n", x, floor(x));

10.

11. printf("Ceil of %.2f is %.2f\n", y, ceil(y));

12. printf("Floor of %.2f is %.2f\n", y, floor(y));

13.

14. return 0;

15. }

16. </math.h></stdio.h>

Output:

Ceil of 3.70 is 4.00

Floor of 3.70 is 3.00

Ceil of -2.30 is -2.00

Floor of -2.30 is -3.00

7. fabs() - Absolute Value Function

The fabs() function returns the absolute value of a given number, which is its distance from zero.

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {
5. double x = -5.0;

6. double result = fabs(x);

7. printf("The absolute value of %.2f is %.2f\n", x, result);

8. return 0;

9. }

10. </math.h></stdio.h>

Output:

The absolute value of -5.00 is 5.00

8. fmod() - Remainder Calculation Function

The remaining value of a two-number division is calculated using the fmod() function.

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {

5. double dividend = 10.0;

6. double divisor = 3.0;

7. double remainder = fmod(dividend, divisor);

8. printf("The remainder of %.2f divided by %.2f is %.2f\n", dividend, divisor, remainder);

9. return 0;

10. }

11. </math.h></stdio.h>

Output:

The remainder of 10.00 divided by 3.00 is 1.00

9. sinh() and cosh() - Hyperbolic Sine and Cosine Functions

A given integer hyperbolic sine or cosine can be calculated using the sinh() and cosh() functions.

Example:

1. #include <stdio.h>

2. #include <math.h>
3.

4. int main() {

5. double x = 2.0;

6. double sinh_val = sinh(x);

7. double cosh_val = cosh(x);

8.

9. printf("Hyperbolic sine of %.2f is %.2f\n", x, sinh_val);

10. printf("Hyperbolic cosine of %.2f is %.2f\n", x, cosh_val);

11.

12. return 0;

13. }

14. </math.h></stdio.h>

Output:

Hyperbolic sine of 2.00 is 3.63

Hyperbolic cosine of 2.00 is 3.76

10. atan2() - Arc Tangent Function (2 Arguments)

Considering both of the arguments' signs, the atan2() function calculates the arctangent of the
quotient of its two inputs.

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {

5. double x = 1.0;

6. double y = 1.0;

7. double result = atan2(y, x);

8. printf("The arctangent of y=%.2f and x=%.2f is %.2f radians\n", y, x, result);

9. return 0;

10. }

11. </math.h></stdio.h>
-

Output:

The arctangent of y=1.00 and x=1.00 is 0.79 radians

11. round() - Rounding to Nearest Integer

When given a floating-point number, the round() function returns the closest integer.

Example:

1. #include <stdio.h>

2. #include <math.h>

3.

4. int main() {

5. double x = 3.6;

6. double y = 3.3;

7.

8. printf("Rounded value of %.2f is %.2f\n", x, round(x));

9. printf("Rounded value of %.2f is %.2f\n", y, round(y));

10.

11. return 0;

12. }

13. </math.h></stdio.h>

Output:

Rounded value of 3.60 is 4.00

Rounded value of 3.30 is 3.00

You might also like