0% found this document useful (0 votes)
13 views17 pages

C Programming Introduction

None
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views17 pages

C Programming Introduction

None
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

Variables in C

➢ A variable is a named location in memory that stores a value.


➢ a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.
➢ It is a way to represent memory location through symbol so that it can be
easily identified.

i. Syntax and declaration of a variable


datatype variable_list;
Before using a variable, you need to declare it. The declaration specifies
the data type of the variable and its name.
For example:
int age; // Declaration of an integer variable named 'age'
float height; // Declaration of a floating-point variable named 'height'
char grade; // Declaration of a character variable named 'grade'

ii. Initialization
Initialization means assigning an initial value to the variable. After
declaration, you can optionally initialize a variable with a specific value.
For example:
int age = 18; // Initialization of 'age' with the value 18
float height = 7.5; // Initialization of 'height' with the value 7.5
char grade = 'B'; // Initialization of 'grade' with the character 'B'

iii. Scope/Types of Variables in C


The scope of a variable defines where it can be accessed. In C, variables
can have either local or global scope.
• Local Variables: Declared within the function and can only be
accessed within that function.
• Global Variables: Declared outside the function and can be accessed
by any part of the program/function.

iv. Variable Naming Rules


Variables in C must follow these naming rules:
1) Must begin with a letter or underscore (_).
2) Subsequent characters can be letters, digits, or underscores.
3) Case-sensitive (e.g., area and Area are different variables).
4) No whitespace is allowed within the variable name
5) Avoid using reserved words (e.g., int, for, while) as variable names.

v. Constants
• In addition to variables, C allows the use of constants. Constants are
similar to variables, but their values cannot be changed once set.
They are often defined using the const keyword.
• Are the read-only variables whose values cannot be modified once
they are declared in the C program
Syntax
const data_type var_name = value;

Data types
As the name suggests, a Datatype defines the type of data being used. Whenever
we define a variable or use any data in the C programming, we have to specify
the type of the data, so that the compiler knows what type of data to expect.
The following are 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

A. Basic Data Types:


• Integer Data Type: Integer data type is used to store whole
numbers (positive or negative).
Range : -2,147,483,648 to 2,147,483,647
Size : 4 bytes
Format Specifier : %d
Syntax of Integer
We use int keyword to declare the integer variable:
int var_name;

Example
int number;
• Float Data Type: Floating-point data type is used to store numbers
with decimal points.
Range : 1.2E-38 to 3.4E+38
Size : 4 bytes
Format Specifier : %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;

Example
float pi = 3.14;
• Double Data Type: Double-precision floating-point data type is
used for larger decimal numbers and provides more precision than
float.
Range : 1.7E-308 to 1.7E+308
Size : 8 bytes
Format Specifier : %lf
Syntax of Double
The variable can be declared as double precision floating point using
the double keyword:

double var_name;
Example
double bigSize = 123456.79;

• Character Data Type: Character data type is used to store a single


character.
Range : (-128 to 127) or (0 to 255)
Size : 1 byte
Format Specifier : %c
Syntax of char
The char keyword is used to declare the variable of character type:

char var_name;
Example
char grade = 'A';
• Bool: Boolean data type is used to represent true or false values (0
or 1).

Example
bool a = true;
B. Derived Data Type
• These data types give programmers the ability to handle
heterogeneous data, directly modify memory, and build complicated
data structures.
• C also supports derived data types, including arrays, pointers,
structures, and unions.
➢ Arrays: Arrays allow you to store multiple values of the same
data type in a contiguous memory block.

Example
int numbers[5] = {1, 2, 3, 4, 5};
➢ Pointers: Pointers store the memory address of a variable.
They allow dynamic memory allocation and manipulation.

Example
int *ptr = &number;
➢ Structures: Structures allow you to group variables of different
data types under a single name.

Example
struct Person {
char name[20];
int age;
};
➢ Unions: Unions are similar to structures, but they share the
same memory location for all their members.

Example
union Value {
int intValue;
float floatValue;
};

C. Enumeration Data Type


• A set of named constants or enumerators that represent a collection
of connected values
• Enumeration allows you to define a set of named integer constants.
• It’s declared using enum keyword
Example
enum Days {Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday, Sunday};
D. Void Data Type
The void data type is used to indicate that a function does not return any
value.

Data type Qualifiers


Type qualifiers are keywords that can be used to change a data type's behavior.
These qualifiers can be used to describe a variable or pointer's constancy,
volatility, and restrictions.
1. const Qualifier:
The const qualifier is used to declare constants. Once a variable is declared
as const, its value cannot be modified during the program execution. This
helps in creating read-only variables and improves program safety.
Example:
const int MAX_VALUE = 100;
const float PI = 3.14159;
In the above example, MAX_VALUE and PI are constants, and any attempt
to modify their values later in the program will result in a compilation
error.
2. volatile Qualifier:
The volatile qualifier is used to indicate that a variable's value may be
changed by external entities not known to the compiler. This prevents the
compiler from optimizing away certain operations involving the variable.
Used to describe a variable whose value is subject to sudden change.
Example:
volatile int sensorValue;
In this example, sensorValue is marked as volatile because its value might
change due to external factors, such as hardware interrupts or external
devices. Without the volatile qualifier, the compiler might optimize code
that assumes the value of sensorValue doesn't change outside the
program's control.
3. restrict Qualifier:
This is used only with pointers. The restrict qualifier is used as a hint to
the compiler that a particular pointer is the only way to access the pointed-
to data during its lifetime. It helps the compiler optimize code by assuming
that there are no other aliases for the same data.
Example:
void myFunction(int * restrict ptr1, int * restrict ptr2) {
// Code with the assumption that ptr1 and ptr2 don't alias.
}
In the above example, the restrict qualifier indicates that ptr1 and ptr2 are
not pointing to the same memory location.

C operators
Meaning;
✓ An operator is a symbol that tells the compiler to perform a certain
operation (arithmetic, comparison, etc.) using the values provided along
with the operator.
✓ Operators are used in programs to manipulate data and variables.
✓ An operand
➢ Every operator works with some values.
➢ The value with which an operator works is called as Operand.
➢ Can be a constant, a variable or a function result

Type of C Operators
C operators can be classified into the following types
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Conditional operators
7. Special operators

1. Arithmetic Operators
The C language supports all the basic arithmetic operators such as addition,
subtraction, multiplication, division, etc.

The following table shows all the basic arithmetic operators along with their
descriptions.
Example
(where a and b are
Operator Description variables with some
integer value)
+ Adds two operands (values) a+b

- Subtract second operands from first a-b

* Multiply two operands a*b

/ Divide the numerator by the denominator,


i.e. divide the operand on the left side with
a/b

the operand on the right side


% This is the modulus operator,
the remainder of the division of two
it returns a%b

++ operands
This is as the
the result
Increment operator - a++ or ++a
increases the integer value by one. This
-- operatorisneeds
This theonly a single operand.
Decrement operator - --b or b--
decreases integer value by one. This
operator needs only a single operand.
Example: Basic Arithmetic Operators
#include <stdio.h>
int main() {
int a = 50, b = 25, result;
// addition
result = a+b;
printf("Addition of a & b = %d \n",result);
// subtraction
result = a-b;
printf("Subtraction of a & b = %d \n",result);
// multiplication
result = a*b;
printf("Multiplication of a & b = %d \n",result);
// division
result = a/b;
printf("Division of a & b = %d \n",result);
// Using Modulus operator
result = a%b;
printf("result = %d",result);
return 0;
}

2. Relational operators in C
➢ The relational operators (or comparison operators) are used to check
the relationship between two operands.
➢ It checks whether two operands are equal or not equal or less than or
greater than, etc.
➢ It returns 1 if the relationship checks pass, otherwise, it returns 0.
➢ The following table shows all relational operators supported in the C
language.

Example
Operator Description (a and b, where a = 10 and b = 11)

== Check if the two operands are equal a == b, returns 0

Check if the two operands are not


!= a != b, returns 1
equal.

Check if the operand on the left is


> a > b, returns 0
greater than the operand on the right

Check operand on the left is smaller


< a < b, returns 1
than the right operand

check left operand is greater than or


>= a >= b, returns 0
equal to the right operand

Check if the operand on the left is


<= smaller than or equal to the right a <= b, returns 1
operand

Example: Relational Operators


When we use relational operators, we get the output based on the result of the
comparison.
If it's true, then the output is 1 and if it's false, then the output is 0.

#include <stdio.h>
int main() {
int a = 10, b = 20, result;
// Equal
result = (a==b);
printf("(a == b) = %d \n",result);
// less than
result = (a<b);
printf("(a < b) = %d \n",result);
// greater than
result = (a>b);
printf("(a > b) = %d \n",result);
// less than equal to
result = (a<=b);
printf("(a <= b) = %d \n",result);
return 0;
}

3. Logical Operators
C language supports the following 3 logical operators.
&& (Logical AND): Returns true if both operands are true.
|| (Logical OR): Returns true if at least one operand is true.
! (Logical NOT): Returns true if the operand is false and vice versa.

4. Assignment Operators
The assignment operators are used to assign value to a variable.
You can see all the assignment operators in the table given below.
Example
(a and b are two variables,
Operator Description with where a=10 and b=5)

assigns values from right side operand to


= a=b, a gets value 5
left side operand

+= adds right operand to the left operand a+=b, is same as a=a+b,


and assign the result to left operand value of a becomes 15
-= subtracts right operand from the left a-=b, is same as a=a-b, value
operand and assign the result to left of a becomes 5
*= operand
multiply left operand with the right a*=b, is same as a=a*b, value
operand and assign the result to left of a becomes 50
/= operandleft operand with the right
divides a/=b, is same as a=a/b,
operand and assign the result to left value of a becomes 2
%= operand modulus using two operands
calculate a%=b, is same as a=a%b,
and assign the result to left operand value of a becomes 0
Example: Using Assignment Operators
Below we have a code example in which we have used all the different forms of
assignment operators, starting from the basic assignment.
#include <stdio.h>
int main() {
int a = 10;
// Assign
int result = a;
printf("result = %d \n",result);
// += operator
result += a;
printf("result = %d \n",result);
// -= operator
result -= a;
printf("result = %d \n",result);
// *= operator
result *= a;
printf("result = %d \n",result);
return 0;
}
5. Bitwise Operators in C
During computation, mathematical operations like: addition, subtraction,
multiplication, division, etc are converted to bit-level which makes processing
faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Bitwise AND Operator &
The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If
either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
In C Programming, the bitwise AND operator is denoted by &.
Example for the bitwise AND operation of two integers 12 and 25.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)
--------

Example
#include <stdio.h>
int main ()
{
int a = 12, b = 25;
printf("Output = %d", a & b);
return 0;
}
Bitwise OR Operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is
1. In C Programming, bitwise OR operator is denoted by |.
Example for the bitwise OR operation of two integers 12 and 25.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)
--------

Example
#include <stdio.h>

int main()
{
int a = 12, b = 25;
printf("Output = %d", a | b);
return 0;
}

Bitwise XOR (exclusive OR) Operator ^


The result of bitwise XOR operator is 1 if the corresponding bits of two operands
are opposite. It is denoted by ^.
Example for the bitwise XOR operation of two integers 12 and 25.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
________
00010101 = 21 (In decimal)
--------

Example
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a ^ b);
return 0;
}

Bitwise Complement Operator ~


Bitwise complement operator is a unary operator (works on only one operand).
It changes 1 to 0 and 0 to 1. It is denoted by ~.

28 = 00011100 (In Binary)

Bitwise complement Operation of 28


~ 00011100
________
11100011 = 227 (In decimal)
--------

Shift Operators
There are two shift operators in C programming:
Right shift operator.
Left shift operator.

Right Shift Operator.


Right shift operator shifts all bits towards right by certain number of specified
bits. It is denoted by >>.

212 = 11010100 (In binary)


212 >> 2 = 00110101 (In binary) [Right shift by two bits]
212 >> 7 = 00000001 (In binary)
212 >> 8 = 00000000
212 >> 0 = 11010100 (No Shift)

Left Shift Operator.


Left shift operator shifts all bits towards left by a certain number of specified
bits. The bit positions that have been vacated by the left shift operator are filled
with 0. The symbol of the left shift operator is <<.

212 = 11010100 (In binary)


212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 = 11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)

#include <stdio.h>
int main()
{
int num=212, i;
for (i = 0; i <= 2; ++i)
{
printf("Right shift by %d: %d\n", i, num >> i);
}
printf("\n");
for (i = 0; i <= 2; ++i)
{
printf("Left shift by %d: %d\n", i, num << i);
}
return 0;
}
6. Conditional (Ternary) Operator:
➢ The conditional statements are the decision-making statements which
depends upon the output of the expression. It is represented by two
symbols, i.e., '?' and ':'.
➢ As conditional operator works on three operands, so it is also known as
the ternary operator.
➢ The behavior of the conditional operator is similar to the 'if-else'
statement as 'if-else' statement is also a decision-making statement.
➢ Syntax of a conditional operator
Expression1? expression2: expression3;

7. Special operators
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants,
variables, array, structure, etc).
Comma Operator
Comma operators are used to link related expressions together.

Precedence and Associativity.

In C, operators have precedence and associativity rules that determine the order
in which they are evaluated in an expression. Precedence defines the priority of
operators, and associativity defines the order in which operators of the same
precedence are evaluated. Understanding these rules is crucial for correctly
interpreting and writing expressions.

Precedence Rules:
The table below lists some of the major C operators in order of decreasing
precedence:

Operator Description of Operator Associativity


. Direct member selection Left to right
-> Indirect member selection Left to right
[] Array element reference Left to right
() Functional call Left to right
~ Bitwise(1’s) complement Right to left
! Logical negation Right to left
– Unary minus Right to left
+ Unary plus Right to left
— Decrement Right to left
++ Increment Right to left
* Pointer reference Right to left
& Dereference (Address) Right to left
(type) Typecast (conversion) Right to left
sizeof Returns the size of an Right to left
% object
Remainder Left to right
/ Divide Left to right
* Multiply Left to right
– Binary minus (subtraction) Left to right
+ Binary plus (Addition) Left to right
>> Right shift Left to right
<< Left shift Left to right
> Greater than Left to right
< Less than Left to right
>= Greater than or equal Left to right
<= Less than or equal Left to right
== Equal to Left to right
!= Not equal to Left to right
^ Bitwise exclusive OR Left to right
& Bitwise AND Left to right
|| Logical OR Left to right
| Bitwise OR Left to right
?: Conditional Operator Right to left
&& Logical AND Left to right
, Separator of expressions Left to right
= Simple assignment Right to left
/= Assign quotient Right to left
*= Assign product Right to left
%= Assign remainder Right to left
-= Assign difference Right to left
+= Assign sum Right to left
|= Assign bitwise OR Right to left
^= Assign bitwise XOR Right to left
&= Assign bitwise AND Right to left
>>= Assign right shift Right to left
<<= Assign left shift Right to left
Some Important Points to Remember
i. We only use associativity when we have two or more operators that have
the same precedence in an expression.
ii. The point to note here is that associativity is not applicable when we are
defining the order of evaluation of operands with different levels of
precedence.

iii. All the operators that have a similar level of precedence have the same
associativity. It is very important, or else the compiler won’t be able to
decide what order of evaluation must an expression follow when it has two
operators with the same precedence but different associativity. For
example, – and + have the very same associativity.

iv. The associativity and precedence of prefix ++ and postfix ++ are very
different from each other. Here, the precedence of prefix ++ is less as
compared to the postfix ++. Thus, their associativity also turns out to be
different. Here, the associativity of prefix ++ is from right to left, while the
associativity of postfix ++ is from left to right.

v. We must use a comma (,) very carefully, as it has the least level of
precedence among all the other operators present in an expression.

vi. We don’t have chaining of comparison in the C programming language.


The Python language treats the expressions such as x > y > z as x > y and
y > z. No similar type of chaining occurs in the C program.

int main()
{
int x = 5, y = 10;
int z;
z = x * 2 + y;
printf(“\n output = %d”, z);
return 0;
}

Type cast operator I/O statements

Type casting is the process in which the compiler automatically converts


one data type in a program to another one.
The basic syntax for type casting is as follows:

(type) expression

Here, (type) is the type cast operator, and expression is the value or
variable to be cast to the specified data type.

Examples of Type Casting:


Integer to Float:
int num = 10;
float result = (float) num;

Float to Integer:
float num = 15.75;
int result = (int) num;

Character to Integer:
char ch = 'A';
int asciiValue = (int) ch;

Integer to Character:
int asciiValue = 65;
char ch = (char) asciiValue;

Input/Output Statements and Type Casting:


When working with input and output statements, such as those involving
printf and scanf, it's important to use the appropriate format specifiers to
correctly interpret the data.

Formatted I/O Functions:


➢ Formatted I/O functions are used to take various inputs from the
user and display multiple outputs to the user. These types of I/O
functions can help to display the output to the user in different
formats using the format specifiers. These I/O supports all data
types like int, float, char etc.

➢ These functions are called formatted I/O functions because we can


use format specifiers in these functions

➢ Examples

1. printf()

printf() function is used in a C program to display any value


like float, integer, character, string, etc on the console screen.
It is a pre-defined function that is already declared in the
stdio.h(header file).

Syntax 1:
To display any variable value
printf(“Format Specifiers”, var1, var2, …., varn);

Syntax 2:
To display any string or a message
printf(“Enter the text which you want to display”);
2. scanf()

scanf() function is used in the C program for reading or taking


any value from the keyboard by the user, these values can be
of any data type like integer, float, character, string etc. This
function is declared in stdio.h(header file), that’s why it is also
a pre-defined function. In scanf() function we use &(address-
of operator) which is used to store the variable value on the
memory location of that variable.

Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);

Unformatted Input/Output functions:


➢ Unformatted I/O functions are used only for character data type or
character array/string and cannot be used for any other datatype. These
functions are used to read single input from the user at the console and it
allows to display the value at the console.
➢ These functions are called unformatted I/O functions because we cannot
use format specifiers in these functions and hence, cannot format these
functions according to our needs.
➢ Examples
1. getch()
getch() function reads a single character from the keyboard by the
user but doesn’t display that character on the console screen and
immediately returned without pressing enter key. This function is
declared in conio.h(header file). getch() is also used for hold the
screen.
Syntax:
getch();
2. getchar and putchar
getchar: Reads a single character from standard input.
putchar: Writes a single character to standard output.

Example
char ch;
ch = getchar(); // Read a character
putchar(ch); // Write a character

Example Program to do in the Lab Session

Exercise 1:
#include <stdio.h>
#include<conio.h>
void main()
{
// Declare variables
float length, width, area;

// Input: Get user input for length and width


printf("Enter the length of the rectangle: ");
scanf("%f", &length);

printf("Enter the width of the rectangle: ");


scanf("%f", &width);

// Process: Calculate the area using variables in expression


area = length * width;

// Output: Display the result


printf("The area of the rectangle with length %.2f and width %.2f is: %.2f\n",
length, width, area);

getch();
}

Exercise 2:
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a ^ b);
printf("Output = %d", a & b);
printf("Output = %d", a | b);

return 0;
}

Unit II: Flow Control

You might also like