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

Day 2 - Workshop - C Programming

The document outlines a workshop on C programming covering various topics including conditional statements (if, else, switch), loops (while, do-while, for), and arrays. It provides syntax examples and explanations for each concept, demonstrating how to implement them in code. Additionally, it discusses the use of break and continue statements within loops.

Uploaded by

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

Day 2 - Workshop - C Programming

The document outlines a workshop on C programming covering various topics including conditional statements (if, else, switch), loops (while, do-while, for), and arrays. It provides syntax examples and explanations for each concept, demonstrating how to implement them in code. Additionally, it discusses the use of break and continue statements within loops.

Uploaded by

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

Workshop - C

Programming :
Day - 02
Day : 02
Index : Duration : 8 Hours

● C If...Else

● C Switch

● C While Loop

● C For Loop

● C Break/Continue

● C Arrays

● C Strings

● C User Input
1. C If...Else :

Conditions and If Statements :


We have learned from the operators, that C supports the usual logical conditions
from mathematics:
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
● Equal to : a == b
● Not Equal to: a != b
1. C If...Else :

You can use these conditions to perform different actions for different decisions.
C has the following conditional statements:
● Use if to specify a block of code to be executed, if a specified
condition is true
● Use else to specify a block of code to be executed, if the same
condition is false
● Use else if to specify a new condition to test, if the first condition is
false
● Use switch to specify many alternative blocks of code to be executed
1.1. The if Statement : Use the if statement to specify a block of C code to be executed if a condition is true.

Syntax for if statement:

if (condition){
if (condition){
//// block
block of codeof code
to be to if
executed betheexecuted
condition is if
true the condition is true
}
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two variables to find out if x is greater than y. If the condition is true, print some text:

Input : Output :

int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
1.1. The if Statement : Use the if statement to specify a block of C code to be executed if a condition is true.

Syntax for if statement:

if (condition){
if (condition){
//// block
block of codeof code
to be to if
executed betheexecuted
condition is if
true the condition is true
}
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two variables to find out if x is greater than y. If the condition is true, print some text:

Input : Output :

int x = 20; x is greater than y

int y = 18;
if (x > y) {
printf("x is greater than y");
}
1.2. Else Statement : Use the else statement to specify a block of code to be executed if the condition is false.

Syntax for else statement :

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Input : Output :

int time = 20;


if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
1.2. Else Statement : Use the else statement to specify a block of code to be executed if the condition is false.

Syntax for else statement :

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Input : Output :

int time = 20; Good evening.

if (time < 18) {


printf("Good day.");
} else {
printf("Good evening.");
}
1.3. Else if Statement : Use the else if statement to specify a new condition if the first condition is false.

Syntax for else if statement :


if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Input : Output :

int time = 22;


if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
1.3. Else if Statement : Use the else if statement to specify a new condition if the first condition is false.

Syntax for else if statement :


if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Input : Output :

int time = 22; Good evening.


if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
2. C Switch :
● Instead of writing many if..else statements, you can use the switch statement.
● The switch statement selects one of many code blocks to be executed:

Syntax for switch statement :


This is how it works:
switch(expression)
{ ● The switch expression is evaluated once

case x: ● The value of the expression is compared with the


// code block values of each case
break; ● If there is a match, the associated block of code is
case y: executed
// code block ● The break statement breaks out of the switch block
break;
and stops the execution
default:
● The default statement is optional, and specifies
// code block
some code to run if there is no case match
}
2. C Switch :
● The example below uses the weekday number to calculate the weekday name:

Input code :

int day = 4; case 6:


Output :
switch (day) {
printf("Saturday");
case 1:
break;
printf("Monday");
break; default :
case 2: printf("Sunday");
printf("Tuesday"); }
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
2. C Switch :
● The example below uses the weekday number to calculate the weekday name:

Input code :

int day = 4; case 6:


Output :
switch (day) {
printf("Saturday");
case 1: Thursday
break;
printf("Monday");
break; default :
case 2: printf("Sunday");
printf("Tuesday"); }
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
2. C Switch :
2.1. The break Keyword :

● When C reaches a break keyword, it breaks out of the switch block.


● This will stop the execution of more code and case testing inside the block.
● When a match is found, and the job is done, it's time for a break. There is no need for more testing.
● A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.

2.2. The default Keyword :

● The default keyword specifies some code to run if there is no case match.

Example is seen in previous example.


3. C While Loop :
Loops :

● Loops can execute a block of code as long as a specified condition is reached.


● Loops are handy because they save time, reduce errors, and they make code more readable.

3.1. While Loop :

● The while loop loops through a block of code as long as a specified condition is true:

Syntax for while loop :

while (condition)
{
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Input Code :
Output :
#include <stdio.h>

int main() {
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
return 0;
}

Note: Do not forget to increase the variable used in the condition (i++), otherwise the loop will never end!
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Input Code :
Output :
#include <stdio.h>
0
1
int main() { 2
int i = 0; 3
while (i < 5) { 4
printf("%d\n", i);
i++;
}
return 0;
}

Note: Do not forget to increase the variable used in the condition (i++), otherwise the loop will never end!
3.2. The Do/While Loop :

● The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax for do while :

do
{
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the
code block is executed before the condition is tested:

Input code :

#include <stdio.h> Output :

int main()
{
int i = 0;
do
{
printf("%d\n", i);
Do not forget to increase the variable used in the
i++;
condition, otherwise the loop will never end!
} while (i < 5);
return 0;
}
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the
code block is executed before the condition is tested:

Input code :

#include <stdio.h> Output :

int main() 0
1
{
2
int i = 0;
3
do 4
{
printf("%d\n", i);
Do not forget to increase the variable used in the
i++;
condition, otherwise the loop will never end!
} while (i < 5);
return 0;
}
4. C For Loop :
When you know exactly how many times you want to loop through a block of code, use the
for loop instead of a while loop:

Syntax of for statement :

for (statement
for (statement1; 1;
statement 2; statement
statement 3) { 3)
2; statement
{ // code block to be executed
// code block to be executed
}
}

● Statement 1 is executed (one time) before the execution of the code block.
● Statement 2 defines the condition for executing the code block.
● Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:

Input code : Output :


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

Example explained :
● Statement 1 sets a variable before the loop starts (int i = 0).
● Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again,
if it is false, the loop will end.
● Statement 3 increases a value (i++) each time the code block in the loop has been executed.
The example below will print the numbers 0 to 4:

Input code : Output :


#include <stdio.h>
0
int main()
1
{
2
int i;
for (i = 0; i < 5; i++)
3
{
4
printf("%d\n", i);
}
return 0;
}

Example explained :
● Statement 1 sets a variable before the loop starts (int i = 0).
● Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again,
if it is false, the loop will end.
● Statement 3 increases a value (i++) each time the code block in the loop has been executed.
5. C Break/Continue :
5.1. Break :

● You have already seen the break statement used earlier, It was used to "jump out" of a switch statement.
● The break statement can also be used to jump out of a loop.

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

Input code :
Output :

int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
break;
}
printf("%d\n", i);
}
5. C Break/Continue :
5.1. Break :

● You have already seen the break statement used earlier, It was used to "jump out" of a switch statement.
● The break statement can also be used to jump out of a loop.

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

Input code :
Output :

int i; 0
1
for (i = 0; i < 10; i++) {
2
if (i == 4) { 3
break;
}
printf("%d\n", i);
}
5. C Break/Continue :
5.2. Continue :

● The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in
the loop.

This example skips the value of 4:

Input code :
Output :

int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf("%d\n", i);
}
5. C Break/Continue :
5.2. Continue :

● The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in
the loop.

This example skips the value of 4:

Input code :
Output :

int i; 0
1
for (i = 0; i < 10; i++) {
2
if (i == 4) { 3
continue; 5
6
}
7
printf("%d\n", i); 8
} 9
6. C Arrays :

Arrays :

● Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

● To create an array, define the data type (like int) and specify the name of the array followed by square brackets [].

● To insert values to it, use a comma-separated list, inside curly braces:

Syntax for array :

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


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

We have now created a variable that holds an array of four integers.


6. C Arrays :
6.1. Access the Elements of an Array :

● To access an array element, refer to its index number.


● Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example :
Output :
#include <stdio.h>

int main()
{
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);

return 0;
}

● This statement accesses the value of the first element [0] in myNumbers.
6. C Arrays :
6.1. Access the Elements of an Array :

● To access an array element, refer to its index number.


● Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example :
Output :
#include <stdio.h>
25
int main()
{
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);

return 0;
}

● This statement accesses the value of the first element [0] in myNumbers.
6. C Arrays :
6.2. Change an Array Element :

● To change the value of a specific element, refer to the index number:


Example : Output :

#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
printf("MyNumber[0] = %d \n", myNumbers[0]);

myNumbers[0] = 33;
printf("MyNumber[0] = %d \n", myNumbers[0]);

return 0;
}

● This statement changes the value of the first element [0] in myNumbers.
6. C Arrays :
6.2. Change an Array Element :

● To change the value of a specific element, refer to the index number:


Example : Output :

#include <stdio.h> MyNumber[0] = 25


int main() { MyNumber[0] = 33
int myNumbers[] = {25, 50, 75, 100};
printf("MyNumber[0] = %d \n", myNumbers[0]);

myNumbers[0] = 33;
printf("MyNumber[0] = %d \n", myNumbers[0]);

return 0;
}

● This statement changes the value of the first element [0] in myNumbers.
6. C Arrays :
6.3. Loop Through an Array :

● You can loop through the array elements with the for loop.
● The following example outputs all elements in the myNumbers array:

Example : Output :

#include <stdio.h>

int main() {
int myNumbers[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++)
{
printf("Array at location = %d : value = %d\n",
i,myNumbers[i]);
}
return 0;
}
6. C Arrays :
6.3. Loop Through an Array :

● You can loop through the array elements with the for loop.
● The following example outputs all elements in the myNumbers array:

Example : Output :

#include <stdio.h> Array at location = 0 : value = 25


Array at location = 1 : value = 50
int main() { Array at location = 2 : value = 75
int myNumbers[] = {25, 50, 75, 100}; Array at location = 3 : value = 100
int i;
for (i = 0; i < 4; i++)
{
printf("Array at location = %d : value = %d\n",
i,myNumbers[i]);
}
return 0;
}
6. C Arrays :
6.4. Set Array Size :

● Another common way to create arrays, is to specify the size of the array, and add elements later:
Example :
Output :
#include <stdio.h>
int main()
{
// Declare an array of four integers:
int myNumbers[4];
// Add elements to it
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
printf("%d\n", myNumbers[0]);
return 0;
}
6. C Arrays :
6.4. Set Array Size :

● Another common way to create arrays, is to specify the size of the array, and add elements later:
Example :
Output :
#include <stdio.h>
int main() 25
{
// Declare an array of four integers:
int myNumbers[4]; Note :
// Add elements to it ● Using this method, you should know the size of
myNumbers[0] = 25;
the array, in order for the program to store
enough memory.
myNumbers[1] = 50;
● You are not able to change the size of the array
myNumbers[2] = 75;
after creation.
myNumbers[3] = 100;
printf("%d\n", myNumbers[0]);
return 0;
}
7. C Strings :

Strings :

● Strings are used for storing text/characters.

● For example, "Hello World" is a string of characters.

● Unlike many other programming languages, C does not have a String type to easily create string variables. However, you can use

the char type and create an array of characters to make a string in C:

Syntax for string in C :

char greetings[] = "Hello World!";


char greetings[] = "Hello World!";

Note that you have to use double quotes.


7. C Strings :

Example : Output :

#include <stdio.h>

int main()
{
char greetings[] = "Hello World!";
printf("%s", greetings);

return 0;
}
7. C Strings :

Example : Output :

#include <stdio.h> Hello World!

int main()
{
char greetings[] = "Hello World!";
printf("%s", greetings);

return 0;
}
7. C Strings :
7.1. Access Strings :
● Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets [].
● This example prints the first character (0) in greetings:
Example : Output :

#include <stdio.h>
int main()
{
char greetings[] = "Hello World!";

printf("greetings[0] = %c \n", greetings[0]);


printf("greetings[1] = %c \n", greetings[1]);
printf("greetings[2] = %c \n", greetings[2]);
printf("greetings[3] = %c \n", greetings[3]);
printf("greetings[4] = %c \n", greetings[4]);

return 0;
}
7. C Strings :
7.1. Access Strings :
● Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets [].
● This example prints the first character (0) in greetings:
Example : Output :

#include <stdio.h> greetings[0] = H


int main() greetings[1] = e
{ greetings[2] = l
char greetings[] = "Hello World!"; greetings[3] = l
greetings[4] = o
printf("greetings[0] = %c \n", greetings[0]);
printf("greetings[1] = %c \n", greetings[1]);
Note : That we have to use the “%c” format specifier to print a
printf("greetings[2] = %c \n", greetings[2]);
single character.
printf("greetings[3] = %c \n", greetings[3]);
printf("greetings[4] = %c \n", greetings[4]);

return 0;
}
7. C Strings :
7.2. Modify Strings :

● To change the value of a specific character in a string, refer to the index number, and use single quotes:

Example : Output :

#include <stdio.h>

int main()
{
char greetings[] = "Hello World!";
printf("Before : %s \n ", greetings);
greetings[0] = 'J';
printf("After : %s \n", greetings);
return 0;
}
7. C Strings :
7.2. Modify Strings :

● To change the value of a specific character in a string, refer to the index number, and use single quotes:

Example : Output :

#include <stdio.h> Before : Hello World!


After : Jello World!

int main()
{
char greetings[] = "Hello World!";
printf("Before : %s \n ", greetings);
greetings[0] = 'J';
printf("After : %s \n", greetings);
return 0;
}
7. C Strings :
7.3. Another Way Of Creating Strings :
● In the examples above, we used a "string literal" to create a string variable. This is the easiest way to create a string in C.

● You should also note that you can to create a string with a set of characters. This example will produce the same result as the one above:

Example : Output :

#include <stdio.h>
int main()
{
char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ',
'W', 'o', 'r', 'l', 'd', '!', '\0'};

char greetings2[] = "Hello World!";


printf("greetings = %s \n", greetings);
printf("greetings2 = %s \n", greetings2);
return 0;

}
7. C Strings :
7.3. Another Way Of Creating Strings :
● In the examples above, we used a "string literal" to create a string variable. This is the easiest way to create a string in C.

● You should also note that you can to create a string with a set of characters. This example will produce the same result as the one above:

Example : Output :

#include <stdio.h> greetings = Hello World!


int main() greetings2 = Hello World!
{
char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ',
'W', 'o', 'r', 'l', 'd', '!', '\0'}; Why do we include the \0 character at the end?
● This is known as the "null terminating character", and must
char greetings2[] = "Hello World!";
printf("greetings = %s \n", greetings); be included when creating strings using this method. It
printf("greetings2 = %s \n", greetings2); tells C that this is the end of the string.
return 0;

}
7. C Strings :
7.3. Another Way Of Creating Strings :
● In the examples above, we used a "string literal" to create a string variable. This is the easiest way to create a string in C.

● You should also note that you can to create a string with a set of characters. This example will produce the same result as the one above:

Example :
Differences :

char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', ● The difference between the two ways of creating strings, is
'W', 'o', 'r', 'l', 'd', '!', '\0'};
that the first method is easier to write, and you do not have
char greetings2[] = "Hello World!";
to include the \0 character, as C will do it for you.
printf("%lu\n", sizeof(greetings)); // Outputs 13
● You should note that the size of both arrays is the same:
printf("%lu\n", sizeof(greetings2)); // Outputs 13

They both have 13 characters (space also counts as a

character by the way), including the \0 character:


8. C User Input :
● You have already learned that printf() is used to output values in C.
● To get user input, you can use the scanf() function:

Example : Output :

#include <stdio.h>
int main()
{

// Create an integer variable that will store the number we get from
the user
int myNum;

// Ask the user to type a number


printf("Type a number and press enter: \n");

// Get and save the number the user types


scanf("%d", &myNum);

// Print the number the user typed


printf("Your number is: %d", myNum);
return 0;
}
8. C User Input :
● You have already learned that printf() is used to output values in C.
● To get user input, you can use the scanf() function:

Example : Output :

#include <stdio.h> Type a number and press enter:


int main() 10
{ Your number is: 10
// Create an integer variable that will store the number we get from
the user Note :
int myNum; ● The scanf() function takes two arguments: the format
specifier of the variable (%d in the example above)
// Ask the user to type a number
and the reference operator (&myNum), which stores
printf("Type a number and press enter: \n");
the memory address of the variable.
// Get and save the number the user types ● Tip: You will learn more about memory addresses and
scanf("%d", &myNum); functions in the next chapter.

// Print the number the user typed


printf("Your number is: %d", myNum);
return 0;
}
8. C User Input :
Example :
Output :
#include <stdio.h>

int main() {
// Create a string
char firstName[30];

// Ask the user to input some text


printf("Enter your first name: \n");

// Get and save the text


scanf("%s", firstName);

// Output the text


printf("Hello %s.", firstName);

return 0;
}
8. C User Input :
Example :
Output :
#include <stdio.h>
Enter your first name and press enter:
Yash
int main() { Hello Yash.
// Create a string
char firstName[30];

// Ask the user to input some text


printf("Enter your first name: \n"); Note :

● You must specify the size of the string/array (we used


// Get and save the text
scanf("%s", firstName); a very high number, 30, but atleast then we are certain

// Output the text it will store enough characters for the first name), and
printf("Hello %s.", firstName);
you don't have to specify the reference operator (&)
return 0;
}
when working with strings in scanf().
Thank You!!

You might also like