Introduction to C Programming -Lecture 3

1mohamedgamal54 31 views 73 slides Sep 09, 2024
Slide 1
Slide 1 of 73
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73

About This Presentation

Introduction to C Programming Lecture for absolute beginners level.


Slide Content

Introduction to C
Programming
By Mohamed Gamal
© Mohamed Gamal 2024

The topics of today’s lecture:
Agenda

Loops
#include <stdio.h>
intmain () {
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
return0;
}
What if someone asks you to print 'Hello World'
10 times?
- One way is to write theprintfstatement 10 times.
But that is definitely not a good idea if you have
to write it 500 times!
Three types of loops in C:
1. for
2. while
3. do while

1) For Loop
for (initialization; test condition; increment or decrement) {
// codetobeexecuted
}
#include <stdio.h>
int main() {
for (int count = 1; count <= 10; count = count + 1) {
printf("%d\n", count);
}
return 0;
}

How does For loop work?

Example 1
#include <stdio.h>
int main() {
int i = 1, number = 0; // Declare the variables
printf("Enter a number: ");
scanf("%d", &number);
// for (Initialization ; Condition ; Inc/Dec )
for(i = 1; i <= 10; i++) {
printf("%d * %d = %d\n", number, i, (number * i));
}
return 0;
}

Example 2
#include <stdio.h>
int main()
{
unsigned long n, j;
printf("Enter a number: ");
scanf("%li", &n);
for (j = 2; j <= n / 2; j++)
if (n % j == 0)
{
printf("It's not prime; divisible by % i\n", j);
return 0; //exit from the program
}
printf("It's prime!");
return 0;
}

Example 3
#include <stdio.h>
int main() {
int number = 0, sum = 0; // Declare the variables
printf("Enterapositive integer: ");
scanf("%d", &number); // Take the number
// for (Initialization ; Condition ; Inc/Dec )
for(inti = 1; i <= number; i++) {
sum = sum + i;
}
printf("Sum = %d", sum);
return 0;
}

Multiple Initialization and Test Expressions
#include <stdio.h>
int main() {
for (int i = 1, j = 5; j > 0; i++, j--) {
printf("i = %i, j = %i\n", i, j);

}
return 0;
}
Output:

Infinite For Loop
#include <stdio.h>
int main() {
for ( ; ; ) {
printf("Infinite Loop!\n");
}
return 0;
}
Infinitive for loop in C
To make a for loop infinite, we need not give any expression in the syntax. Instead of that,
we need to provide two semicolons to validate the syntax of the for loop. This will work as an
infinite for loop.

Nested For

2
2) While Loop
while (expression) {
statement;
}
Syntax: Example:
1
3
4
int x = 0
while (x != 50) {
printf("Hello");
x += 1;
}

While Loop – Example
#include <stdio.h>
int main()
{
long dividend, divisor;
char ch = 'y';
while (ch != 'n')
{
printf("Enter dividend: ");
scanf("%i", &dividend);
printf("Enter divisor: ");
scanf("%i", &divisor);
printf("Result is %f", dividend / static_cast<float>(divisor));
printf(", quotient is %i", dividend / divisor);
printf(", remainder is %i\n", dividend % divisor);
printf("\nDo another (y/n)? "); // do it again?
scanf(" %c", &ch);
}
return 0;
}

2) While Loop – How it works?

3) Do-While Loop
oThe do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of
several parts of the statements. The do-while loop is mainly used in the case where we need to
execute the loop at least once.
do {
// codetobeexecuted
} while (condition);
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Hello World\n");
count++;
} while (count <= 10); // stop condition
return 0;
}

int x = 0
do {
printf("Hello");
x = x + 1;
} while (x < 50);
2
3) Do-While Loop – Example
Example:
1
3
4

Which type of loop to use?
–The for loop is appropriate when you know in advance how many times the
loop will be executed.
–The while and do while loops are used when you don’t know in advance
when the loop will terminate.
–The while loop when you may not want to execute the loop body even once.
–The do while loop when you’re sure you want to execute the loop body at
least once.

Task 3
–Write a C Program of a calculator using do-while loop.

Break Statement
–The break is a keyword in C which is used to bring the program control
out of the loop or switch.
–The break statement breaks the loop one by one, i.e., in the case of
nested loops, it breaks the inner loop first and then proceeds to outer
loops.
– The break statement in C can be used in the following two scenarios:
•With switch case
•With loops

Break Statement (Cont.)

Break Statement – Example
#include <stdio.h>
int main() {
int i;
for(i = 0; i < 10; i = i + 1) {
printf("%d ", i);
if (i == 5)
break;
}
printf("came outside of loop i = %d", i);
return 0;
}

Continue Statement
●The continue statement in C language is used to bring the program
control to the beginning of the loop.
●The continue statement skips some lines of code inside the loop and
continues with the next iteration.
●It is mainly used for a condition so that we can skip some code for a
particular condition.

Continue Statement (Cont.)

Continue Statement (Cont.)
#include <stdio.h>
int main() {
int i;
for(i = 0; i < 10; i = i + 1) {
printf("%d\n", i);
if (i == 5)
continue;
}
return 0;
}

Arrays in C
–An array is a multiple values of the same data type that can be stored
with only one variable name.
–The use of arrays allows for the development of smaller and more clearly
readable programs.
A
B
C
D
E
F
0
1
2
3
4
5
Array indices generally start with zero;
the first element of an array is zero
elements away from the start, the
next is one element away from the
start, and so on.
Tip:

Arrays in C (Cont.)
–Consider a scenario where you need to store 100 students scores in the exam
and then calculate the average.
int student1, student2, student3 … student100;
scanf("%i", student1);
scanf("%i", student2);

scanf("%i", student100);
float average = (student1 + student2 + student3
…. student100) / 100.0
Why don't we have a single
variable that holds all the
students variables ?!

Arrays in C (Cont.)
A
rr
ay
30 89 97 89 68 22 17 63 55 40
0 1 2 3 4 5 6 7 8 9
Array Length = 10
First Index = 0
Last index = 9
← Array indices
← Array values
int arr[10];
Tip: Arrays in programming are similar to vectors or matrices in
mathematics.
All the array elements occupy
contiguous space in memory.
name no. elements
The topmost element is arr[9], there’s no arr[10]

Total size of the array
#include <stdio.h>
int main()
{
int arr[5]= { 10, 20, 30, 40, 50 };
printf("Total size of arr: %i\n", sizeof(arr)); // 5 ints * 4 bytes
for(inti = 0; i < 5; i++)
printf("%i\n", arr[i]);
return 0;
}
–It’s not feasible to enter the size of the array statically, thus, there should be away
to use a dynamic way.

No. elements in the array
#include <stdio.h>
int main() {
// Index: 0 1 2 3 4
int arr[5] = { 10, 20, 30, 40, 50 };
int no_elements = sizeof(arr) / sizeof(int);
printf("No. Elements: %i\n", no_elements);
for(inti = 0; i < no_elements; i++)
printf("%i\n", arr[i]);
return 0;
}
Example:

/*
no. elements = 5 integers
size of int = 4 bytes
total size = no. elements x size of int
= 5 4
= 20 bytes
no. elements = total size / size of int
= 20 / 4
= 5

*/

Contiguous space in memory
#include <stdio.h>
int main() {
int arr[5];
printf("Size of int: %i\n", sizeof(int));
for(inti = 0; i < 5; i++)
printf("Address of arr[%d] is %p\n", i, &arr[i]);
return 0;
}
Example:

Accessing array elements
A
rr
ay
40 55 63 17 22 68 89 97 89 30
0 1 2 3 4 5 6 7 8 9
Index = 8arr[8];
–You can use array subscript (or index) to access any element stored in an array,
by using a numeric index in square brackets [] .
arr[5];

Accessing array elements
–Arrays are a real convenience for many problems, but there is not a lot that C will
do with them for you automatically.
–In particular, you can neither set all elements of an array a once nor assign one
array to another; both of the assignments
arr = 0; /* WRONG */
int arr2[10];
arr2 = arr; /* WRONG */
for(inti =0; i <10; i++)
arr[i] =0;
for(inti =0; i <10; i++)
arr2[i] =arr[i];
illegal
legal

Index out of bounds
–There's no index out of bounds checking in C/C++, thus, it may produce
unexpected output when using an out of bound index.
// This C program compiles fine as index out of bound is not checked in C.
#include <stdio.h>
int main() {
int arr[2];
printf("%d ", arr[3]);
printf("%d ", arr[-2]);
return 0;
}

Array Declaration
–It’s possible to initialize some or all elements of an array when the array is
defined.
int arr[10] = {40, 55, 63, 17, 22, 68, 89, 97, 89, 30};
int arr[10] = {40, 55, 63, 17, 22, 68, 89};
9 8 7 6 5 4 3 2 1 0← index
int arr[] = {40, 55, 63, 17, 22};
Same as arr[5]

Array Declaration
–It is possible to initialize some or all elements of an array when the array is
defined.
int a[10] = {40, 55, 63, 17, 22, 68, 89, 97, 89, 30};
int a[10] = {40, 55, 63, 17, 22, 68, 89};
0 1 2 3 4 5 6 7 8 9 ← index
int a[] = {40, 55, 63, 17, 22};
Tip: Arrays are not limited to type int; you can have arrays of char or double or any other
type, but keep in mind that all the elements should be of the same data type.

Initializing and Printing array elements
–Arrays are a real convenience for many problems, but there is not a lot that C will
do with them for you automatically.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(int);
printf("Size of arr[] = %d\n", size);
for(inti = 0; i < size; i++)
printf("arr[%d] = %d\n", i, arr[i]);
return 0;
}

#include <iostream>
using namespace std;
int main()
{
int month, day, total_days;
int days_per_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
cout << "\nEnter a month (1 to 12): "; //get date
cin >> month;
cout << "Enter a day (1 to 31): " ;
cin >> day;
total_days = day; //separate days
for (int j = 0; j < month - 1; j++) //add days each month
total_days += days_per_month[j];
cout << "Total days from start of year is: " << total_days << endl;
return 0;
}

Arrays of Arrays (Multidimensional Arrays)
–We can use array of arrays which is organized as matrices and can be represented
as a collection of rows and columns.
0 1 2
0 405563
1 172268
2 899789
3 301527
Columns
Rows
int arr[4][3] = { {40, 55, 63}, {17, 22, 68}, {89, 97, 89}, {30, 15, 27} };
0 1 2 3
0 1 2 0 1 2 0 1 2 0 1 2
•In the 1D array, we don't need to specify the size of the array if the
declaration and initialization are being done simultaneously.
•However, this will not work with 2D arrays, you have to define at
least the second dimension of the array.

Printing the ND array elements
#include <stdio.h>
int main() {
int arr[][3] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
int rows = sizeof(arr) / sizeof(arr[0]);
int columns = sizeof(arr[0]) / sizeof(arr[0][0]);
for(inti = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
return 0;
}

Array of Strings
#include <stdio.h>
int main()
{
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string
//array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
for (int j = 0; j < DAYS; j++) //display every string
printf("%s\n", star[j]);
return 0;
}

Strings in C
–In C programming, a string is a sequence/array of characters
terminated with a null character \0.
Hello World\0
char c[] = "Hello World";
End of string
char c[] = "abcd";
char c[50] = "abcd";
char c[] = { 'a', 'b', 'c', 'd', '\0' };
char c[5] = { 'a', 'b', 'c', 'd', '\0' };
← index0 1 2 3 4 5 6 7 8 9 10 11

Strings in C
char c[100];
c = "C programming"; // Error!
#include <stdio.h>
int main() {
char name[20];
printf("Enter name: ");
scanf("%s", name); // no & used
printf("Your name is %s.", name);
return 0;
}
1
2

Printing String Values
#include <stdio.h>
int main()
{
char str[] = "Hello World!";
// Method #1
printf("str = %s\n", str);
// Method #2
for (int i = 0; i < sizeof(str) / sizeof(char); ++i)
printf("%c", str[i]);
return 0;
}

A more efficient way
#include <stdio.h>
int main()
{
char str[] = "Hello World!";
// Method #1
printf("str = %s\n", str);
// Method #2
for (int i = 0, arr_size = sizeof(str) / sizeof(char); i < arr_size; ++i)
printf("%c", str[i]);
return 0;
}

Strings in C
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}

More about strings
–Note that that character ‘H’ is different from the string “H”.
char str[] = "Hello";
str[0] = "H";
char str[] = "Hello";
str[0] = 'H';
/* WRONG */ /* VALID */
–To convert a string to int you can the function atoi().
#include <stdlib.h>
char str[] = "123";
int x = atoi(str);

More about strings
–The following is correct since we are dealing with character representation of
digits ('0' to '9'). Characters in C are represented by their ASCII values, and
the ASCII value of character '0' is 48, '1' is 49, and so on.
–In other words, you subtract the ASCII value.
printf("%i", '1' - '0');
char state[5][3] = {"AA","BB","CC","DD","EE" };
–Strings multidimensional array:

Strings in C
–Commonly used String functions
strlen() calculates the length of a string
strcpy() copies a string to another
strcmp() compares two strings
strcat() concatenates two strings
#include <string.h>

strlen() – Length of the string
#include <stdio.h>
#include <string.h>
int main() {
char name[] = "Mohamed Gamal";
printf("The length is: %d", strlen(name));
return 0;
}
ostrlen(): returns the actual string size, excluding \0.
osizeof(): return the string size, including \0.

Example
#include <stdio.h>
#include <string.h> //for strlen()
int main()
{ //initialized string
char str1[] = "Oh, Captain, my Captain! our fearful trip is done" ;
char str2[80]; //empty string
int j;
for (j = 0; j < strlen(str1); j++) //copy strlen characters
str2[j] = str1[j]; // from str1 to str2
str2[j] = '\0'; //insert NULL at end
printf("%s", str2); //display str2
return 0;
}

strcpy() – Copy a string into another
#include <stdio.h>
#include <string.h>
int main() {
char name[] = "Mohamed Gamal";
char copy[14];
strcpy(copy, name); // destination, source
printf("Source string: %s", name);
printf("Copied string: %s", copy);
return 0;
}

strcmp() – Compare two strings
#include <stdio.h>
#include <string.h>
int main() {
char name1[] = "Mohamed Gamal";
char name2[] = "Thomas Jack";
int result = strcmp(name1, name2); // 0: same, otherwise: different
if (result == 0) {
printf("They are the same!");
}
else {
printf("They are different!");
}
return 0;
}

strcat() – Concatenate two strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Mohamed ";
char str2[] = "Gamal";
// Concatenate str1 and str2, the result is stored in str1.
strcat(str1, str2);
printf("Concated String: %s", str1);
return 0;
}

Operators Shortcuts
–C provides another set of shortcuts, in their simplest forms, they
look like this:
++i or i++ or i += 1 Add 1 to i
--i or i-- or i -= 1 Subtract 1 from i
i *= 2 Multiply i by 2
i /= 2 Divide i by 2
int i = 5;
printf("%d", i++);
int i = 5;
printf("%d", ++i);
Prefix
Infix
Postfix
Tip: be careful when using such operators since they may be ambiguous sometimes.

Exercises
1.Which of the following terms describes data that remains the same
throughout a program?
a)Constant
b)Variable
c)Integer
d)float
2.Which data type uses the most memory and provides the more
precision?
a)float
b)char
c)int
d)double

Exercises
3.Which data type does not support fractional values?
a)float
b)int
c)long float
d)double
4.Which data type requires only one byte of memory?
a)char
b)int
c)float
d)double

Exercises
5.Which of the following are valid variable names?
a)sam
b)SAM
c)hi_cost
d)9%d4
e)howdoyoudothis
6.List some rules for forming variables names.
7.Explain the two different usages of division operator with int and
float data types.

Exercises
8.Which of the following is the correct order of evaluation for the
below expression?
z = x + y * z / 4 % 2 – 1
a)/ % + - =
b)= * / % + -
c)/ * % - + =
d)* % / - + =

Exercises
9.What value is returned by the following code fragment?
int i = 7, y = 0;
y = y + i;
if(i < 8)
printf("The value is less than eight.\n");
a)7
b)The value is less than eight.
c)8
d)No value is returned, since the test is false.

Exercises
10. What would this code print?
for(inti = 0; i < 3; i = i + 1)
printf("a\n");
printf("b\n");
printf("c\n");

Exercises
10.How many times will the following message be printed?
int x, y;
for(x = 10, y = 0; x < 100; x = x + 10, y = y + 1)
printf("x = %d\n", x);
a)1 time
b)9 times
c)10 times
d)100 times

Exercises
1.Which data type is used for array subscripts (i.e., indices)?
a)char only
b)int only
c)char and int only
d)int, float, and char only
2.Given the following code fragment, what is the value of arg1[5]?
int arg1[] = {1, 2, 3, 4, 5};
a)0
b)4
c)5
d)Not a meaningful value.

Exercises
3.Given the following code fragment, which of the following is correct?
num[3] = 9;
--num[3];
a)num[3] = 9
b)num[2] = 9
c)num[3] = 8
d)num[2] = 8

Exercises
3.Which of the following declares a float array called worksheet[], with
30 rows and 50 columns?
a)float worksheet array[30][50];
b)float worksheet[50][30];
c)float worksheet[30][50];
d)worksheet[30][50] = float;
4.The shorthand expression for x = x + 10 is:
a)x += 10;
b)+x = 10;
c)x =+ 10;
d)x = 10+;

End of lecture 3
Thank You!