SlideShare a Scribd company logo
Introduction to C
Programming
By Mohamed Gamal
© Mohamed Gamal 2024
The topics of today’s lecture:
Agenda
Introduction to C Programming -Lecture 3
Loops
#include <stdio.h>
int main () {
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");
return 0;
}
What if someone asks you to print 'Hello World'
10 times?
- One way is to write the printf statement 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) {
// code to be executed
}
#include <stdio.h>
int main() {
for (int count = 1; count <= 10; count = count + 1) {
printf("%dn", count);
}
return 0;
}
Introduction to C Programming -Lecture 3
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 = %dn", 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 %in", 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("Enter a positive integer: ");
scanf("%d", &number); // Take the number
// for (Initialization ; Condition ; Inc/Dec )
for (int i = 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 = %in", 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 %in", 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
o The 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 {
// code to be executed
} while (condition);
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Hello Worldn");
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("%dn", i);
if (i == 5)
continue;
}
return 0;
}
Introduction to C Programming -Lecture 3
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.)
Array
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]
Introduction to C Programming -Lecture 3
Total size of the array
#include <stdio.h>
int main()
{
int arr[5]= { 10, 20, 30, 40, 50 };
printf("Total size of arr: %in", sizeof(arr)); // 5 ints * 4 bytes
for (int i = 0; i < 5; i++)
printf("%in", 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: %in", no_elements);
for (int i = 0; i < no_elements; i++)
printf("%in", 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: %in", sizeof(int));
for (int i = 0; i < 5; i++)
printf("Address of arr[%d] is %pn", i, &arr[i]);
return 0;
}
Example:
Accessing array elements
Array
40 55 63 17 22 68 89 97 89 30
0 1 2 3 4 5 6 7 8 9
Index = 8
arr[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(int i = 0; i < 10; i++)
arr[i] = 0;
for(int i = 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[] = %dn", size);
for (int i = 0; i < size; i++)
printf("arr[%d] = %dn", 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 40 55 63
1 17 22 68
2 89 97 89
3 30 15 27
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 (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
printf("arr[%d][%d] = %dn", 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("%sn", star[j]);
return 0;
}
Introduction to C Programming -Lecture 3
Introduction to C Programming -Lecture 3
Strings in C
– In C programming, a string is a sequence/array of characters
terminated with a null character 0.
H e l l o W o r l d 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' };
← index
0 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 = %sn", 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 = %sn", 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;
}
o strlen(): returns the actual string size, excluding 0.
o sizeof(): 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;
}
Introduction to C Programming -Lecture 3
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 (int i = 0; i < 3; i = i + 1)
printf("an");
printf("bn");
printf("cn");
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 = %dn", 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
ThankYou!
Ad

More Related Content

Similar to Introduction to C Programming -Lecture 3 (20)

COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
Hemantha Kulathilake
 
Core programming in c
Core programming in cCore programming in c
Core programming in c
Rahul Pandit
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
12 lec 12 loop
12 lec 12 loop 12 lec 12 loop
12 lec 12 loop
kapil078
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
mohd_mizan
 
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
DR B.Surendiran .
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
Mahira Banu
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
WondimuBantihun1
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
C faq pdf
C faq pdfC faq pdf
C faq pdf
DebiPanda
 
pointers 1
pointers 1pointers 1
pointers 1
gaurav koriya
 
C language
C languageC language
C language
Priya698357
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 
Cse115 lecture08repetitionstructures part02
Cse115 lecture08repetitionstructures part02Cse115 lecture08repetitionstructures part02
Cse115 lecture08repetitionstructures part02
Md. Ashikur Rahman
 
C++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdfC++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdf
SumitSingh813090
 
3. chapter ii
3. chapter ii3. chapter ii
3. chapter ii
Chhom Karath
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements looping
MomenMostafa
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdf
Ashutoshprasad27
 
PCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxPCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docx
Ashutoshprasad27
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
Icaii Infotech
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
Hemantha Kulathilake
 
Core programming in c
Core programming in cCore programming in c
Core programming in c
Rahul Pandit
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
12 lec 12 loop
12 lec 12 loop 12 lec 12 loop
12 lec 12 loop
kapil078
 
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
DR B.Surendiran .
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
Mahira Banu
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 
Cse115 lecture08repetitionstructures part02
Cse115 lecture08repetitionstructures part02Cse115 lecture08repetitionstructures part02
Cse115 lecture08repetitionstructures part02
Md. Ashikur Rahman
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements looping
MomenMostafa
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdf
Ashutoshprasad27
 
PCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxPCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docx
Ashutoshprasad27
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
Icaii Infotech
 

More from Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt (20)

How to install CS50 Library (Step-by-step guide)
How to install CS50 Library (Step-by-step guide)How to install CS50 Library (Step-by-step guide)
How to install CS50 Library (Step-by-step guide)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding Singular Value Decomposition (SVD)
Understanding Singular Value Decomposition (SVD)Understanding Singular Value Decomposition (SVD)
Understanding Singular Value Decomposition (SVD)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Linux OS (Part 2) - Tutorial
Introduction to Linux OS (Part 2) - TutorialIntroduction to Linux OS (Part 2) - Tutorial
Introduction to Linux OS (Part 2) - Tutorial
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Linux OS (Part 1) - Tutorial
Introduction to Linux OS (Part 1) - TutorialIntroduction to Linux OS (Part 1) - Tutorial
Introduction to Linux OS (Part 1) - Tutorial
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
How to use tmux in Linux - A basic tutorial
How to use tmux in Linux - A basic tutorialHow to use tmux in Linux - A basic tutorial
How to use tmux in Linux - A basic tutorial
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Getting started with neural networks (NNs)
Getting started with neural networks (NNs)Getting started with neural networks (NNs)
Getting started with neural networks (NNs)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding K-Nearest Neighbor (KNN) Algorithm
Understanding K-Nearest Neighbor (KNN) AlgorithmUnderstanding K-Nearest Neighbor (KNN) Algorithm
Understanding K-Nearest Neighbor (KNN) Algorithm
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding Convolutional Neural Networks (CNN)
Understanding Convolutional Neural Networks (CNN)Understanding Convolutional Neural Networks (CNN)
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Luhn's algorithm to validate Egyptian ID numbers
Luhn's algorithm to validate Egyptian ID numbersLuhn's algorithm to validate Egyptian ID numbers
Luhn's algorithm to validate Egyptian ID numbers
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Difference between Mean and Weighted Mean
Difference between Mean and Weighted MeanDifference between Mean and Weighted Mean
Difference between Mean and Weighted Mean
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Complier Design - Operations on Languages, RE, Finite Automata
Complier Design - Operations on Languages, RE, Finite AutomataComplier Design - Operations on Languages, RE, Finite Automata
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 5
Object Oriented Programming (OOP) using C++ - Lecture 5Object Oriented Programming (OOP) using C++ - Lecture 5
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 2
Object Oriented Programming (OOP) using C++ - Lecture 2Object Oriented Programming (OOP) using C++ - Lecture 2
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 1
Object Oriented Programming (OOP) using C++ - Lecture 1Object Oriented Programming (OOP) using C++ - Lecture 1
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 3
Object Oriented Programming (OOP) using C++ - Lecture 3Object Oriented Programming (OOP) using C++ - Lecture 3
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Operating System - Lecture 2
Introduction to Operating System - Lecture 2Introduction to Operating System - Lecture 2
Introduction to Operating System - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Operating System - Lecture 1
Introduction to Operating System - Lecture 1Introduction to Operating System - Lecture 1
Introduction to Operating System - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Operating System - Lecture 3
Introduction to Operating System - Lecture 3Introduction to Operating System - Lecture 3
Introduction to Operating System - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Freelancing - Quick Guide
Introduction to Freelancing - Quick GuideIntroduction to Freelancing - Quick Guide
Introduction to Freelancing - Quick Guide
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Ad

Recently uploaded (20)

LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
New Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdfNew Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdf
mohamedezzat18803
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
New Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdfNew Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdf
mohamedezzat18803
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Ad

Introduction to C Programming -Lecture 3

  • 1. Introduction to C Programming By Mohamed Gamal © Mohamed Gamal 2024
  • 2. The topics of today’s lecture: Agenda
  • 4. Loops #include <stdio.h> int main () { 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"); return 0; } What if someone asks you to print 'Hello World' 10 times? - One way is to write the printf statement 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
  • 5. 1) For Loop for (initialization; test condition; increment or decrement) { // code to be executed } #include <stdio.h> int main() { for (int count = 1; count <= 10; count = count + 1) { printf("%dn", count); } return 0; }
  • 7. How does For loop work?
  • 8. 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 = %dn", number, i, (number * i)); } return 0; }
  • 9. 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 %in", j); return 0; //exit from the program } printf("It's prime!"); return 0; }
  • 10. Example 3 #include <stdio.h> int main() { int number = 0, sum = 0; // Declare the variables printf("Enter a positive integer: "); scanf("%d", &number); // Take the number // for (Initialization ; Condition ; Inc/Dec ) for (int i = 1; i <= number; i++) { sum = sum + i; } printf("Sum = %d", sum); return 0; }
  • 11. Multiple Initialization and Test Expressions #include <stdio.h> int main() { for (int i = 1, j = 5; j > 0; i++, j--) { printf("i = %i, j = %in", i, j); } return 0; } Output:
  • 12. 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.
  • 14. 2 2) While Loop while (expression) { statement; } Syntax: Example: 1 3 4 int x = 0 while (x != 50) { printf("Hello"); x += 1; }
  • 15. 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 %in", dividend % divisor); printf("nDo another (y/n)? "); // do it again? scanf(" %c", &ch); } return 0; }
  • 16. 2) While Loop – How it works?
  • 17. 3) Do-While Loop o The 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 { // code to be executed } while (condition); #include <stdio.h> int main() { int count = 1; do { printf("Hello Worldn"); count++; } while (count <= 10); // stop condition return 0; }
  • 18. int x = 0 do { printf("Hello"); x = x + 1; } while (x < 50); 2 3) Do-While Loop – Example Example: 1 3 4
  • 19. 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.
  • 20. Task 3 – Write a C Program of a calculator using do-while loop.
  • 21. 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
  • 23. 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; }
  • 24. 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.
  • 26. Continue Statement (Cont.) #include <stdio.h> int main() { int i; for (i = 0; i < 10; i = i + 1) { printf("%dn", i); if (i == 5) continue; } return 0; }
  • 28. 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:
  • 29. 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 ?!
  • 30. Arrays in C (Cont.) Array 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]
  • 32. Total size of the array #include <stdio.h> int main() { int arr[5]= { 10, 20, 30, 40, 50 }; printf("Total size of arr: %in", sizeof(arr)); // 5 ints * 4 bytes for (int i = 0; i < 5; i++) printf("%in", 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.
  • 33. 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: %in", no_elements); for (int i = 0; i < no_elements; i++) printf("%in", arr[i]); return 0; } Example:
  • 34. /* 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 */
  • 35. Contiguous space in memory #include <stdio.h> int main() { int arr[5]; printf("Size of int: %in", sizeof(int)); for (int i = 0; i < 5; i++) printf("Address of arr[%d] is %pn", i, &arr[i]); return 0; } Example:
  • 36. Accessing array elements Array 40 55 63 17 22 68 89 97 89 30 0 1 2 3 4 5 6 7 8 9 Index = 8 arr[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];
  • 37. 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(int i = 0; i < 10; i++) arr[i] = 0; for(int i = 0; i < 10; i++) arr2[i] = arr[i]; illegal legal
  • 38. 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; }
  • 39. 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]
  • 40. 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.
  • 41. 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[] = %dn", size); for (int i = 0; i < size; i++) printf("arr[%d] = %dn", i, arr[i]); return 0; }
  • 42. #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; }
  • 43. 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 40 55 63 1 17 22 68 2 89 97 89 3 30 15 27 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.
  • 44. 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 (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) printf("arr[%d][%d] = %dn", i, j, arr[i][j]); return 0; }
  • 45. 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("%sn", star[j]); return 0; }
  • 48. Strings in C – In C programming, a string is a sequence/array of characters terminated with a null character 0. H e l l o W o r l d 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' }; ← index 0 1 2 3 4 5 6 7 8 9 10 11
  • 49. 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
  • 50. Printing String Values #include <stdio.h> int main() { char str[] = "Hello World!"; // Method #1 printf("str = %sn", str); // Method #2 for (int i = 0; i < sizeof(str) / sizeof(char); ++i) printf("%c", str[i]); return 0; }
  • 51. A more efficient way #include <stdio.h> int main() { char str[] = "Hello World!"; // Method #1 printf("str = %sn", str); // Method #2 for (int i = 0, arr_size = sizeof(str) / sizeof(char); i < arr_size; ++i) printf("%c", str[i]); return 0; }
  • 52. 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; }
  • 53. 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);
  • 54. 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:
  • 55. 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>
  • 56. 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; } o strlen(): returns the actual string size, excluding 0. o sizeof(): return the string size, including 0.
  • 57. 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; }
  • 58. 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; }
  • 59. 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; }
  • 60. 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; }
  • 62. 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.
  • 63. 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
  • 64. 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
  • 65. 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.
  • 66. 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) * % / - + =
  • 67. 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.
  • 68. Exercises 10. What would this code print? for (int i = 0; i < 3; i = i + 1) printf("an"); printf("bn"); printf("cn");
  • 69. 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 = %dn", x); a) 1 time b) 9 times c) 10 times d) 100 times
  • 70. 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.
  • 71. 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
  • 72. 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+;
  • 73. End of lecture 3 ThankYou!