In: Computer Science
Part II: Programming Questions
NOTE: CODING LANGUAGE IS C#
PQ1. How would you declare the following scalar and non-scalar (vector) variables?
PQ2.
PQ3.
PQ4. The algorithm for checking if a number is a prime is to check if it is divisible by any number less than itself other than 1. (Divisibility implies that if you use the modulus operator, %, the result will be 0). Write a function to check if a number is a prime.
Please find your answers below and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
PQ1. How would you declare the following scalar and non-scalar (vector) variables?
Answer: We can declare them like below.
int counter;
double sum;
double average;
//declaring an array that is capable of storing 32 grades.
double[] grades=new double[32]; //or simply double[] grades; if you want to initialize later
PQ2.
i. How would you initialize the array above with numbers between 0.0 and 4.0 representing the grades of all courses a senior has received in the four years of college?
Answer: You can initialize the grades array like below. Replace the numbers with the grades you need.
grades=new
double[]{3,3.5,4,4,1,2,3,4,5,3.4,4,1,2.3,3,4,2.5,2.5,3,3,3,3,3,3,4,2.3,4,4,4,2,3.9,3,3};
ii. Instead of initializing the array above, how would you, in a loop, accept input from the user for the 32 grades?
Answer: You can initialize the grades array using a loop, accepting input from user like below
//looping from i=0 to
i=grades.Length-1 (32 in this case)
for(int
i=0;i<grades.Length;i++){
//asking
for the grade
Console.WriteLine("Enter
grade "+(i+1)+": ");
//reading
a grade, parsing to double, adding to index i in grades array
grades[i]=double.Parse(Console.ReadLine());
}
PQ3.
i. How would you calculate the sum of all the grades in the array above?
sum=0;
//looping from i=0
to i=grades.Length-1 (32 in this case)
for(int
i=0;i<grades.Length;i++){
//adding
current grade to sum
sum+=grades[i];
}
ii. How would you average the sum above?
//dividing sum by
number of grades to get the average
average=(double)
sum/grades.Length;
PQ4. The algorithm for checking if a number is a prime is to check if it is divisible by any number less than itself other than 1. (Divisibility implies that if you use the modulus operator, %, the result will be 0). Write a function to check if a number is a prime.
//method to check if n is prime, return true if prime, else
false
public static
bool IsPrime(int
n){
//any number below
2 is not prime
if(n<2){
return
false;
}
//looping from 2 to
n-1
for(int
i=2;i<n;i++){
//if
i divides n evenly, then n is not prime
if(n%i
== 0){
return
false; //not prime
}
}
//if the program
reach this point, then n is prime.
return
true;
}