Unit-1(Programming in c Notes)
Unit-1(Programming in c Notes)
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.
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.
32 space
48-57 0-9
65-90 A-Z
97-122 a-z
It is used to specify the acceptable characters that can be inserted into the source code or
interpreted while the programme is executing.
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.
Alphabets
Digits
Special characters
White space
Alphabets
The C programming language allows for all upper- and lower-case alphabets in its programs.
Digits
The C programming language also supports digits for building numeric expressions.
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.
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:
The various character sets that can be used with the C language are shown in the following table:
White spaces Blank Spaces, Tab, Carriage Return, New Line, horizontal tab, vertical tab, null
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.
The programs below would help you print all the characters of the C charset.
C
#include <stdio.h>
int main()
int j;
return 0;
Run Code
Output:
48 ==> 0
49 ==> 1
50 ==> 2
51 ==> 3
52 ==> 4
53 ==> 5
54 ==> 6
55 ==> 7
56 ==> 8
57 ==> 9
C
#include <stdio.h>
int main()
int j;
return 0;
}
Run Code
Output:
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
#include <stdio.h>
int main()
int j;
return 0;
Run Code
Output:
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
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.
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.
Here is a brief explanation of each keyword in the C language along with their syntax and an
example:
Syntax:
Example:
Code:
1. #include <stdio.h>
2.
3. int main() {
6.
7. {
10. }
11.
13.
14. return 0;
15. }
Output:
Count: 10
Inner Count: 5
Count: 10
Syntax:
1. break;
Code:
1. #include <stdio.h>
2.
3. int main() {
5. if (i == 5) {
6. break;
7. }
9. }
10.
11. return 0;
12. }
Output:
01234
Syntax:
1. case constant_expression:
Code:
1. #include <stdio.h>
2.
3. int main() {
4. int choice = 2;
5. switch (choice) {
6. case 1:
8. break;
9. case 2:
11. break;
12. default:
14. }
15.
16. return 0;
17. }
Output:
Syntax:
1. char variable_name;
Example:
Code:
1. #include <stdio.h>
2.
3. int main() {
6.
7. return 0;
8. }
Output:
Grade: A
Syntax:
It has the following syntax:
Code:
1. #include <stdio.h>
2.
3. int main() {
6.
7. return 0;
8. }
Output:
o continue: It is used to skip the remaining statements in a loop and continue with the next
iteration.
Syntax:
1. continue;
Code:
1. #include <stdio.h>
2.
3. int main() {
5. if (i == 5) {
6. continue;
7. }
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:
1. efault:
Code:
1. #include <stdio.h>
2.
3. int main() {
4. int choice = 3;
5. switch (choice) {
6. case 1:
8. break;
9. case 2:
11. break;
12. default:
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:
1. do {
2. // code to be executed
3. } while (condition);
Code:
1. #include <stdio.h>
2.
3. int main() {
4. inti = 0;
5. do {
7. i++;
9.
10. return 0;
11. }
Output:
01234
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;
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:
1. if (condition) {
3. } else {
5. }
Code:
1. #include <stdio.h>
2.
3. int main() {
7. } else {
8. printf("You are not an adult.\n");
9. }
10.
11. return 0;
12. }
Output:
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.
16.
17. return 0;
18. }
Output:
o extern: It is used to declare a variable or function that is defined in another file or external
to the current scope.
Syntax:
Code:
1. #include <stdio.h>
2.
4.
5. int main() {
6. global_variable = 10;
8.
9. return 0;
10. }
11.
Output:
Global variable: 10
1. float variable_name;
Example:
Code:
1. #include <stdio.h>
2.
3. int main() {
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:
2. // code to be executed
3. }
Example:
3. }
-
Code:
1. #include <stdio.h>
2.
3. int main() {
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:
1. goto label_name;
Code:
1. #include <stdio.h>
2.
3. int main() {
5. if (i == 5) {
6. goto end;
7. }
9. }
10.
11. end:
13.
14. return 0;
15. }
Output:
01234
Loop ended.
Syntax:
1. if (condition) {
3. }
Code:
1. #include <stdio.h>
2.
3. int main() {
4. int x = 5;
5. if (x > 0) {
7. }
8.
9. return 0;
10. }
Output:
x is a positive number.
1. int variable_name;
Example:
Code:
1. #include <stdio.h>
2.
3. int main() {
6.
7. return 0;
8. }
Output:
Number: 10
Syntax:
1. long variable_name;
Example:
Code:
1. #include <stdio.h>
2.
3. int main() {
4. long population = 1000000;
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:
Example:
1. register int x = 5;
Code:
1. #include <stdio.h>
2.
3. int main() {
4. register intreg_var = 5;
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) {
5. }
6.
7. intmain() {
10.
11. return 0;
12. }
Output:
Square: 25
Syntax:
1. short variable_name;
Code:
1. #include <stdio.h>
2.
3. int main() {
6.
7. return 0;
8. }
Output:
Copy code
Temperature: -10
Syntax:
Example:
Code:
1. #include <stdio.h>
2.
3. int main() {
6.
7. return 0;
8. }
Output:
Balance: -100
Syntax:
1. sizeof(data_type); or sizeof(variable);
-
Code:
1. #include <stdio.h>
2.
3. int main() {
6.
7. return 0;
8. }
Output:
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:
Code:
1. #include <stdio.h>
2.
3. void increment() {
5. 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:
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() {
14.
15. return 0;
16. }
Output:
o switch: It is used to create a switch statement, which allows multiple execution paths based
on different cases.
Syntax:
1. switch (expression) {
2. case constant1:
4. break;
5. case constant2:
7. break;
8. //...
9. default:
11. }
Code:
1. #include <stdio.h>
2.
3. int main() {
4. int choice = 2;
5. switch (choice) {
6. case 1:
9. case 2:
11. break;
12. default:
14. }
15.
16. return 0;
17. }
Output:
o typedef: It is used to create a new name (alias) for an existing data type.
Syntax:
Code:
1. #include <stdio.h>
2.
4.
5. int main() {
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() {
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:
Code:
1. #include <stdio.h>
2.
3. int main() {
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:
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:
Example:
Code:
1. #include <stdio.h>
2.
3. int main() {
5.
8. sensor_reading = i;
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:
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) {
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.
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 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.
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
Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.
It does not contain the underscore character. It can contain the underscore character.
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.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
1) C const keyword
1. #include<stdio.h>
2. int main(){
5. return 0;
6. }
Output:
If you try to change the the value of PI, it will render compile time error.
1. #include<stdio.h>
2. int main(){
4. PI=4.5;
6. return 0;
7. }
Output:
2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define preprocessor
directive.
Types of constant:
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() {
6. return 0;
7. }
Output:
Example:
1. #include <stdio.h>
2.
3. int main() {
6. return 0;
7. }
Output:
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() {
6. return 0;
7. }
Output:
Hexadecimal Constant:
Example:
1. #include <stdio.h>
2.
3. int main() {
6. return 0;
7. }
Output:
Character Constant
Example:
1. #include <stdio.h>
2.
3. int main() {
6. return 0;
7. }
Output:
String Constant:
Example:
1. #include <stdio.h>
2.
3. int main() {
6. return 0;
7. }
Output:
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:
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:
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
Hexadecimal Constants:
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).
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:
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.
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:
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.
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;
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:
1. type variable_list;
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.
2. float f=20.9;
3. char c='A';
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.
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.
1. int age;
2. float salary;
3. char _status;
4. double average_score;
5. int studentCount;
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.
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.
1. data_type variable_name;
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.
1. #include <stdio.h>
2.
3. int main() {
4. // Variable definition
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.
1. #include <stdio.h>
2. int main() {
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
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.
1. void function1(){
3. }
-
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.
2. void function1(){
4. }
Static Variable
A variable that is declared with the static keyword is called static variable.
1. void function1(){
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(){
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
-program1.c
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
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:
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.
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.
float 4 byte
double 8 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.
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.
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.
1. #include <stdio.h>
2.
3. int main() {
7. numbers[0] = 10;
8. numbers[1] = 20;
9. numbers[2] = 30;
12.
17. }
18. printf("\n");
19.
20. return 0;
21. }
Output:
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.
1. #include <stdio.h>
2.
3. int main() {
6.
8.
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.
1. #include <stdio.h>
2. #include <string.h>
4. struct Person {
5. char name[50];
6. int age;
7. float height;
8. };
9.
18.
23.
24. return 0;
25. }
Output:
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.
1. #include <stdio.h>
3. union NumericValue {
4. int intValue;
5. float floatValue;
6. char stringValue[20];
7. };
8. int main() {
19.
20. return 0;
21. }
Output:
Integer Value: 42
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.
1. #include <stdio.h>
2.
4. enum DaysOfWeek {
5. Monday,
6. Tuesday,
7. Wednesday,
8. Thursday,
9. Friday,
10. Saturday,
11. Sunday
12. };
13.
17.
20.
23.
24. return 0;
25. }
Output:
Today is 2
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.
1. a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
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
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.
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.
Relational Expressions
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.
1. #include <stdio.h>
2. int main()
3. {
4.
5. int x=4;
6. if(x%2==0)
7. {
9. }
10. else
12. return 0;
13. }
Output
Logical Expressions
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 10;
7. {
8. printf("Condition is true");
9. }
10. else
12. return 0;
13. }
Output
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
12. return 0;
13. }
-
Output
Conditional Expressions
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.
1. #include<stdio.h>
2. #include<string.h>
3. int main()
4. {
6. char status;
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 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.
1. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive
operator).
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:
-
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:
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:
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:
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:
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:
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:
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:
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:
Example:
1. int a = 2;
2. int b = 6;
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:
Example:
1. int a = 5;
2. int b = 5;
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:
Example:
1. int a = 3;
2. int b = 6;
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:
Example:
Output:
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:
-
Example:
Output:
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:
Example:
1. int a = 5;
2. int b = 3;
Output:
result = 1 (true)
Logical OR Operator (||): The logical OR operator returns true if at least one of the operands is true.
Syntax:
Example:
1. int a = 5;
2. int b = 3;
-
Output:
result = 1 (true)
Logical NOT Operator (!): The logical NOT operator negates the value of the operand.
Syntax:
1. result = !operand;
Example:
1. int a = 5;
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:
Example:
Output:
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:
Example:
3. int result = a | b;
Output:
Bitwise XOR Operator (^): The bitwise XOR operator performs a bitwise exclusive OR operation on
the corresponding bits of the operands.
Syntax:
Example:
3. int result = a ^ b;
Output:
Bitwise NOT Operator (~): The bitwise NOT operator flips each bit of the operand.
Syntax:
1. result = ~operand;
Example:
Output:
Ternary or Conditional Operator: The ternary or conditional operator allows you to assign a value
based on a condition.
Syntax:
Example:
1. int a = 5;
2. int b = 3;
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:
1. variable = value;
Example:
1. int a;
2. a = 5;
Output:
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:
Example:
1. int a;
Output:
Comma Operator (,): The comma operator evaluates multiple expressions and returns the value of
the last expression.
Syntax:
1. makefileCopy code
Example:
1. int a = 5, b = 3;
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 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 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 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.
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
// AS PREFIX
++m
// AS POSTFIX
m++
where m is variable.
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;
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++;
result = var;
var = var + 1;
C
#include <stdio.h>
void increment()
int a = 5;
int b = 5;
// PREFIX
// 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;
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;
C
// types
#include <stdio.h>
void decrement()
int a = 5;
int b = 5;
// PREFIX
// POSTFIX
// Driver code
int main()
decrement();
return 0;
}
Output
Prefix = 4
Postfix = 5
The following table list the difference between the increment and decrement operators:
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).
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:
-
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.
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:
C Math Functions:
There are various math methods.h header file. The commonly used functions of math.h header files
are given below.
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().
Rounding Functions:
Following are some other mathematical functions that used in math function:
<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;
8. return 0;
9. }
10. </math.h></stdio.h>
Output:
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.
Example:
1. #include <stdio.h>
2. #include <math.h>
3.
4. int main() {
5. double x = 25.0;
8. return 0;
9. }
10. </math.h></stdio.h>
Output:
Example:
1. #include <stdio.h>
2. #include <math.h>
3.
4. int main() {
9. return 0;
10. }
11. </math.h></stdio.h>
Output:
1. #include <stdio.h>
2. #include <math.h>
3.
4. int main() {
9.
14.
15. return 0;
16. }
17. </math.h></stdio.h>
Output:
Sine: 0.84
Cosine: 0.54
Tangent: 1.56
Example:
1. #include <stdio.h>
2. #include <math.h>
3.
4. int main() {
5. double x = 2.0;
8. return 0;
9. }
10. </math.h></stdio.h>
Output:
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;
8.
11. return 0;
12. }
13. </math.h></stdio.h>
Output:
Example:
1. #include <stdio.h>
2. #include <math.h>
3.
4. int main() {
5. double x = 3.7;
6. double y = -2.3;
7.
10.
13.
14. return 0;
15. }
16. </math.h></stdio.h>
Output:
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;
8. return 0;
9. }
10. </math.h></stdio.h>
Output:
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() {
9. return 0;
10. }
11. </math.h></stdio.h>
Output:
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;
8.
11.
12. return 0;
13. }
14. </math.h></stdio.h>
Output:
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;
9. return 0;
10. }
11. </math.h></stdio.h>
-
Output:
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.
10.
11. return 0;
12. }
13. </math.h></stdio.h>
Output: