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

Data Types

The document provides an overview of basic C programming concepts, including data types, operators, control structures, and loops. It covers how to declare variables, use format specifiers for output, and implement conditional statements like if-else and switch. Additionally, it explains the use of loops such as while, do-while, and for, along with examples for each concept.

Uploaded by

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

Data Types

The document provides an overview of basic C programming concepts, including data types, operators, control structures, and loops. It covers how to declare variables, use format specifiers for output, and implement conditional statements like if-else and switch. Additionally, it explains the use of loops such as while, do-while, and for, along with examples for each concept.

Uploaded by

ksr
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 208

• #include <stdio.

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 char Type


• The char data type is used to store a single character.

• 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:

• Binary Arithmetic Operators


• Unary Arithmetic Operators
1. Binary Arithmetic Operators
• The binary arithmetic operators work on two operands.
Example-Arithmetic program
cont...
C Keywords
C Output (Print Text)
• #include <stdio.h>
• int main() {
• printf("Hello World!");
• return 0;
•}
• #include <stdio.h>
• int main() {
• printf("Hello World!");
• printf("I am learning C.");
• printf("And it is awesome!");
• return 0;
•}
operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
operators:
Operators are used to perform operations on
variables and values.
• #include <stdio.h>

• 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;

• if (PersonAge >= votingAge) {


• printf("Old enough to vote!");
• } else {
• printf("Not old enough to vote.");
• }

• return 0;
• }
Switch Statement
• Instead of writing many if..else statements, you can use the switch
statement.

• The switch statement selects one of many code blocks to be


executed:
syntax
• switch (expression) {
• case x:
• // code block
• break;
• case y:
• // code block
• break;
• default:
• // code block
•}
• This is how it works:

• The switch expression is evaluated once


• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed
• The break statement breaks out of the switch block and stops the
execution
• The default statement is optional, and specifies some code to run if
there is no case match
• #include <stdio.h>

• 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;

• while (countdown > 0) {


• printf("%d\n", countdown);
• countdown--;
• }

• printf("Happy New Year!!\n");

• 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;

• for (i = 0; i < 5; i++) {


• printf("%d\n", i);
• }

• return 0;
• }
EXPRESSIONS
TYPE CASTING
INPUT/OUTPUT STATEMENTS
GETC() AND PUTC()
GETS() AND PUTS()
FORMATTED INPUT/OUTPUT
STATEMENTS
UNCONDITIONAL STATEMENTS
• BREAK
• CONTINUE
• GOTO
• return

• BREAK:
• The break statement can also be used to jump out of a loop.

• This example jumps out of the for loop when i is equal to 4:


• #include <stdio.h>

• 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.

• This example skips the value of 4:


• #include <stdio.h>
• int main() {
• int i = 0;
• while (i < 10) {
• if (i == 4) {
• i++;
• continue;
• }
• printf("%d\n", i);
• i++;
• }
• return 0;
USING WHILE LOOP
• #include <stdio.h>
• int main() {
• int i = 0;
• while (i < 10) {
• if (i == 4) {
• break;
• }
• printf("%d\n", i);
• i++;
• }
• return 0;
• }
GOTO STATEMENTS
OUTPUT
BOOLEAN
• A boolean variable is declared with the bool keyword and can take
the values true or false:
• you should know that boolean values are returned as integers:

• 1 (or any other number that is not 0) represents true


• 0 represents false
• Therefore, you must use the %d format specifier to print a boolean
value:
if-else ladder
• An if-else ladder (also called an if-else-if ladder) is a series of
conditional statements used to check multiple conditions sequentially.
It is an alternative to using multiple if statements separately.
syntax
• if (condition1) {
• // Code block if condition1 is true
• }
• else if (condition2) {
• // Code block if condition2 is true
• }
• else if (condition3) {
• // Code block if condition3 is true
• }
• else {
• // Code block if none of the above conditions are true
• }
Example
• #include <stdio.h>
• int main() {
• int num = 10;
• if (num > 0) {
• printf("Number is positive.\n");
• }
• else if (num < 0) {
• printf("Number is negative.\n");
• }
• else {
• printf("Number is zero.\n");
• }
• return 0;
• }
Key Points:

• 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()

• getchar(): Reads a single character.


• gets(): Reads a string(use fgets() instead).)

• Unformatted Output: putchar(), puts()


• putchar(): Displays a single character.
• puts(): Displays a string and automatically adds a newline (\n).
• #include <stdio.h>

• 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.

• Formatted Input: scanf()


• Formatted Output: printf()
Formatted Input (scanf())
• scanf() is used to take user input in a formatted manner.
• It requires format specifiers to determine the type of data being read.
• Syntax:
• scanf("format_specifier", &variable);
• example:
• int num;
• scanf("%d", &num);
Common Format Specifiers in
scanf()
• %d or %i
• %f
• %c
• %s
• %lf
Example Using scanf()
• #include <stdio.h>

• int main() {
• int age;
• float height;
• char name[20];

• printf("Enter your name: ");


• scanf("%s", name); // Reads a single word (no spaces)

cont....
• printf("Enter your age: ");
• scanf("%d", &age); // Reads an integer

• printf("Enter your height: ");


• scanf("%f", &height); // Reads a float

• 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

• Name: John, Age: 25, Height: 5.90 meters


Formatted Output (printf())
• printf() is used to display data with specific formatting.
• Syntax:
• printf("format_specifier", variable);
example
• int num = 10;
• printf("The number is: %d", num);
cont....
example
• #include <stdio.h>
• int main() {
• int num = 100;
• float pi = 3.14159;
• char letter = 'A';
• char name[] = "Alice";
• printf("Integer: %d\n", num);
• printf("Floating-point: %.2f\n", pi); // Two decimal places
• printf("Character: %c\n", letter);
• printf("String: %s\n", name);
• return 0;
• }
output
• Integer: 100
• Floating-point: 3.14
• Character: A
• String: Alice
Width and Precision in printf()
• You can control the width and precision of output using the format
specifiers:
• Width: Defines the minimum number of characters to display.
• Precision: Defines the number of decimal places for floating-point
numbers.
cont...
• printf("%10d\n", 123); // Right-align with width 10
• printf("%-10d\n", 123); // Left-align with width 10
• printf("%.2f\n", 3.14159); // Show only 2 decimal places
• printf("%10.2f\n", 3.14159); // Right-align with width 10 and 2
decimal places
output:
• 123
• 123
• 3.14
• 3.14
• Reading a Full Line of Text (scanf() Limitation)
• By default, scanf("%s", str); cannot read spaces.
• To read a full line of text, use fgets() instead:
• char str[50];
• printf("Enter a sentence: ");
• fgets(str, sizeof(str), stdin);
• printf("You entered: %s", str);
syn:printf("%[width]d", value);
• #include <stdio.h>
• int main() {
• int num = 42;
• printf("Default: [%d]\n", num);
• printf("Width 5: [%5d]\n", num);
• printf("Width 10: [%10d]\n", num);
• return 0;
•}
output
• Default: [42]
• Width 5: [ 42]
• Width 10: [ 42]
• In [5d], the total width is 5, so three spaces are added before 42 to
make it five characters long.
• In [10d], eight spaces are added before 42.
Left-Aligning Using - (Negative
Width)
• By default, printf() right-aligns numbers.
• To left-align, use a minus (-) before the width.
• #include <stdio.h>
• int main() {
• int num = 42;
• printf("Right-aligned: [%5d]\n", num);
• printf("Left-aligned : [%-5d]\n", num);
• return 0;
•}
output
• Right-aligned: [ 42]
• Left-aligned : [42 ]
Width with Floating-Point Numbers
• For floating-point numbers, width applies to the entire number, and precision (.n)
controls decimal places.
• #include <stdio.h>
• int main() {
• float pi = 3.14159;
• printf("Default : [%f]\n", pi);
• printf("Width 10 : [%10f]\n", pi);
• printf("Width 10.2: [%10.2f]\n", pi);
• return 0;
• }
output
• Default : [3.141590]
• Width 10 : [ 3.141590]
• Width 10.2: [ 3.14]
cont...
• %10f → Reserves 10 spaces, padding before the number.
• %10.2f → Reserves 10 spaces with 2 decimal places.
PATTERN OR PYRAMID FORMAT
• #include <stdio.h>
• int main() {
• int i, j, rows;
• printf("Enter the number of rows: ");
• scanf("%d", &rows);
• for (i = 1; i <= rows; ++i) {
• for (j = 1; j <= i; ++j) {
• printf("* ");
• }
• printf("\n");
OUTPUT
•1
•12
•123
•1234
•12345
factorial
• #include <stdio.h>

• int main() {
• int n, i;
• double fact = 1;
• printf("Enter an integer: ");
• scanf("%d", &n);

• // shows error if the user enters a negative integer


• if (n < 0)
• printf("Error! Factorial of a negative number doesn't exist.");
• else {
• for (i = 1; i <= n; ++i) {
• fact *= i;
• }
• printf("Factorial of %d = %lf", n, fact);
• }

• return 0;
• }
output
• Enter an integer: 5
• Factorial of 5 = 120.000000

• === Code Execution Successful ===


even or odd
• #include <stdio.h>
• int main() {
• int num;
• printf("Enter an integer: ");
• scanf("%d", &num);

• // true if num is perfectly divisible by 2


• if(num % 2 == 0)
• printf("%d is even.", num);
• else
• printf("%d is odd.", num);

• return 0;
output
• Enter an integer: -7
• -7 is odd.
Print numbers from 1 to 10
• // Print numbers from 1 to 10
• #include <stdio.h>

• int main() {
• int i;

• for (i = 1; i < 11; ++i)


• {
• printf("%d ", i);
• }
• return 0;
output
• 1 2 3 4 5 6 7 8 9 10
C Arrays
• An array is a variable that can store multiple values. For example, if
you want to store 100 integers, you can create an array for it.

• 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,

• int mark[5] = {19, 10, 8, 17, 9};


• You can also initialize an array like this.

• int mark[] = {19, 10, 8, 17, 9};


• Here, we haven't specified the size. However, the compiler knows its
size is 5 as we are initializing it with 5 elements.
• mark[0] is equal to 19
• mark[1] is equal to 10
• mark[2] is equal to 8
• mark[3] is equal to 17
• mark[4] is equal to 9
Change Value of Array elements
• nt mark[5] = {19, 10, 8, 17, 9}

• // make the value of the third element to -1


• mark[2] = -1;

• // make the value of the fifth element to 0


• mark[4] = 0;
Input and Output Array Elements

• // take input and store it in the 3rd element


• ​scanf("%d", &mark[2]);

• // take input and store it in the ith element


• scanf("%d", &mark[i-1]);
• // print the first element
• printf("%d", mark[0]);

• // print the third element


• printf("%d", mark[2]);

• // print the ith element\


• printf("%d", mark[i-1]);
• // Program to take 5 values from the user and store them in an array
• // Print the elements stored in the array

• #include <stdio.h>

• int main() {

• int values[5];

• printf("Enter 5 integers: ");

• // taking input and storing it in an array


• for(int i = 0; i < 5; ++i) {
• scanf("%d", &values[i]);
• }

• printf("Displaying integers: ");

• // printing elements of the array


• for(int i = 0; i < 5; ++i) {
• printf("%d\n", values[i]);
• }
• return 0;
• }
C String Functions
• String Functions
• C also has many useful string functions, which can be used to perform
certain operations on strings.

• 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.

• The following example outputs all elements in the matrix array:


• #include <stdio.h>
• int main() {
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
• int i, j;
• for (i = 0; i < 2; i++) {
• for (j = 0; j < 3; j++) {
• printf("%d\n", matrix[i][j]);
• }
• }
• printf("\n");
• return 0;
• }
simple program to assign values:
• #include <stdio.h>
• int main() {
• // Declare an array of four integers:
• int myNumbers[4];
• // Add elements to it
• myNumbers[0] = 25;
• myNumbers[1] = 50;
• myNumbers[2] = 75;
• myNumbers[3] = 100;
• printf("%d\n", myNumbers[0]);
• return 0;
• }
Avoid Mixing Data Types
• #include <stdio.h>
• int main() {
• // Trying to declare an array of both integers and floating point numbers
• int myArray[] = {25, 50, 75, 3.15, 5.99};
• int i;
• for (i = 0; i < 5; i++) {
• printf("%d\n", myArray[i]);
• }
• return 0;
• }
output???
QUIZ
1.what is the correct syntax to declare an array of integers called
myNumbers with the values 25, 50, 75, and 100?
• int myNumbers[25, 50, 75, 100];
• int myNumbers = {25, 50, 75, 100};
• int myNumbers[] = {25, 50, 75, 100};
• int myNumbers[] = 25, 50, 75, 100;
• 2.Create an array of type int called myNumbers.
• -------- ----------------- ------{25,20,20,90};
Print the value of the second
element in the myNumbers array.
• int myNumbers[] = {25, 50, 75, 100};
• printf("%d", ------------------);
Change the value of the first
element to 33:
• int myNumbers[] = {25, 50, 75, 100};
• -------- ------------------- --------;
5.What will the following code output?
• int myNumbers[] = {25, 50, 75, 100};
• myNumbers[0] = 12;
• printf("%d", myNumbers[0]);
• 25
• 50
• 12
• 100
Which index should be used to
access the third element in an array?
•0
•1
•2
•3
7.What is the output of the following code?
• int myNumbers[] = {25, 50, 75, 100};
• for (int i = 0; i < 4; i++) {
• printf("%d ", myNumbers[i]);
•}
• 25 50 75 100
• 25 75 50 100
• 100 75 50 25
•0123
8.Loop through the elements in the array using a for loop.

• int myNumbers[] = {25, 50, 75, 100};


• int i;
• ------------ (i = 0; i < 4; i++) {
• printf("%d\n", ----------------);
•}

You might also like