C# exercises and solutions-C# Conditional statements if else


C# Conditional statements if else exercises

These C# exercises help you practice using if, if...else, and if...else if...else statements.

Exercise 1: Write a C# program that prompts the user to input three integer values and find the greatest value of the three values.

Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{


int x,y,z;

Console.Write("Enter value 1:");
x = int.Parse(Console.ReadLine());
Console.Write("Enter value 2:");
y = int.Parse(Console.ReadLine());
Console.Write("Enter value 3:");
z = int.Parse(Console.ReadLine());


if (x > y)
   if (x > z) Console.Write("The greatest value is:{0}.",x);
   else Console.Write("The greatest value is:{0}.", z);
else if (y > z) Console.Write("The greatest value is:{0}.",y);
   else Console.Write("The greatest value is:{0}.",z);



Console.ReadLine();
    }
  }
}

Exercise 2: Write a C# program that determines a student’s grade.

The program will read three types of scores(quiz score, mid-term score, and final score) and determine the grade based on the following rules:

-if the average score =90% =>grade=A
-if the average score >= 70% and <90% => grade=B
-if the average score>=50% and <70% =>grade=C
-if the average score<50% =>grade=F

Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{


float quiz_score;
float mid_score;
float final_score;
float avg;
Console.Write("Enter quiz score:");
quiz_score=float.Parse(Console.ReadLine());
Console.Write("Enter mid-term score:");
mid_score = float.Parse(Console.ReadLine());
Console.Write("Enter final score:");
final_score = float.Parse(Console.ReadLine());
avg = (quiz_score +mid_score+final_score) / 3;

if (avg >= 90) Console.WriteLine("Grade A");
else if ((avg >= 70) && (avg < 90)) Console.WriteLine("Grade B");
else if ((avg >= 50) && (avg < 70)) Console.WriteLine("Grade C");
else if (avg < 50) Console.WriteLine("Grade F");
else Console.WriteLine("Invalid input");


Console.ReadLine();
     }
  }
}



Comments

solomon comment

 solomon

#include<iostream.h> // for inpit and output
#include<string.h> // for string nama...
using namespace std; // for name space..

struct student // declare struct
{
string name,no_matric;
string sub_code[10],sub_name[10],sub_grade[10];
float credit_hour[10];
}student1;

main()
{
int credit_hours[10];
int sem,total_subject; //'b', 'a',total_credit_hours and total_point
//are removed
float value[10],gpa[10],get_point[10];
float cgpa;
float total_point_sem = 0; //Initialise value
int total_credit_hours_sem = 0; //Initialise value
cin.ignore();

cout << "\t\ ================ ";
cout << "\n\t\ STUDENT'S REKOD " << endl;
cout << "\t\ ================ " << endl;

cout << "\n ENTER STUDENT'S NAME : "; //Enter student's name
getline(cin,student1.name);
cout << " ENTER STUDENT'S MATRIC NUMBER : "; //Enter student's matric number
getline(cin,student1.no_matric);
cout << " ENTER TOTAL SEM TAKEN :"; //Total semester taken by the student
cin >> sem;

for(int a = 0; a< sem ; a++) //'a' declared as int in for()[newly added]
{
int b; //newly added line,'b' choose to add it here because, if not, error will be occured : 'b' for gpa[b] will become undefined...

int total_credit_hours = 0; //newly added
float total_point = 0; //newly added
cout << "\n ENTER SUBJECT TAKEN FOR SEM : " << a+1 << ":"; //Enter total number of subject taken for each sem
cin >> total_subject;
for(int b = 0; b< total_subject; b++) //loop for the courses
{
cin.ignore();
cout << " ENTER SUBJECT CODE : "; //Enter subject code
getline(cin,student1.sub_code[b]);
cout << " ENTER SUBJECT NAME : "; //Enter subject name
getline(cin,student1.sub_name[b]);
cout << " ENTER SUBJECT'S CREDIT HOUR : "; //Enter credit hours of the subject
cin >> student1.credit_hour[b];
cin.ignore();
cout << " ENTER SUBJECT GRED : "; //Enter grade gained by student for every subject
getline(cin,student1.sub_grade[b]);

if(student1.sub_grade[b]=="A")
value[b]=4;
else if(student1.sub_grade[b]=="A-")
value[b]=3.75;
else if(student1.sub_grade[b]=="B+")
value[b]=3.5;
else if(student1.sub_grade[b]=="B")
value[b]=3;
else if(student1.sub_grade[b]=="B-")
value[b]=2.75;
else if(student1.sub_grade[b]=="C+")
value[b]=2.5;
else if(student1.sub_grade[b]=="C")
value[b]=2;
else if(student1.sub_grade[b]=="C-")
value[b]=1.75;
else if(student1.sub_grade[b]== "D+")
value[b]=1.5;
else if(student1.sub_grade[b]=="D")
value[b]=1;
else
value[b]=0;

get_point[b] = student1.credit_hour[b] * value[b]; //multiply of credit hours and grade get for each subject
total_credit_hours +=student1.credit_hour[b]; //total cerdit hours for a sem
total_point += get_point[b]; //total points(multiple of credits hours and grade)get for a sem
}

gpa[b] = total_point / total_credit_hours; //calculate GPA for each sem

total_point_sem += total_point; //Total points(multiple of grade and credit hours) get for all semester

total_credit_hours_sem += total_credit_hours; //credits hour get for all semester
}

cgpa = total_point_sem / total_credit_hours_sem; //calculate CGPA

cout << "\n =================================================== ";
cout <<"\n NAME : " << student1.name << endl; //display name of student
cout <<" NO MATRIC : "<< student1.no_matric << endl;
for(int a = 0; a< sem ; a++) //Declaration of 'a' as int in for()
{
cout <<" SUBJECT CODE \t" << " SUBJECT NAME \t" << " SUBJECT CREDIT HOURS " <<endl;
for(int b=0; b<total_subject; b++) //Declaration of 'b' as int in for()
{
cout << " " << student1.sub_code[b] << " : " << student1.sub_name[b]<< " : " << student1.credit_hour[b] << endl;
}
cout << " GPA" <<a+1<< " : " <<gpa[a] << endl;
}
cout << " CGPA : "<<cgpa<<endl;

cout << "\n =================================================== ";

}


2017-05-18
Solomon comment

 Solomon

Write a c++ program that prints the shape shown on the right side of this slide
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *


2017-05-09
Solomon comment

 Solomon

Write a C++ program that counts the number of digits in an integer number. For example; 23,498 has five digits


2017-05-09
Solomon comment

 Solomon

Write a C++ program that counts the number of digits in an integer number. For example; 23,498 has five digits


2017-05-09
Solomon comment

 Solomon

Write a C++ application that can compute the letter grade of a student after accepting the student’s mid and final mark.
- The program should only accept mid result [0-40] and final [0- 60].
- If the data entered violates this rule, the program should display that
the user should enter the mark in the specified range.
- The program is also expected to run until the user refuses to
continue.


2017-05-09
Solomon comment

 Solomon

Write a C++ application that can compute the letter grade of a student after accepting the student’s mid and final mark.
- The program should only accept mid result [0-40] and final [0- 60].
- If the data entered violates this rule, the program should display that
the user should enter the mark in the specified range.
- The program is also expected to run until the user refuses to
continue.


2017-05-09
Abubakar sohail comment

 Abubakar sohail

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nestedifelse
{
class Program
{
static void Main(string[] args)
{
float avg;
float mid;
float final;
float quiz;
Console.WriteLine("enter the quiz marks out of 100");
quiz = int.Parse(Console.ReadLine());
Console.WriteLine("enter the mid term marks out of 100");
mid = int.Parse(Console.ReadLine());
Console.WriteLine("enter the final term marks out of 100");
final = int.Parse(Console.ReadLine());
avg = (mid + final + quiz) / 300*100;
if (avg >= 90)
{
Console.WriteLine("A1 grade");
}
else if (avg >= 80)
{
Console.WriteLine("A+ grade");
}
else

if (avg >= 70)
{
Console.WriteLine("A grade");
}
else

if (avg >= 60)
{
Console.WriteLine("B grade");
}
else

if (avg >= 50)
{
Console.WriteLine("C grade");
}
else

Console.WriteLine("invalid");
Console.ReadKey();

}
}

}


2017-03-02
shrill comment

 shrill

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace conditional_statements
{
public class Program
{
public void Main(string[] args)
{
/*
int first_number, second_number, third_number;
Console.WriteLine("Enter three integer numbers");
first_number = int.Parse(Console.ReadLine());
second_number = int.Parse(Console.ReadLine());
third_number = int.Parse(Console.ReadLine());
if (first_number > second_number)
if (first_number > third_number)
Console.WriteLine("greatest number is {0}", first_number);
else
Console.WriteLine("greatest number is {0}", third_number);
else
if (second_number > third_number)
Console.WriteLine("greatest is {0}", second_number);
else
Console.WriteLine("greates is {0}", third_number);
*/
int quiz, midterm, final;
float Average;
Console.WriteLine("quiz ?, mid term an final?");
quiz = int.Parse(Console.ReadLine());
midterm = int.Parse(Console.ReadLine());
final = int.Parse(Console.ReadLine());
Average = (quiz + midterm + final) / 3;
if (Average >= 90)
Console.WriteLine("A");
else if ((Average >= 70) && (Average < 90))
Console.WriteLine("B");
else if ((Average >= 50) && (Average < 70))
Console.WriteLine("c");
else if ((Average < 50) )
Console.WriteLine(" F");






}
}
}


2017-01-28
Ahmed Bakri comment

 Ahmed Bakri

int num1, num2, num3;
Console.WriteLine("plz enter the first number");
num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("plz enter the second number");
num2 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("plz enter the third number");
num3 = Convert.ToInt32(Console.ReadLine());
if (num1>num2&num1>num3)
{
Console.WriteLine(num1);
}
else if (num2>num1&num2>num3)
{
Console.WriteLine(num2);
}
else
{
Console.WriteLine(num3);
}



2016-05-21
Daniel Tiotuico comment

 Daniel Tiotuico

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MaxValue3Input
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter First Number: ");
double number1 = double.Parse(Console.ReadLine());
Console.Write("Enter Second Number: ");
double number2 = double.Parse(Console.ReadLine());
Console.Write("Enter Third Number: ");
double number3 = double.Parse(Console.ReadLine());


double max = Maximum(number1, number2, number3);
Console.WriteLine("Max value is: " +max);
}
static double Maximum(double x, double y, double z)
{
return Math.Max(x, (Math.Max(y, z)));
}
}
}


2015-07-09
Matt comment

 Matt

Exercise #2 using the Average() method of Array, also checks for valid input:

public static void Main (string[] args)
{

while (true) {

Console.WriteLine ("Enter quiz score:");
string quizScore = Console.ReadLine ();
Console.WriteLine ("Enter midterm score:");
string midtermScore = Console.ReadLine ();
Console.WriteLine ("Enter final score:");
string finalScore = Console.ReadLine ();

//array of string inputs from user
string[] inputValues = { quizScore, midtermScore, finalScore };

// array to hold converted doubles
double[] doublesFromValues;
doublesFromValues = new double[3];

for (int i = 0; i < inputValues.Length; i++) {

Double temp;

if (Double.TryParse (inputValues[i], out temp)) {

doublesFromValues [i] = temp;

} else {

Console.WriteLine ("Value at index {0} is not valid.", i);

}
}

double averageScore = doublesFromValues.Average();

Console.WriteLine ("\nAverage of all scores is: " + averageScore);

if (averageScore >= 90) {
Console.WriteLine ("\nYour grade is A");
} else if (averageScore >= 70 && averageScore < 90) {
Console.WriteLine ("\nYour grade is B");
} else if (averageScore >= 50 && averageScore < 70) {
Console.WriteLine ("\nYour grade is C");
} else {
Console.WriteLine ("\nYour grade is F");
}

Console.ReadLine ();

return;
}
}


2015-03-19
Matt comment

 Matt

Exercise #1 using the Max() method of an Array:

public static void Main (string[] args)
{

while (true) {

Console.WriteLine ("Enter 3 integers:\n");

string userInputA = Console.ReadLine ();
string userInputB = Console.ReadLine ();
string userInputC = Console.ReadLine ();

//array of string inputs from user
string[] inputValues = { userInputA, userInputB, userInputC };

// array to hold converted integers
int[] integersFromValues;
integersFromValues = new int[3];

for (int i = 0; i < inputValues.Length; i++) {

int temp;

if (Int32.TryParse (inputValues[i], out temp)) {

integersFromValues [i] = temp;

} else {

Console.WriteLine ("Value at index {0} is not an integer.", i);

}
}

Console.WriteLine ("Max value is: " + integersFromValues.Max());

Console.ReadLine ();

return;
}
}


2015-03-19
CR7 comment

 CR7

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rami
{
class Program
{

static void Main(string[] args)
{
Console.WriteLine("enter the quiz degrees\n");
int total = 0;
for (int i = 0; i < 3; i++)
{
if(i==0)
Console.WriteLine("quiz score\n");
if (i == 1)
Console.WriteLine("mid-term score\n");
if (i == 2)
Console.WriteLine("final score\n");

int x = Int32.Parse(Console.ReadLine());
total = total + x;
}
Console.WriteLine("the total is :{0}\n",total);


float percent = total/3f ;
Console.WriteLine("the averge is = {0}\n", percent);

if (percent >= 90)
Console.WriteLine("the student grade A\n");
else if (percent >= 70)
if (percent < 90)
Console.WriteLine("the student grade B\n");
if (percent >= 50)
if (percent < 70)
Console.WriteLine("the student grade C\n");
if (percent <= 50)
Console.WriteLine("the student grade F\n");


}
}
}


2015-01-13
bookw0rm comment

 bookw0rm

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DetermineAStudentGrade
{
class Program
{
static void Main(string[] args)
{
float quizScore,midScore,finalScore,avgScore;
Console.WriteLine("Enter quiz score:");
quizScore = Convert.ToSingle(Console.ReadLine());
Console.WriteLine("Enter mid-term score:");
midScore = Convert.ToSingle(Console.ReadLine());
Console.WriteLine("Enter final score:");
finalScore = Convert.ToSingle(Console.ReadLine());
avgScore = (quizScore + midScore + finalScore) / 3;

if (avgScore >= 90)
{
Console.WriteLine("Congratulations ! You have Grade A !");
}
else if ((avgScore >= 70) && (avgScore <= 90))
{
Console.WriteLine("Almost on the right track ! You have Grade B !");
}
else if ((avgScore >= 50) && (avgScore <= 70))
{
Console.WriteLine("You can do better than this ! You have Grade C !");
}
else if (avgScore < 50)
{
Console.WriteLine("You really need to study ! You have Grade F !");
}
}
}
}


2014-11-06
bookw0rm comment

 bookw0rm

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GreatestValueOf3NumbersEntered
{
class Program
{
static void Main(string[] args)
{
int x, y, z;
Console.WriteLine("Enter the first number:");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number:");
y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the third number:");
z = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Let's compare the values entered !");

if ((x > y) && (x > z))
{
Console.WriteLine("Greatest number is {0}", x);
}
else if ((y > x) && (y > z))
{
Console.WriteLine("Greatest number is {0}", y);
}
else
{
Console.WriteLine("Greatest number is {0}", z);
}



}
}
}


2014-11-06
Jun comment

 Jun

Better one.

static void Main(string[] args)
{
int x, y, z;

Console.Write("Enter value 1: ");
x = int.Parse(Console.ReadLine());

Console.Write("Enter value 2: ");
y = int.Parse(Console.ReadLine());

Console.Write("Enter value 3: ");
z = int.Parse(Console.ReadLine());

Console.WriteLine("The greatest number is {0}.", Math.Max(Math.Max(x, y),z));

Console.ReadLine();
}


2014-10-27
Rajbir Singh comment

 Rajbir Singh

static void Main(string[] args)
{

Console.WriteLine("please enter % quiz score");
double quizscore = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("please enter % midterm score");
double midtermscore = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("please enter % final score");
double finalscore = Convert.ToDouble(Console.ReadLine());
double average = ((quizscore + midtermscore + finalscore) / 3);
char grade ;

grade = (average > 90) ? 'A' : (average < 90 && average > 70) ? 'B' : (average < 70 && average > 50) ? 'C' : 'F';

Console.WriteLine("grade {1} with and average of {0}%", Math.Round(average, 1), grade);
Console.ReadLine();

}


2014-08-13
Gufran comment

 Gufran

using System;

namespace LearnCSharpByPractice
{
class Program
{
static void Main(string[] args)
{

//Console.WriteLine("enter your age");
//int age = Convert.ToInt32(Console.ReadLine());
//int age = Int32.Parse(Console.ReadLine());
//int number;
//bool b = Int32.TryParse(Console.ReadLine(),out number);
//if (b) { Console.WriteLine("you are = {0} years old", number); }
int x = 10; int y = 20; int z = 30;
if (x > y)
{
if (x > z) Console.WriteLine("greatest value = {0}", x);
else Console.WriteLine("greatest value = {0}", z);

}
else
{
if (y > z) Console.WriteLine("greatest value ={0}", y);
else
Console.WriteLine("greatest value ={0}", z);


}

Console.ReadKey();
}
}
}


2014-08-05
shariq comment

 shariq

Alternatively i use this but that one also works well
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace reverse
{
class Program
{
static void Main(string[] args)
{
int X, Y, Z;
Console.WriteLine("eNTER fIRST nUMBER");
X = int.Parse (Console.ReadLine());
Console.WriteLine("eNTER 2ND nUMBER");
Y = int.Parse(Console.ReadLine());
Console.WriteLine("eNTER 3RD nUMBER");
Z = int.Parse(Console.ReadLine());

if (X > Y && X > Z)
{
Console.WriteLine("Greatest Number is" +X );
}
else if (Y > X && Y > Z)
{
Console.WriteLine("Greatest Number is" +Y);
}
else
{
Console.WriteLine("Greatest Number is" +Z);
}




Console.ReadLine();
}
}
}


2014-07-23
abeeb comment

 abeeb

the approach is simple and easy for newbies


2014-04-05
Rudresh comment

 Rudresh

This is great it helps me learn c# as I am ne to it


2014-01-04
Andy comment

 Andy

Alternatively:

if (x <= y)
x = y;
if (x <= z)
x = z;

Console.WriteLine("The greatest value is: {0}.", x);


2013-11-02



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.