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!

More Related Content

PPTX
What is c
PDF
04-Looping( For , while and do while looping) .pdf
PPTX
Fundamentals of computer programming by Dr. A. Charan Kumari
PPTX
Control structure of c
PPTX
the refernce of programming C notes ppt.pptx
PPTX
Claguage 110226222227-phpapp02
What is c
04-Looping( For , while and do while looping) .pdf
Fundamentals of computer programming by Dr. A. Charan Kumari
Control structure of c
the refernce of programming C notes ppt.pptx
Claguage 110226222227-phpapp02

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

PPTX
COM1407: Program Control Structures – Repetition and Loops
DOCX
Core programming in c
PPT
An imperative study of c
PPT
12 lec 12 loop
PPTX
CHAPTER 5
PDF
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
PDF
C programing Tutorial
PPTX
Chapter1.pptx
PPTX
CPP Homework Help
PDF
C faq pdf
PPS
pointers 1
PPTX
C language
PPT
Introduction to Basic C programming 01
PDF
Cse115 lecture08repetitionstructures part02
PDF
C++ in 10 Hours.pdf.pdf
PPTX
3. chapter ii
PDF
5 c control statements looping
PDF
PCA-2 Programming and Solving 2nd Sem.pdf
DOCX
PCA-2 Programming and Solving 2nd Sem.docx
DOC
Assignment c programming
COM1407: Program Control Structures – Repetition and Loops
Core programming in c
An imperative study of c
12 lec 12 loop
CHAPTER 5
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
C programing Tutorial
Chapter1.pptx
CPP Homework Help
C faq pdf
pointers 1
C language
Introduction to Basic C programming 01
Cse115 lecture08repetitionstructures part02
C++ in 10 Hours.pdf.pdf
3. chapter ii
5 c control statements looping
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.docx
Assignment c programming
Ad

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

PDF
PDF
PDF
PDF
Understanding Convolutional Neural Networks (CNN)
PDF
PDF
Complier Design - Operations on Languages, RE, Finite Automata
PDF
Object Oriented Programming (OOP) using C++ - Lecture 5
PDF
Object Oriented Programming (OOP) using C++ - Lecture 2
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Understanding Convolutional Neural Networks (CNN)
Complier Design - Operations on Languages, RE, Finite Automata
Object Oriented Programming (OOP) using C++ - Lecture 5
Object Oriented Programming (OOP) using C++ - Lecture 2
Object Oriented Programming (OOP) using C++ - Lecture 1
Object Oriented Programming (OOP) using C++ - Lecture 3
Object Oriented Programming (OOP) using C++ - Lecture 4
Ad

Recently uploaded (20)

PPTX
additive manufacturing of ss316l using mig welding
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Lecture Notes Electrical Wiring System Components
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Construction Project Organization Group 2.pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
PPT
Project quality management in manufacturing
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
web development for engineering and engineering
additive manufacturing of ss316l using mig welding
CYBER-CRIMES AND SECURITY A guide to understanding
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
UNIT 4 Total Quality Management .pptx
Internet of Things (IOT) - A guide to understanding
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
bas. eng. economics group 4 presentation 1.pptx
Lecture Notes Electrical Wiring System Components
Mechanical Engineering MATERIALS Selection
Construction Project Organization Group 2.pptx
CH1 Production IntroductoryConcepts.pptx
Project quality management in manufacturing
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Model Code of Practice - Construction Work - 21102022 .pdf
web development for engineering and engineering

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!