Data Types
Data Types
h>
• int main() {
• // Create variables
• int Num = 5; // Integer (whole number)
• float FloatNum = 5.99; // Floating point number
• char Letter = 'D'; // Character
•
• // Print variables
• printf("%d\n", Num);
• printf("%f\n", FloatNum);
• printf("%c\n", Letter);
• return 0;
• }
Basic Format Specifiers
C Character Data Types
• The character must be surrounded by single quotes, like 'A' or 'c', and
we use the %c format specifier to print it:
• Example
char myGrade = 'A';
printf("%c", myGrade);
example
• #include <stdio.h>
• int main() {
• char Grade1 = 'A';
• char Grade2='B';
• printf("%c\n%c\t", Grade1,Grade2);
• return 0;
•}
TO GET ASCII VALUE
• #include <stdio.h>
• int main() {
• char a = 65, b = 66, c = 67;
• printf("%c\n", a);
• printf("%c\n", b);
• printf("%c", c);
• return 0;
•}
NOTE
• If you try to store more than a single character, it will only print the
last character:
• #include <stdio.h>
• int main() {
• char myText = 'Hello';
• printf("%c", myText);
• return 0;
•}
CONT...
• To store multiple characters (or whole words), use strings (which you
will learn more about in a later chapter):
• #include <stdio.h>
• int main() {
• char myText[] = "Hello";
• printf("%s", myText);
• return 0;
•}
C Numeric Data Types
• Use int when you need to store a whole number without decimals, like 35 or 1000,
and float or double when you need a floating point number (with decimals), like
9.99 or 3.14515.
• INTEGER:
• #include <stdio.h>
• int main() {
• int myNum = 1000;
• printf("%d", myNum);
• return 0;
• }
FLOAT
• #include <stdio.h>
• int main() {
• float myNum = 5.75;
• printf("%f", myNum);
• return 0;
•}
DOUBLE
• #include <stdio.h>
• int main() {
• double myNum = 19.99;
• printf("%lf", myNum);
• return 0;
•}
C The sizeof Operator
Memory Size:
• The memory size of a variable varies depending on the type:
• #include <stdio.h>
• int main() {
• int myInt;
• float myFloat;
• double myDouble;
• char myChar;
•
• printf("%lu\n", sizeof(myInt));
• printf("%lu\n", sizeof(myFloat));
• printf("%lu\n", sizeof(myDouble));
• printf("%lu\n", sizeof(myChar));
•
• return 0;
constant
• #include <stdio.h>
• int main() {
• const int minutesPerHour = 60;
• const float PI = 3.14;
• printf("%d\n", minutesPerHour);
• printf("%f\n", PI);
• return 0;
•}
• Arithmetic operators are the type of operators used to perform basic math
operations like addition, subtraction, and multiplication. Let’s take a look at an
example:
• #include <stdio.h>
• int main() {
• // Calculate the area of the triangle
• int sum = 10 + 20;
• printf("%d", sum);
• return 0;
• }
• These can be classified into two types based on the number of
operands they work on:
• int main() {
• int myNum = 100 + 50;
• printf("%d", myNum);
• return 0;
•}
assignment operator
• #include <stdio.h>
• int main() {
• int x = 10;
• printf("%d", x);
• return 0;
•}
Assignment operators
cont..
comparision operator
• #include <stdio.h>
int main() {
• int x = 5;
• int y = 3;
• printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
• return 0;
•}
percedence of operators
precedence table
()- parenthesis in function call
Member access operator(->.)
table
cont..
Important facts
ex
problem?
}
Assignment operators
• Assignment operators are used to assign values to variables.
• #include <stdio.h>
• int main() {
• int x = 10;
• printf("%d", x);
• return 0;
•}
Addition assignment
operator(x=x+a)
• The addition assignment operator (+=) adds a value to a variable:
• #include <stdio.h>
• int main() {
• int x = 10;
• x += 5;
• printf("%d", x);
• return 0;
•}
Comparison Operators
• Comparison operators are used to compare two values (or variables).
This is important in programming, because it helps us to find answers
and make decisions.
• The return value of a comparison is either 1 or 0, which means true
(1) or false (0).
Example
• #include <stdio.h>
• int main() {
• int x = 5;
• int y = 3;
• printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
• return 0;
•}
Comparision operator table
Logical Operators
• Logical operators are used to determine the logic between variables
or values, by combining multiple conditions:
Conditions and If Statements
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b
The if Statement
• Use the if statement to specify a block of code to be executed if a
condition is true.
• Syntax:
• if (condition) {
// block of code to be executed if the condition is true
•}
• #include <stdio.h>
• int main() {
• int x = 20;
• int y = 18;
• if (x > y) {
• printf("x is greater than y");
• }
• return 0;
•}
example
• #include <stdio.h>
• int main() {
• if (20 > 18) {
• printf("20 is greater than 18");
• }
• return 0;
•}
The else Statement
• Use the else statement to specify a block of code to be executed if the
condition is false.
• Syntax:
• if (condition) {
• // block of code to be executed if the condition is true
• } else {
• // block of code to be executed if the condition is false
•}
Example
• #include <stdio.h>
• int main() {
• int time = 20;
• if (time < 18) {
• printf("Good day.");
• } else {
• printf("Good evening.");
• }
• return 0;
• }
The else if Statement
• Use the else if statement to specify a new condition if the first condition is false.
• Syntax:
• if (condition1) {
• // block of code to be executed if condition1 is true
• } else if (condition2) {
• // block of code to be executed if the condition1 is false and condition2 is true
• } else {
• // block of code to be executed if the condition1 is false and condition2 is false
• }
Example
• #include <stdio.h>
• int main() {
• int time = 22;
• if (time < 10) {
• printf("Good morning.");
• } else if (time < 20) {
• printf("Good day.");
• } else {
• printf("Good evening.");
• }
• return 0;
• }
Short Hand If...Else (Ternary
Operator)
• There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands. It can be used to
replace multiple lines of code with a single line. It is often used to
replace simple if else statements:
• Syntax:
• variable = (condition) ? expressionTrue : expressionFalse;
Example using if -else
• #include <stdio.h>
• int main() {
• int time = 20;
• if (time < 18) {
• printf("Good day.");
• } else {
• printf("Good evening.");
• }
• return 0;
• }
Another Example using Ternary
operator
• #include <stdio.h>
• int main() {
• int time = 20;
• (time < 18) ? printf("Good day.") : printf("Good evening.");
• return 0;
•}
Real time example
• #include <stdio.h>
• int main() {
• int PersonAge = 25;
• int votingAge = 18;
• int main() {
• int day = 4;
•
• switch (day) {
• case 1:
• printf("Monday");
• break;
• case 2:
• printf("Tuesday");
• break;
• case 3:
• printf("Wednesday");
• break;
• case 4:
• printf("Thursday");
• break;
• case 5:
• printf("Friday");
• break;
• case 6:
• printf("Saturday");
• break;
• case 7:
• printf("Sunday");
• break;
• }
•
default keyword
• #include <stdio.h>
• int main() {
• int day = 4;
•
• switch (day) {
• case 6:
• printf("Today is Saturday");
• break;
• case 7:
• printf("Today is Sunday");
• break;
• default:
• printf("Looking forward to the Weekend");
loops
• Loops are handy because they save time, reduce errors, and they
make code more readable.
While Loop:
• The while loop loops through a block of code as long as a specified
condition is true.
Syntax:
• while (condition) {
• // code block to be executed
•}
Example
• #include <stdio.h>
• int main() {
• int i = 0;
•
• while (i < 5) {
• printf("%d\n", i);
• i++;
• }
•
• return 0;
• }
Do/While Loop
• The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it
will repeat the loop as long as the condition is true.
Syntax:
• do {
• // code block to be executed
•}
• while (condition);
Example
• #include <stdio.h>
• int main() {
• int i = 0;
•
• do {
• printf("%d\n", i);
• i++;
• }
• while (i < 5);
•
• return 0;
• }
while loop
• #include <stdio.h>
• int main() {
• int countdown = 3;
• return 0;
• }
For Loop
• When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop:
• Syntax:
• for (expression 1; expression 2; expression 3) {
• // code block to be executed
•}
example
• #include <stdio.h>
• int main() {
• int i;
• BREAK:
• The break statement can also be used to jump out of a loop.
• int main() {
• int i;
•
• for (i = 0; i < 10; i++) {
• if (i == 4) {
• break;
• }
• printf("%d\n", i);
• }
•
• return 0;
CONTINUE
• The continue statement breaks one iteration (in the loop), if a
specified condition occurs, and continues with the next iteration in
the loop.
• The if-else ladder is useful when you have multiple conditions to check.
• The first if condition is checked first. If it's true, the corresponding
block executes, and the rest are skipped.
• If the first condition is false, it moves to the next else if, and so on.
• The else block is optional and executes only if none of the previous
conditions are met.
• This is different from using multiple if statements separately, where each
if is checked independently.
Unformatted Input and Output
Statements
• Unformatted input and output statements are used to read and
display data without any specific formatting. These statements deal
with raw data and do not require format specifiers like %d, %f, etc.
• Unformatted Input: getchar(), gets()
• int main() {
• char ch;
• char str[100];
• // Unformatted input
• printf("Enter a character: ");
• ch = getchar(); // Reads a single character
• printf("Enter a string: ");
• getchar(); // Consume newline left by getchar
• gets(str); // Reads a string (deprecated, use fgets instead)
• // Unformatted output
• printf("You entered: ");
• putchar(ch); // Prints single character
• printf("\n");
• printf("String is: ");
• puts(str); // Prints string with newline
• return 0;
•}
output
• Enter a character: A
• Enter a string: Hello World
• You entered: A
• String is: Hello World
Formatted Input and Output
Statements in C
• 1. What Are Formatted I/O Statements?
cont..
• Formatted input and output functions allow us to read and display
data in a controlled format using format specifiers.
• int main() {
• int age;
• float height;
• char name[20];
• printf("\nName: %s, Age: %d, Height: %.2f meters\n", name, age, height);
• return 0;
•}
output
• Enter your name: John
• Enter your age: 25
• Enter your height: 5.9
• int main() {
• int n, i;
• double fact = 1;
• printf("Enter an integer: ");
• scanf("%d", &n);
• return 0;
• }
output
• Enter an integer: 5
• Factorial of 5 = 120.000000
• int main() {
• int i;
• int data[100];
How to declare an array?
• dataType arrayName[arraySize];
• For example,
• float mark[5];
note:
• we declared an array, mark, of floating-point type. And its size is 5.
Meaning, it can hold 5 floating-point values.
• It's important to note that the size and type of an array cannot be
changed once it is declared.
Access Array Elements
• u can access elements of an array by indices.
• Suppose you declared an array mark as above. The
first element is mark[0], the second element is
mark[1] and so on.
keynotes:
• Arrays have 0 as the first index, not 1. In this example, mark[0] is the
first element.
• If the size of an array is n, to access the last element, the n-1 index is
used. In this example, mark[4]
• Suppose the starting address of mark[0] is 2120d. Then, the address
of the mark[1] will be 2124d. Similarly, the address of mark[2] will be
2128d and so on.
• This is because the size of a float is 4 bytes.
How to initialize an array?
• It is possible to initialize an array during declaration. For example,
• #include <stdio.h>
• int main() {
• int values[5];
• To use them, you must include the <string.h> header file in your
program:
• #include <string.h>
String Length
• To get the length of a string, you can use the strlen() function:
• #include <stdio.h>
• #include <string.h>
• int main()
•{
• char alphabet[] = "ABCDEF";
• printf("%d", strlen(alphabet));
• return 0;
•}
• sizeof also includes the \0 character when counting:
• #include <stdio.h>
• #include <string.h>
• int main()
•{
• char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
• printf("Length is: %d\n", strlen(alphabet));
• printf("Size is: %d\n", sizeof(alphabet));
• return 0;
•}
Concatenate Strings
• To concatenate (combine) two strings, you can use the strcat()
function:
• #include <stdio.h>
• #include <string.h>
• int main() {
• char str1[20] = "Hello ";
• char str2[] = "World!";
• // Concatenate str2 to str1 (the result is stored in str1)
• strcat(str1, str2);
• // Print str1
• printf("%s", str1);
• return 0;
• }
Copy Strings
• To copy the value of one string to another, you can use the strcpy()
function:
• #include <stdio.h>
• #include <string.h>
• int main() {
• char str1[20] = "Hello World!";
• char str2[20];
• // Copy str1 to str2
• strcpy(str2, str1);
• // Print str2
• printf("%s", str2);
• return 0;
• }
Compare Strings
• To compare two strings, you can use the strcmp() function.
• It returns 0 if the two strings are equal, otherwise a value that is not
0:
• #include <stdio.h>
• #include <string.h>
• int main() {
• char str1[] = "Hello";
• char str2[] = "Hello";
• char str3[] = "Hi";
• // Compare str1 and str2, and print the result
• printf("%d\n", strcmp(str1, str2));
• // Compare str1 and str3, and print the result
• printf("%d\n", strcmp(str1, str3));
• return 0;
QUIZ
1.Which function is used to find the length of a string in C?
STRCOPY()
STRCMP()
STRLEN()
STRCAT()
What will the following code output?
char alphabet[] = "ABC";
printf("%d", strlen(alphabet));
1
3
4
2
Which function can be used to
concatenate two strings in C?
STRCPY()
STRCMP()
STRLEN()
STRCAT()
Given char str1[20] = "Hello"; and char str2[]
= " World";, what will be the value of str1
after strcat(str1, str2);?
Hello
Hello World
World
HelloWorld
Which function is used to copy the
contents of one string to another in C?
STRCPY()
STRCMP()
STRLEN()
STRCAT()
What does strcmp(str1, str2) return
if str1 and str2 are identical?
1
-1
0
UNDEFINED
Example of One Dimensional Array
in
• // CC
program to illustrate how to create an array,
• // initialize it, update and access elements
• #include <stdio.h>
• int main()
• {
• // declaring and initializing array
• int arr[5] = { 1, 2, 4, 8, 16 };
• // printing it
• for (int i = 0; i < 5; i++) {
• printf("%d ", arr[i]);
• }
• printf("\n");
• // updating elements
• arr[3] = 9721;
• // printing again
• for (int i = 0; i < 5; i++) {
• printf("%d ", arr[i]);
• }
• return 0;
•}
output
• 1 2 4 8 16
• 1 2 4 9721 16
Advantages of Arrays:
• Efficient Memory Usage
• Fast Random Access
• Simple Implementation
• Suitable for Ordered Data:
Drawbacks of Arrays:
• Fixed Size:
• Insertion/Deletion Difficulty:(it takes time)
• Memory Waste with Sparse Data:
• Poor Performance for Dynamic Operations:(When dealing with
frequently changing data sizes, arrays can become inefficient due to
the need for resizing operations. )
• Homogeneity
2D array example
• // C Program to illustrate the 2D array
• #include <stdio.h>
• int main() {
• // Create and initialize an array with 3 rows
• // and 2 columns
• int arr[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
• // Print each array element's value
• for (int i = 0; i < 3; i++) {
• for (int j = 0; j < 2; j++) {
• printf("arr[%d][%d]: %d ", i, j, arr[i][j]);
• }
• printf("\n");
• }
• return 0;
• }
Output
• arr[0][0]: 0 arr[0][1]: 1
• arr[1][0]: 2 arr[1][1]: 3
• arr[2][0]: 4 arr[2][1]: 5
Length of Array in C
• #include <stdio.h>
• int main() {
• int arr[5] = { 1, 2, 3, 4, 5 };
• // Find the size of the array arr
• int n = sizeof(arr) / sizeof(arr[0]);
• printf("%d", n);
• return 0;
•}
output
•5
How would you access the element in the second row
and first column of this array?
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
• matrix[1][0]
• matrix[2][0]
• matrix[0][1]
• matrix[1][1]
What would the following code
output?
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
• printf("%d", matrix[0][2]);
•4
•6
•2
•3
Which of the following statements will change the
first element in the second row of matrix to 7?
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
• matrix[0][1] = 7;
• matrix[1][0] = 7;
• matrix[2][0] = 7;
• matrix[1][1] = 7;
What does the following declaration represent?
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
• A 1-dimensional array of 5 elements
• A 2-dimensional array with 2 rows and 3 columns
• A 3-dimensional array with 2 rows and 3 columns
• A 1-dimensional array with 6 elements
To print all elements in a 2D array,
what is required?
• Only one for loop
• A nested loop with one for loop for each dimension
• Two separate for loops for each dimension
• A single printf statement
Two-Dimensional Arrays
• A 2D array is also known as a matrix (a table of rows and columns).
• EXAMPLE:
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
The first dimension represents the number of rows
[2], while the second dimension represents the
number of columns [3].
Access the Elements of a 2D Array
• To access an element of a two-dimensional array, you must specify
the index number of both the row and column.
• This statement accesses the value of the element in the first row (0)
and third column (2) of the matrix array.
• #include <stdio.h>
• int main() {
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
• printf("%d", matrix[0][2]);
• return 0;
•}
Change Elements in a 2D Array
• To change the value of an element, refer to the index number of the
element in each of the dimensions:
• #include <stdio.h>
• int main() {
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
• matrix[0][0] = 9;
• printf("%d", matrix[0][0]); // Now outputs 9 instead of 1
• return 0;
•}
Loop Through a 2D Array
• To loop through a multi-dimensional array, you need one loop for
each of the array's dimensions.