6 Lecture
6 Lecture
C++ if Statement
if (testExpression)
// statements
#include <iostream>
using namespace std;
void main() {
int number;
cout << "Enter an integer: ";
cin >> number;
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
else{
cout << "This statement is always executed.";
return 0;
}
}
Example 2:
// Program to check whether an integer is positive or negative
#include <iostream>
using namespace std;
void main() {
int number;
cout << "Enter an integer: ";
cin >> number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
cout<< "You entered a negative integer: " << number << endl;
}
cout << "This line is always printed.";
return 0;
}
#include <iostream>
Using namespace std;
Void main(){
int number;
Cout <<”enter the number=”;
Cin>> number;
If (number >0){
Cout<<” you entered the positive number”<<number<<endl;
}
else if (number <0){
cout<<: you entered the negative number”<<number<<endl;
}
else{
Cout<<”you entered the zero”;
}
}
Same Example for drawing shapes:
// C++ program for Square Shape using 10 stars:
#include<iostream>
using namespace std;
void main()
{
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
if (i == 1 || i == 10) {
}
cout << "*";
else if (j == 1 || j == 10) // (||) means OR
//(&&) means AND
}
}
// C++ program for X letter using 5 stars:
#include<iostream>
using namespace std;
void main()
{
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
if (i == j || j == 6-i)
cout << "*";
else
cout << " ";
}
cout << endl;
}
}