SlideShare a Scribd company logo
1 | P a g e
Workbook #2 {Re-view of principles printf, scanf, designing a
program, definitions, sub-routines (sub functions) with main function,
numeric, string, characters, arrays, for loop, while loop, if – else
statements}
Theory (Briefing)
2 | P a g e
3 | P a g e
4 | P a g e
5 | P a g e
6 | P a g e
Draw the IPO chart and describe each part
Describe all parts of the problem analysis
7 | P a g e
Algorithm
It is a sequence of instructions to solve a problem, written in human language.
• A step-by-step procedure to solve a given problem.
• An algorithm should always have a clear stopping point
• Programmer writes the problem solving in the form of an algorithm before
coding it into computer language.
• Algorithms for making things will divide into sections: (the
parts/components/ ingredients (inputs) required to accomplish the task, the
actions/steps/methods (processing) to produce the required
outcome(output)
• Algorithm can be developed using: pseudo code (similar to programming
language)
• Flow chart
8 | P a g e
9 | P a g e
Flowchart is a graphical representation of data, information and workflow using
certain symbols that are connected to flow lines to describe the instructions
done in problem solving.
10 | P a g e
11 | P a g e
Operations
Calculations and variables
There are different operators that can be used for calculations which are listed in the following
table:
Operator Operation
+ Addition
– Subtraction
* Multiplication
/ Division
%
Modulus(Remainder of integer
division)
Now that we know the different operators, let’s calculate something:
Example 1:
int main()
{
int a, b;
a = 1;
b = a + 1;
a = b - 1;
return 0;
}
Example 2: So let’s make a program that can do all these things:
#include<stdio.h>
int main()
{
int inputvalue;
scanf("%d", &inputvalue);
inputvalue = inputvalue * 10;
printf("Ten times the input equals %dn",inputvalue);
return 0;
}
12 | P a g e
Note: The input must be a whole number (integer).
Boolean Operators
Before we can take a look at test conditions we have to know what Boolean operators are. They
are called Boolean operators because they give you either true or false when you use them to
test a condition. The greater than sign “>”
for instance is a Boolean operator.
In the table below you see all the Boolean operators:
== Equal
! Not
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
&& And
|| Or
13 | P a g e
The if-statement
The if statement can be used to test conditions so that we can alter the flow of a program. In
other words: if a specific statement is true, execute this instruction. If not true, execute this
instruction. So lets take a look at an example:
Example 3 based on if-statement
#include<stdio.h>
int main()
{
int mynumber;
scanf("%d",&mynumber);
if ( mynumber == 10 )
printf("Is equaln");
return 0;
}
Now we like to also print something if the “if statement” is not equal. We could do this by adding
another “if statement” but there is an easier / better way. Which is using the so called “else
statement” with the “if statement”.
Example 4:
#include<stdio.h>
int main()
{
int mynumber;
scanf("%d",&mynumber);
if ( mynumber == 10 )
{
printf("Is equaln");
printf("Closing programn");
}
else
{
printf("Not equaln");
printf("Closing programn");
}
return 0;
}
Note: Take a look at the placement of the curly brackets and how the indentations are placed.
This is all done to make reading easier and to make less mistakes in large programs.
14 | P a g e
Nested-if statements
If you use an “if statement” in an “if statement” it is called nesting. Nesting “if statements” can
make a program very complex, but sometimes there is no other way. So use it wisely. Take a
look at a nested “if statement” example below:
Example 5: Nested-if statements
#include<stdio.h>
int main()
{
int grade;
scanf("%d",&grade);
if ( grade <= 10 )
{
printf("YOU DID NOT STUDY.n");
printf("YOU FAILED ! n");
}
else
{
if ( grade < 60 ) {
printf("You failed n");
printf("Study hardern");
}
else
{
if ( grade >= 60 )
printf("YOU PASSED ! n");
}
}
return 0;
}
Multiple condition testing
It is possible to test two or more conditions at once in an “if statement” with the use of the AND
(&&) operator. Example:
if (a > 10 && b > 20 && c < 10 )
If a is greater then ten and b is greater then twenty and c is smaller then ten, do something. So
all three conditions must be true, before something happens.
With the OR ( || ) operator you can test if one of two conditions are true. Example:
if ( a = 10 || b < 20 )
15 | P a g e
If a equals ten or b is smaller then twenty then do something. So if a or b is true, something
happens.
The switch statement
The switch statement is almost the same as an “if statement”. The switch statement can have
many conditions. You start the switch statement with a condition. If one of the variable equals
the condition, the instructions are executed. It is also possible to add a default. If none of the
variable equals the condition the default will be executed. See the
example below:
Example 6:
#include<stdio.h>
int main()
{
char myinput;
printf("Which option will you choose:n");
printf("a) Program 1 n");
printf("b) Program 2 n");
scanf("%c", &myinput);
switch (myinput)
{
case 'a':
printf("Run program 1n");
break;
case 'b':
{
printf("Run program 2n");
printf("Please Waitn");
break;
}
default:
printf("Invalid choicen");
break;
}
return 0;
}
Note: break is used to exit the switch.
16 | P a g e
For-loop, While loop, Do-While loop, Break and Continue
In every programming language, thus also in the C programming language, there are
circumstances where you want to do the same thing many times. For instance you want to print
the same words ten times. You could type ten printf function, but it is easier to use a loop. The
only thing you have to do is to setup a loop that execute the same printf function ten times.
There are three basic types of loops which are:
▪ “for loop”
▪ “while loop”
▪ “do while loop”
The for loop
The “for loop” loops from one number to another number and increases by a specified value
each time.
The “for loop” uses the following structure:
for (Start value; continue or end condition; increase value)
statement;
Look at the example below:
Example 7:
#include<stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf ("Hellon");
printf ("Worldn");
}
return 0;
}
Note: A single instruction can be placed behind the “for loop” without the curly brackets.
Let’s look at the “for loop” from the example: We first start by setting the variable i to 0. This
is where we start to count. Then we say that the for loop must run if the counter i is smaller
then ten. Last we say that every cycle i must be increased by one (i++).
In the example we used i++ which is the same as using i = i + 1. This is called incrementing.
The instruction i++ adds 1 to i. If you want to subtract 1 from i you can use i--. It is also
possible to use ++i or --i. The difference is that with ++i (prefix incrementing) the one is added
17 | P a g e
before the “for loop” tests if i < 10. With i++ (postfix incrementing) the one is added after the
test i < 10. In case of a for loop this make no difference, but in while loop test it makes a
difference. But before we look at a postfix and prefix increment while loop example, we first look
at the while loop.
The while loop
The while loop can be used if you don’t know how many times a loop must run. Here is an
example 8
#include<stdio.h>
int main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
while ( counter < howmuch)
{
counter++;
printf("%dn", counter);
}
return 0;
}
Let’s take a look at the example: First you must always initialize the counter before the while
loop starts ( counter = 1). Then the while loop will run if the variable counter is smaller then the
variable “howmuch”. If the input is ten, then 1 through 10 will be printed on the screen. A last
thing you have to remember is to increment the counter inside the loop (counter++). If you
forget this the loop becomes infinitive.
As said before (after the for loop example) it makes a difference if prefix incrementing (++i) or
postfix incrementing (i++) is used with while loop. Take a look at the following postfix and prefix
increment while loop example:
Example 9
#include<stdio.h>
int main(void) {
int i;
i = 0;
while(i++ < 5) {
printf("%dn", i);
}
18 | P a g e
printf("n");
i = 0;
while(++i < 5) {
printf("%dn", i);
}
return 0;
}
The output of the postfix and prefix increment example will look like this:
1
2
3
4
5
1
2
3
4
i++ will increment the value of i, but is using the pre-incremented value to test against < 5.
That’s why we get 5 numbers.
++i will increment the value of i, but is using the incremented value to test against < 5. That’s
why we get 4 numbers.
The do while loop
The “do while loop” is almost the same as the while loop. The “do while loop” has the following
form:
do
{
do something;
}
while (expression);
Do something first and then test if we have to continue. The result is that the loop always runs
once. (Because the expression test comes afterward). Take a look at an example:
Example 10
#include<stdio.h>
int main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
do
19 | P a g e
{
counter++;
printf("%dn", counter);
}
while ( counter < howmuch);
return 0;
}
Note: There is a semi-colon behind the while line.
Break and continue
To exit a loop you can use the break statement at any time. This can be very useful if you want
to stop running a loop because a condition has been met other than the loop end condition. Take
a look at the following example:
Example 11:
#include<stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
if ( i == 10)
break;
}
return 0;
}
In the example above, the while loop will run, as long i is smaller then twenty. In the while loop
there is an if statement that states that if i equals ten the while loop must stop (break).
With “continue;” it is possible to skip the rest of the commands in the current loop and start
from the top again. (the loop variable must still be incremented). Take a look at the example
below:
Example 12:
#include<stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
20 | P a g e
i++;
continue;
printf("Nothing to seen");
}
return 0;
}
In the example above, the printf function is never called because of the “continue;”.
Arrays and Multi-Dimensional Arrays
In this C programming language tutorial, we are going to talk about arrays.
An array lets you declare and work with a collection of values of the same type. Let’s say you
want to declare four integers. With the knowledge from the last few tutorials you would do
something like this:
int a , b , c , d;
What if you wanted to declare a thousand variables? That will take you a long time to type. This
is where arrays come in handy. An easier way is to declare an array of four integers:
int a[4];
The four separate integers inside this array are accessed by an index. Each element can be
accessed by using square brackets with the element number inside. All arrays start at element
zero and will go to n-1. (In this case from 0 to 3). So if we want to fill each element you get
something like this:
int a[4];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
If you want to use an element, for example for printing, you can do this:
printf("%d", a[1]);
Arrays and loops
One of the nice things about arrays is that you can use a loop to manipulate each element. When
an array is declared, the values of each element are not set to zero automatically. In some cases
you want to “initialize” the array (which means, setting every element to zero). This can be done
like in the example above, but it is easier to use a loop. Here is an example:
21 | P a g e
Example 13:
#include<stdio.h>
int main()
{
int a[4];
int i;
for ( i = 0; i < 4; i++ )
a[i] = 0;
for ( i = 0; i < 4; i++ )
printf("a[%d] = %dn", i , a[i]);
return 0;
}
Multi-dimensional arrays
The arrays we have been using so far are called one-dimensional arrays.
Here is an example of an one-dimensional array:
int a[2];
0 1
1 2
Note: A one-dimensional array has one column of elements.
Two-dimensional arrays have rows and columns. See the example below:
int a[2][2];
0 1
0 1 2
1 4 5
Note: a[0][0] contains the value 1. a[0][1] contains the value 2. a[1][0] contains the value 4.
a[1][1] contains the value 5.
So let’s look at an example that initialize a two-dimensional array and prints each element:
Example 14:
22 | P a g e
#include<stdio.h>
int main()
{
int a[4][4], i , j;
for (i = 0; i < 4; i++)
{
for ( j = 0; j < 4; j++)
{
a[i][j] = 0;
printf("a[%d][%d] = %d n", i, j, a[i][j]);
}
}
return 0;
}
Note: As you can see, we use two “for loops” in the example above. One to access the rows and
the other to access the columns.
Functions and Global/Local variables
Most languages allow you to create functions of some sort. Functions are used to break up large
programs into named sections. You have already been using a function which is the main
function. Functions are often used when the same piece of code has to run multiple times.
In this case you can put this piece of code in a function and give that function a name. When
the piece of code is required you just have to call the function by its name. (So you only have
to type the piece of code once).
In the example below we declare a function with the name MyPrint. The only thing that this
function does is to print the sentence: Printing from a function. If we want to use the function
we just have to call MyPrint() and the printf statement will be executed. (Don’t forget to put the
round brackets behind the function name when you call it or declare it).
Take a look at the example 15:
#include<stdio.h>
void MyPrint()
{
printf("Printing from a function.n");
}
int main()
{
MyPrint();
return 0;
}
23 | P a g e
Parameters and return
Functions can accept parameters and can return a result. (C functions can accept an unlimited
number of parameters).
Where the functions are declared in your program does not matter, as long as a functions name
is known to the compiler before it is called. In other words: when there are two functions, i.e.
functions A and B, and B must call A, than A has to be declared in front of B.
Let’s take a look at an example where a result is returned:
Example 16
#include<stdio.h>
int Add(int output1,int output2 )
{
printf("%d", output1);
printf("%d", output2);
return output1 + output2;
}
int main()
{
int answer, input1, input2;
scanf("%d", &input1);
scanf("%d", &input2);
answer = Add(input1,input2);
printf(" answer = %dn", answer);
return 0;
}
The main() function starts with the declaration of three integers. Then the user can input two
whole numbers. These numbers are used as input of function Add(). Input1 is stored in output1
and input2 is stored in output2. The function Add() prints the two numbers onto the screen and
will return the result of output1 + output2. The return value is stored in the integer answer. The
number stored in answer is then printed onto the screen.
24 | P a g e
Void
If you don’t want to return a result from a function, you can use void return type instead of the
int.
So let’s take a look at an example of a function that will not return an integer:
void our_site()
{
printf("www");
printf(".NextDawn");
printf(".nl");
}
Note: As you can see there is not an int before our_site() and there is not a return 0; in the
function.
The function can be called by the following statement: our_site();
Global and local variables
A local variable is a variable that is declared inside a function. A global variable is a variable that
is declared outside all functions. A local variable can only be used in the function where it is
declared. A global variable can be used in all functions.
See the following example:
#include<stdio.h>
// Global variables
int A;
int B;
int Add()
{
return A + B;
}
int main()
{
int answer; // Local variable
A = 5;
B = 7;
answer = Add();
printf("%dn",answer);
return 0;
}
As you can see two global variables are declared, A and B. These variables can be used in main()
and Add().
The local variable answer can only be used in main().
Ad

More Related Content

Similar to Workbook_2_Problem_Solving_and_programming.pdf (20)

computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
eaglesniper008
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
JayBhavsar68
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
Komal Kotak
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
monicafrancis71118
 
Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
Programming basics
Programming basicsProgramming basics
Programming basics
246paa
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf
santosh147365
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
Green Ecosystem
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
Introduction to C Programming -Lecture 3
Introduction to C Programming -Lecture 3Introduction to C Programming -Lecture 3
Introduction to C Programming -Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
baabtra.com - No. 1 supplier of quality freshers
 
while loop in C.pptx
while loop in C.pptxwhile loop in C.pptx
while loop in C.pptx
VishnupriyaKashyap
 
Looping
LoopingLooping
Looping
Kathmandu University
 
C lecture 3 control statements slideshare
C lecture 3 control statements slideshareC lecture 3 control statements slideshare
C lecture 3 control statements slideshare
Gagan Deep
 
Lecture 13 Loops1 with C++ programming.PPT
Lecture 13 Loops1 with C++ programming.PPTLecture 13 Loops1 with C++ programming.PPT
Lecture 13 Loops1 with C++ programming.PPT
SamahAdel16
 
175035-cse LAB-04
175035-cse LAB-04 175035-cse LAB-04
175035-cse LAB-04
Mahbubay Rabbani Mim
 
TN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptxTN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptx
knmschool
 
Introduction to c part -1
Introduction to c   part -1Introduction to c   part -1
Introduction to c part -1
baabtra.com - No. 1 supplier of quality freshers
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
eaglesniper008
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
JayBhavsar68
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
Komal Kotak
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
monicafrancis71118
 
Programming basics
Programming basicsProgramming basics
Programming basics
246paa
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf
santosh147365
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
Green Ecosystem
 
C lecture 3 control statements slideshare
C lecture 3 control statements slideshareC lecture 3 control statements slideshare
C lecture 3 control statements slideshare
Gagan Deep
 
Lecture 13 Loops1 with C++ programming.PPT
Lecture 13 Loops1 with C++ programming.PPTLecture 13 Loops1 with C++ programming.PPT
Lecture 13 Loops1 with C++ programming.PPT
SamahAdel16
 
TN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptxTN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptx
knmschool
 

More from DrDineshenScientist (7)

sp95-chap3.pdf
sp95-chap3.pdfsp95-chap3.pdf
sp95-chap3.pdf
DrDineshenScientist
 
sp95-chap3.pdf
sp95-chap3.pdfsp95-chap3.pdf
sp95-chap3.pdf
DrDineshenScientist
 
sp95-chap3.pdf
sp95-chap3.pdfsp95-chap3.pdf
sp95-chap3.pdf
DrDineshenScientist
 
sp95-chap3.pdf
sp95-chap3.pdfsp95-chap3.pdf
sp95-chap3.pdf
DrDineshenScientist
 
sp95-chap3.pdf
sp95-chap3.pdfsp95-chap3.pdf
sp95-chap3.pdf
DrDineshenScientist
 
sp95-chap3.pdf
sp95-chap3.pdfsp95-chap3.pdf
sp95-chap3.pdf
DrDineshenScientist
 
sp95-chap3.pdf
sp95-chap3.pdfsp95-chap3.pdf
sp95-chap3.pdf
DrDineshenScientist
 
Ad

Recently uploaded (20)

NTS - Boost Your Job Search by Volunteering
NTS - Boost Your Job Search by VolunteeringNTS - Boost Your Job Search by Volunteering
NTS - Boost Your Job Search by Volunteering
Bruce Bennett
 
technical seminar Tharun.pptm.pptx by vtu students
technical seminar Tharun.pptm.pptx by vtu studentstechnical seminar Tharun.pptm.pptx by vtu students
technical seminar Tharun.pptm.pptx by vtu students
madhushreer21
 
Slideshow about color communication in groups.pptx
Slideshow about color communication in groups.pptxSlideshow about color communication in groups.pptx
Slideshow about color communication in groups.pptx
joyghassan2001
 
Omar Salim Biography Omar Salim Biography
Omar Salim Biography Omar Salim BiographyOmar Salim Biography Omar Salim Biography
Omar Salim Biography Omar Salim Biography
Omar Selim
 
Infection Control for BSc Nursing,gnm,pbbsc___.pptx
Infection Control for BSc Nursing,gnm,pbbsc___.pptxInfection Control for BSc Nursing,gnm,pbbsc___.pptx
Infection Control for BSc Nursing,gnm,pbbsc___.pptx
Bishnupriyabindhani
 
rajatseydurzruzurzuursruusuduminarppt.pptx
rajatseydurzruzurzuursruusuduminarppt.pptxrajatseydurzruzurzuursruusuduminarppt.pptx
rajatseydurzruzurzuursruusuduminarppt.pptx
YashGaur66
 
Busiensns plan 34678973783738s FPPT.pptx
Busiensns plan 34678973783738s FPPT.pptxBusiensns plan 34678973783738s FPPT.pptx
Busiensns plan 34678973783738s FPPT.pptx
AzkaRao2
 
Mac repertory.pdfgghjjmgggggggggggggglkjhk
Mac repertory.pdfgghjjmgggggggggggggglkjhkMac repertory.pdfgghjjmgggggggggggggglkjhk
Mac repertory.pdfgghjjmgggggggggggggglkjhk
vasajagadishwar1
 
Juniper JN0-224 Certification Preparation Guide with Sample Questions.pdf
Juniper JN0-224 Certification Preparation Guide with Sample Questions.pdfJuniper JN0-224 Certification Preparation Guide with Sample Questions.pdf
Juniper JN0-224 Certification Preparation Guide with Sample Questions.pdf
sabrina pinto
 
电子版成绩单英国UofG文凭格拉斯哥大学学生证学历认证范本购买
电子版成绩单英国UofG文凭格拉斯哥大学学生证学历认证范本购买电子版成绩单英国UofG文凭格拉斯哥大学学生证学历认证范本购买
电子版成绩单英国UofG文凭格拉斯哥大学学生证学历认证范本购买
Taqyea
 
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa HagenUXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA Boston
 
Microsoft 365 Copilot - Vanderbilt University
Microsoft 365 Copilot - Vanderbilt UniversityMicrosoft 365 Copilot - Vanderbilt University
Microsoft 365 Copilot - Vanderbilt University
Neil Beyersdorf - MSES | CLSSMBB | Prosci OCM
 
central nervous system brain nose mourth spinal vord
central nervous system brain nose mourth spinal vordcentral nervous system brain nose mourth spinal vord
central nervous system brain nose mourth spinal vord
MouryaGarg1
 
Interview questions for freshers by Talent Titan.pdf
Interview questions for freshers by Talent Titan.pdfInterview questions for freshers by Talent Titan.pdf
Interview questions for freshers by Talent Titan.pdf
shubhamgoel346498
 
GROUP 1 NAV.pptxhwjwhshwuwhhwhsjssjwjjwd
GROUP 1 NAV.pptxhwjwhshwuwhhwhsjssjwjjwdGROUP 1 NAV.pptxhwjwhshwuwhhwhsjssjwjjwd
GROUP 1 NAV.pptxhwjwhshwuwhhwhsjssjwjjwd
andresjohnjohn99
 
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
Taqyea
 
Coronary artery disease resident final.pptx
Coronary artery disease resident final.pptxCoronary artery disease resident final.pptx
Coronary artery disease resident final.pptx
PrashantMohanty2
 
science stream ppt ankush.injcnjd jfcdsj
science stream ppt ankush.injcnjd jfcdsjscience stream ppt ankush.injcnjd jfcdsj
science stream ppt ankush.injcnjd jfcdsj
prashantksistla
 
What To Expect When Partnering With A Retained Executive Search Firm?
What To Expect When Partnering With A Retained Executive Search Firm?What To Expect When Partnering With A Retained Executive Search Firm?
What To Expect When Partnering With A Retained Executive Search Firm?
WalkWater Talent Advisors Pvt. Ltd.
 
Department of Computer Science and Applications 1.pptx
Department of Computer Science and Applications 1.pptxDepartment of Computer Science and Applications 1.pptx
Department of Computer Science and Applications 1.pptx
panghaldharmender459
 
NTS - Boost Your Job Search by Volunteering
NTS - Boost Your Job Search by VolunteeringNTS - Boost Your Job Search by Volunteering
NTS - Boost Your Job Search by Volunteering
Bruce Bennett
 
technical seminar Tharun.pptm.pptx by vtu students
technical seminar Tharun.pptm.pptx by vtu studentstechnical seminar Tharun.pptm.pptx by vtu students
technical seminar Tharun.pptm.pptx by vtu students
madhushreer21
 
Slideshow about color communication in groups.pptx
Slideshow about color communication in groups.pptxSlideshow about color communication in groups.pptx
Slideshow about color communication in groups.pptx
joyghassan2001
 
Omar Salim Biography Omar Salim Biography
Omar Salim Biography Omar Salim BiographyOmar Salim Biography Omar Salim Biography
Omar Salim Biography Omar Salim Biography
Omar Selim
 
Infection Control for BSc Nursing,gnm,pbbsc___.pptx
Infection Control for BSc Nursing,gnm,pbbsc___.pptxInfection Control for BSc Nursing,gnm,pbbsc___.pptx
Infection Control for BSc Nursing,gnm,pbbsc___.pptx
Bishnupriyabindhani
 
rajatseydurzruzurzuursruusuduminarppt.pptx
rajatseydurzruzurzuursruusuduminarppt.pptxrajatseydurzruzurzuursruusuduminarppt.pptx
rajatseydurzruzurzuursruusuduminarppt.pptx
YashGaur66
 
Busiensns plan 34678973783738s FPPT.pptx
Busiensns plan 34678973783738s FPPT.pptxBusiensns plan 34678973783738s FPPT.pptx
Busiensns plan 34678973783738s FPPT.pptx
AzkaRao2
 
Mac repertory.pdfgghjjmgggggggggggggglkjhk
Mac repertory.pdfgghjjmgggggggggggggglkjhkMac repertory.pdfgghjjmgggggggggggggglkjhk
Mac repertory.pdfgghjjmgggggggggggggglkjhk
vasajagadishwar1
 
Juniper JN0-224 Certification Preparation Guide with Sample Questions.pdf
Juniper JN0-224 Certification Preparation Guide with Sample Questions.pdfJuniper JN0-224 Certification Preparation Guide with Sample Questions.pdf
Juniper JN0-224 Certification Preparation Guide with Sample Questions.pdf
sabrina pinto
 
电子版成绩单英国UofG文凭格拉斯哥大学学生证学历认证范本购买
电子版成绩单英国UofG文凭格拉斯哥大学学生证学历认证范本购买电子版成绩单英国UofG文凭格拉斯哥大学学生证学历认证范本购买
电子版成绩单英国UofG文凭格拉斯哥大学学生证学历认证范本购买
Taqyea
 
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa HagenUXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA Boston
 
central nervous system brain nose mourth spinal vord
central nervous system brain nose mourth spinal vordcentral nervous system brain nose mourth spinal vord
central nervous system brain nose mourth spinal vord
MouryaGarg1
 
Interview questions for freshers by Talent Titan.pdf
Interview questions for freshers by Talent Titan.pdfInterview questions for freshers by Talent Titan.pdf
Interview questions for freshers by Talent Titan.pdf
shubhamgoel346498
 
GROUP 1 NAV.pptxhwjwhshwuwhhwhsjssjwjjwd
GROUP 1 NAV.pptxhwjwhshwuwhhwhsjssjwjjwdGROUP 1 NAV.pptxhwjwhshwuwhhwhsjssjwjjwd
GROUP 1 NAV.pptxhwjwhshwuwhhwhsjssjwjjwd
andresjohnjohn99
 
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
Taqyea
 
Coronary artery disease resident final.pptx
Coronary artery disease resident final.pptxCoronary artery disease resident final.pptx
Coronary artery disease resident final.pptx
PrashantMohanty2
 
science stream ppt ankush.injcnjd jfcdsj
science stream ppt ankush.injcnjd jfcdsjscience stream ppt ankush.injcnjd jfcdsj
science stream ppt ankush.injcnjd jfcdsj
prashantksistla
 
What To Expect When Partnering With A Retained Executive Search Firm?
What To Expect When Partnering With A Retained Executive Search Firm?What To Expect When Partnering With A Retained Executive Search Firm?
What To Expect When Partnering With A Retained Executive Search Firm?
WalkWater Talent Advisors Pvt. Ltd.
 
Department of Computer Science and Applications 1.pptx
Department of Computer Science and Applications 1.pptxDepartment of Computer Science and Applications 1.pptx
Department of Computer Science and Applications 1.pptx
panghaldharmender459
 
Ad

Workbook_2_Problem_Solving_and_programming.pdf

  • 1. 1 | P a g e Workbook #2 {Re-view of principles printf, scanf, designing a program, definitions, sub-routines (sub functions) with main function, numeric, string, characters, arrays, for loop, while loop, if – else statements} Theory (Briefing)
  • 2. 2 | P a g e
  • 3. 3 | P a g e
  • 4. 4 | P a g e
  • 5. 5 | P a g e
  • 6. 6 | P a g e Draw the IPO chart and describe each part Describe all parts of the problem analysis
  • 7. 7 | P a g e Algorithm It is a sequence of instructions to solve a problem, written in human language. • A step-by-step procedure to solve a given problem. • An algorithm should always have a clear stopping point • Programmer writes the problem solving in the form of an algorithm before coding it into computer language. • Algorithms for making things will divide into sections: (the parts/components/ ingredients (inputs) required to accomplish the task, the actions/steps/methods (processing) to produce the required outcome(output) • Algorithm can be developed using: pseudo code (similar to programming language) • Flow chart
  • 8. 8 | P a g e
  • 9. 9 | P a g e Flowchart is a graphical representation of data, information and workflow using certain symbols that are connected to flow lines to describe the instructions done in problem solving.
  • 10. 10 | P a g e
  • 11. 11 | P a g e Operations Calculations and variables There are different operators that can be used for calculations which are listed in the following table: Operator Operation + Addition – Subtraction * Multiplication / Division % Modulus(Remainder of integer division) Now that we know the different operators, let’s calculate something: Example 1: int main() { int a, b; a = 1; b = a + 1; a = b - 1; return 0; } Example 2: So let’s make a program that can do all these things: #include<stdio.h> int main() { int inputvalue; scanf("%d", &inputvalue); inputvalue = inputvalue * 10; printf("Ten times the input equals %dn",inputvalue); return 0; }
  • 12. 12 | P a g e Note: The input must be a whole number (integer). Boolean Operators Before we can take a look at test conditions we have to know what Boolean operators are. They are called Boolean operators because they give you either true or false when you use them to test a condition. The greater than sign “>” for instance is a Boolean operator. In the table below you see all the Boolean operators: == Equal ! Not != Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal && And || Or
  • 13. 13 | P a g e The if-statement The if statement can be used to test conditions so that we can alter the flow of a program. In other words: if a specific statement is true, execute this instruction. If not true, execute this instruction. So lets take a look at an example: Example 3 based on if-statement #include<stdio.h> int main() { int mynumber; scanf("%d",&mynumber); if ( mynumber == 10 ) printf("Is equaln"); return 0; } Now we like to also print something if the “if statement” is not equal. We could do this by adding another “if statement” but there is an easier / better way. Which is using the so called “else statement” with the “if statement”. Example 4: #include<stdio.h> int main() { int mynumber; scanf("%d",&mynumber); if ( mynumber == 10 ) { printf("Is equaln"); printf("Closing programn"); } else { printf("Not equaln"); printf("Closing programn"); } return 0; } Note: Take a look at the placement of the curly brackets and how the indentations are placed. This is all done to make reading easier and to make less mistakes in large programs.
  • 14. 14 | P a g e Nested-if statements If you use an “if statement” in an “if statement” it is called nesting. Nesting “if statements” can make a program very complex, but sometimes there is no other way. So use it wisely. Take a look at a nested “if statement” example below: Example 5: Nested-if statements #include<stdio.h> int main() { int grade; scanf("%d",&grade); if ( grade <= 10 ) { printf("YOU DID NOT STUDY.n"); printf("YOU FAILED ! n"); } else { if ( grade < 60 ) { printf("You failed n"); printf("Study hardern"); } else { if ( grade >= 60 ) printf("YOU PASSED ! n"); } } return 0; } Multiple condition testing It is possible to test two or more conditions at once in an “if statement” with the use of the AND (&&) operator. Example: if (a > 10 && b > 20 && c < 10 ) If a is greater then ten and b is greater then twenty and c is smaller then ten, do something. So all three conditions must be true, before something happens. With the OR ( || ) operator you can test if one of two conditions are true. Example: if ( a = 10 || b < 20 )
  • 15. 15 | P a g e If a equals ten or b is smaller then twenty then do something. So if a or b is true, something happens. The switch statement The switch statement is almost the same as an “if statement”. The switch statement can have many conditions. You start the switch statement with a condition. If one of the variable equals the condition, the instructions are executed. It is also possible to add a default. If none of the variable equals the condition the default will be executed. See the example below: Example 6: #include<stdio.h> int main() { char myinput; printf("Which option will you choose:n"); printf("a) Program 1 n"); printf("b) Program 2 n"); scanf("%c", &myinput); switch (myinput) { case 'a': printf("Run program 1n"); break; case 'b': { printf("Run program 2n"); printf("Please Waitn"); break; } default: printf("Invalid choicen"); break; } return 0; } Note: break is used to exit the switch.
  • 16. 16 | P a g e For-loop, While loop, Do-While loop, Break and Continue In every programming language, thus also in the C programming language, there are circumstances where you want to do the same thing many times. For instance you want to print the same words ten times. You could type ten printf function, but it is easier to use a loop. The only thing you have to do is to setup a loop that execute the same printf function ten times. There are three basic types of loops which are: ▪ “for loop” ▪ “while loop” ▪ “do while loop” The for loop The “for loop” loops from one number to another number and increases by a specified value each time. The “for loop” uses the following structure: for (Start value; continue or end condition; increase value) statement; Look at the example below: Example 7: #include<stdio.h> int main() { int i; for (i = 0; i < 10; i++) { printf ("Hellon"); printf ("Worldn"); } return 0; } Note: A single instruction can be placed behind the “for loop” without the curly brackets. Let’s look at the “for loop” from the example: We first start by setting the variable i to 0. This is where we start to count. Then we say that the for loop must run if the counter i is smaller then ten. Last we say that every cycle i must be increased by one (i++). In the example we used i++ which is the same as using i = i + 1. This is called incrementing. The instruction i++ adds 1 to i. If you want to subtract 1 from i you can use i--. It is also possible to use ++i or --i. The difference is that with ++i (prefix incrementing) the one is added
  • 17. 17 | P a g e before the “for loop” tests if i < 10. With i++ (postfix incrementing) the one is added after the test i < 10. In case of a for loop this make no difference, but in while loop test it makes a difference. But before we look at a postfix and prefix increment while loop example, we first look at the while loop. The while loop The while loop can be used if you don’t know how many times a loop must run. Here is an example 8 #include<stdio.h> int main() { int counter, howmuch; scanf("%d", &howmuch); counter = 0; while ( counter < howmuch) { counter++; printf("%dn", counter); } return 0; } Let’s take a look at the example: First you must always initialize the counter before the while loop starts ( counter = 1). Then the while loop will run if the variable counter is smaller then the variable “howmuch”. If the input is ten, then 1 through 10 will be printed on the screen. A last thing you have to remember is to increment the counter inside the loop (counter++). If you forget this the loop becomes infinitive. As said before (after the for loop example) it makes a difference if prefix incrementing (++i) or postfix incrementing (i++) is used with while loop. Take a look at the following postfix and prefix increment while loop example: Example 9 #include<stdio.h> int main(void) { int i; i = 0; while(i++ < 5) { printf("%dn", i); }
  • 18. 18 | P a g e printf("n"); i = 0; while(++i < 5) { printf("%dn", i); } return 0; } The output of the postfix and prefix increment example will look like this: 1 2 3 4 5 1 2 3 4 i++ will increment the value of i, but is using the pre-incremented value to test against < 5. That’s why we get 5 numbers. ++i will increment the value of i, but is using the incremented value to test against < 5. That’s why we get 4 numbers. The do while loop The “do while loop” is almost the same as the while loop. The “do while loop” has the following form: do { do something; } while (expression); Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the expression test comes afterward). Take a look at an example: Example 10 #include<stdio.h> int main() { int counter, howmuch; scanf("%d", &howmuch); counter = 0; do
  • 19. 19 | P a g e { counter++; printf("%dn", counter); } while ( counter < howmuch); return 0; } Note: There is a semi-colon behind the while line. Break and continue To exit a loop you can use the break statement at any time. This can be very useful if you want to stop running a loop because a condition has been met other than the loop end condition. Take a look at the following example: Example 11: #include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; if ( i == 10) break; } return 0; } In the example above, the while loop will run, as long i is smaller then twenty. In the while loop there is an if statement that states that if i equals ten the while loop must stop (break). With “continue;” it is possible to skip the rest of the commands in the current loop and start from the top again. (the loop variable must still be incremented). Take a look at the example below: Example 12: #include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) {
  • 20. 20 | P a g e i++; continue; printf("Nothing to seen"); } return 0; } In the example above, the printf function is never called because of the “continue;”. Arrays and Multi-Dimensional Arrays In this C programming language tutorial, we are going to talk about arrays. An array lets you declare and work with a collection of values of the same type. Let’s say you want to declare four integers. With the knowledge from the last few tutorials you would do something like this: int a , b , c , d; What if you wanted to declare a thousand variables? That will take you a long time to type. This is where arrays come in handy. An easier way is to declare an array of four integers: int a[4]; The four separate integers inside this array are accessed by an index. Each element can be accessed by using square brackets with the element number inside. All arrays start at element zero and will go to n-1. (In this case from 0 to 3). So if we want to fill each element you get something like this: int a[4]; a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; If you want to use an element, for example for printing, you can do this: printf("%d", a[1]); Arrays and loops One of the nice things about arrays is that you can use a loop to manipulate each element. When an array is declared, the values of each element are not set to zero automatically. In some cases you want to “initialize” the array (which means, setting every element to zero). This can be done like in the example above, but it is easier to use a loop. Here is an example:
  • 21. 21 | P a g e Example 13: #include<stdio.h> int main() { int a[4]; int i; for ( i = 0; i < 4; i++ ) a[i] = 0; for ( i = 0; i < 4; i++ ) printf("a[%d] = %dn", i , a[i]); return 0; } Multi-dimensional arrays The arrays we have been using so far are called one-dimensional arrays. Here is an example of an one-dimensional array: int a[2]; 0 1 1 2 Note: A one-dimensional array has one column of elements. Two-dimensional arrays have rows and columns. See the example below: int a[2][2]; 0 1 0 1 2 1 4 5 Note: a[0][0] contains the value 1. a[0][1] contains the value 2. a[1][0] contains the value 4. a[1][1] contains the value 5. So let’s look at an example that initialize a two-dimensional array and prints each element: Example 14:
  • 22. 22 | P a g e #include<stdio.h> int main() { int a[4][4], i , j; for (i = 0; i < 4; i++) { for ( j = 0; j < 4; j++) { a[i][j] = 0; printf("a[%d][%d] = %d n", i, j, a[i][j]); } } return 0; } Note: As you can see, we use two “for loops” in the example above. One to access the rows and the other to access the columns. Functions and Global/Local variables Most languages allow you to create functions of some sort. Functions are used to break up large programs into named sections. You have already been using a function which is the main function. Functions are often used when the same piece of code has to run multiple times. In this case you can put this piece of code in a function and give that function a name. When the piece of code is required you just have to call the function by its name. (So you only have to type the piece of code once). In the example below we declare a function with the name MyPrint. The only thing that this function does is to print the sentence: Printing from a function. If we want to use the function we just have to call MyPrint() and the printf statement will be executed. (Don’t forget to put the round brackets behind the function name when you call it or declare it). Take a look at the example 15: #include<stdio.h> void MyPrint() { printf("Printing from a function.n"); } int main() { MyPrint(); return 0; }
  • 23. 23 | P a g e Parameters and return Functions can accept parameters and can return a result. (C functions can accept an unlimited number of parameters). Where the functions are declared in your program does not matter, as long as a functions name is known to the compiler before it is called. In other words: when there are two functions, i.e. functions A and B, and B must call A, than A has to be declared in front of B. Let’s take a look at an example where a result is returned: Example 16 #include<stdio.h> int Add(int output1,int output2 ) { printf("%d", output1); printf("%d", output2); return output1 + output2; } int main() { int answer, input1, input2; scanf("%d", &input1); scanf("%d", &input2); answer = Add(input1,input2); printf(" answer = %dn", answer); return 0; } The main() function starts with the declaration of three integers. Then the user can input two whole numbers. These numbers are used as input of function Add(). Input1 is stored in output1 and input2 is stored in output2. The function Add() prints the two numbers onto the screen and will return the result of output1 + output2. The return value is stored in the integer answer. The number stored in answer is then printed onto the screen.
  • 24. 24 | P a g e Void If you don’t want to return a result from a function, you can use void return type instead of the int. So let’s take a look at an example of a function that will not return an integer: void our_site() { printf("www"); printf(".NextDawn"); printf(".nl"); } Note: As you can see there is not an int before our_site() and there is not a return 0; in the function. The function can be called by the following statement: our_site(); Global and local variables A local variable is a variable that is declared inside a function. A global variable is a variable that is declared outside all functions. A local variable can only be used in the function where it is declared. A global variable can be used in all functions. See the following example: #include<stdio.h> // Global variables int A; int B; int Add() { return A + B; } int main() { int answer; // Local variable A = 5; B = 7; answer = Add(); printf("%dn",answer); return 0; } As you can see two global variables are declared, A and B. These variables can be used in main() and Add(). The local variable answer can only be used in main().
  翻译: