ITFN 2313 Mid-Term Practice
(Fall 2009)
static void
RecursiveFunction(int x)
{
if (x > 100)
//Condition to stop recursion
return; //Exit out of function
else
{
Console.WriteLine(x);
RecursiveFunction(x + 2); //Call myself
}
}
static void Main(string[] args)
{
RecursiveFunction(0);
Console.Read();
}
static void Main(string[] args)
{
int num;
Console.WriteLine("Enter
a number");
try
{
num = Convert.ToInt32(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("That
is not a number!");
}
}
11, 9, 7, 5, 3, 1
{static void f(int i)
{
if
(i < 10)
f(i+2);
Console.WriteLine(i);
}
{
if (x > 99) //Condition to stop
recursion
return; //Exit out of
function
else
{
Console.WriteLine(x);
RecursiveFunction(x + 3); //Call myself
}
}
static void Main(string[] args)
{
RecursiveFunction(0);
Console.Read();
}
void Print_N_to_1_to_N(int
n)
For example, Print_N_to_1_to_N(6)would
print 6 5 4 3 2 1 2 3 4 5 6.
public static void Print_N_to_1_to_N(int n)
{
if (n > 0)
{
Console.Write(n);
Print_N_to_1_to_N(n - 1);
Console.Write(n);
}
}
int numOne = 4;
int numTwo = 0;
int sum=(numOne/numTwo); Throw point
– DivideByZero exception
try
{
int sum = (numOne /
numTwo);
}
catch (DivideByZeroException)
{
Console.WriteLine("You cannot divide by zero");
}
int
Sum_1_to_N(int n)
For
example, Sum_N_to_1(5)would be 15 (1 + 2 + 3 + 4 + 5).
public static int Sum1_to_n(int n)
{
int answer = n;
if (n > 0)
{
answer = n + (Sum1_to_n(n -
1));
}
return answer;
}
PALINDROME
TEST
public static bool testString(string s, int left, int right) function
that takes in a string and two ints. The two ints represent the start of
the string and the end of the string
{
if (left
>= right) terminating condition tests # of first
letter against # of last letter
return true; e.g. if string is “Sandra”
left = 0 and right is = 5; makes progress toward middle of string
else if
(s[left] != s[right]) terminating condition tests if first letter
is not equal to last letter
return
false;
else
return
TestString(s, left + 1, right -1); recursive
call, increases left by one, reduces right by one.
}