Programming Fundamentals 3.
Programming Fundamentals 3.
Fundamentals
Course Code: CS-312
Instructor: Muhammad Bilal
Errors
Syntax Error
When a programmer writes code that does not follow the C/C++ syntax rules, it leads to the creation of
syntax errors.
E.g: typing errors, missing keywords or variables, mismatched parentheses, and brackets, incorrect data
types used for operations in a program, etc.
Logical Error
A logical error is an error that occurs when a program produces an incorrect output as a result of incorrect
logic or incorrect input.
For example, if a user were to input two numbers into a program expecting the sum of those two numbers
to be returned. But instead of that, the product was returned.
Runtime Error
A runtime error occurs when a code is executed and an unexpected condition happens. The most common
causes of these errors are- coding mistakes, memory corruption, or incorrect system configuration.
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 0;
int result = a/b;
cout<<result;
if statement
Selection statements choose among alternative courses of action.
For example, suppose the passing grade on an exam is 60. The following statement
determines whether the condition “greater than or equal to 60” is true or false.
If student’s grade is greater than or equal to 60, then “Passed” is printed
If false, the printing is ignored.
#include<iostream>
using namespace std;
int main(void)
{
int grade=70;
if (grade >= 60)
{
cout<<"Passed";
}
if else statement
The if…else selection statement specifies different actions to perform when the
condition is true or false
For example, the statement prints “Passed” if the student’s grade is greater than or
equal to 60; otherwise, it prints “Failed.”
#include<iostream>
using namespace std;
int main(void)
{
int grade=59;
if (grade >= 60)
{
cout<<"Passed";
}
else
{
cout<<"Failed";
}
if else if statement
For example, the following code prints:
A for grades greater than or equal to 90,
B for grades greater than or equal to 80 (but less than 90),
C for grades greater than or equal to 70 (but less than 80),
D for grades greater than or equal to 60 (but less than 70),
F for all other grades.
#include<iostream>
int main(void)
int grade=95;
cout<<"A";
cout<<"B";
cout<<"C";
cout<<"D";
else
cout<<"F";
}
while statement
An iteration statement (also called a repetition statement or loop) repeats
an action while some condition remains true.
#include<iostream>
using namespace std;
int main(void)
{
int a=1; //initialization
while(a<=5) //condition
{
cout<<"hello\n";
a=a+1; //increment/dec
}
while statement
Example: print HELLO ten times
Example: print number 1-10 using while loop
while statement
Example: To find the sum of all numbers from 1 to 10
#include<iostream>
using namespace std;
int main(void)
{
int sum=0;
int counter=1;
while (counter<=10)
{
sum=sum+counter;
counter++;
}
cout<<sum;