C Sharp Programming Exercises Solutions
L
Leora Smitham
C Sharp Programming Exercises Solutions Sharpen Your Skills C Programming Exercises with Solutions Mastering any programming language takes practice and C is no exception This article presents a curated collection of C programming exercises ranging from beginnerfriendly to more challenging designed to solidify your understanding of core concepts and boost your confidence Each exercise includes a clear problem statement and a detailed solution guiding you through the process and highlighting key takeaways Lets dive in Beginner Exercises 1 Hello World Problem Write a C program that prints Hello World to the console Solution C using System class HelloWorld static void Mainstring args ConsoleWriteLineHello World Key takeaway This exercise familiarizes you with the basic structure of a C program and the ConsoleWriteLine method for outputting text 2 Data Types and Variables Problem Declare variables of different data types int double string bool and assign them values Print the values to the console Solution 2 C using System class DataTypes static void Mainstring args int age 25 double height 175 string name John Doe bool isStudent true ConsoleWriteLineAge age ConsoleWriteLineHeight height ConsoleWriteLineName name ConsoleWriteLineIs Student isStudent Key takeaway Understanding different data types and how to declare and assign values to variables is crucial for data manipulation in C 3 Basic Arithmetic Operations Problem Write a program that takes two numbers as input from the user performs addition subtraction multiplication and division and prints the results Solution C using System class ArithmeticOperations static void Mainstring args ConsoleWriteEnter the first number int num1 intParseConsoleReadLine ConsoleWriteEnter the second number 3 int num2 intParseConsoleReadLine int sum num1 num2 int difference num1 num2 int product num1 num2 double quotient doublenum1 num2 ConsoleWriteLineSum sum ConsoleWriteLineDifference difference ConsoleWriteLineProduct product ConsoleWriteLineQuotient quotient Key takeaway This exercise demonstrates how to read user input perform basic arithmetic operations and handle data type conversions Intermediate Exercises 4 Conditional Statements Problem Write a program that asks the user for their age and prints You are eligible to vote if they are 18 years or older otherwise You are not eligible to vote Solution C using System class VotingEligibility static void Mainstring args ConsoleWriteEnter your age int age intParseConsoleReadLine if age 18 ConsoleWriteLineYou are eligible to vote else 4 ConsoleWriteLineYou are not eligible to vote Key takeaway This exercise introduces conditional statements ifelse to control program flow based on specific conditions 5 Loops Problem Write a program that prints the numbers from 1 to 10 using a for loop Solution C using System class LoopDemo static void Mainstring args for int i 1 i 10 i ConsoleWriteLinei Key takeaway This exercise demonstrates the use of loops for for iterating over a sequence of values and performing repetitive tasks 6 Arrays Problem Create an array of 5 integers take input from the user to populate the array and calculate the sum of all elements Solution C using System 5 class ArraySum static void Mainstring args int numbers new int5 int sum 0 ConsoleWriteLineEnter 5 numbers for int i 0 i numbersLength i numbersi intParseConsoleReadLine sum numbersi ConsoleWriteLineSum of array elements sum Key takeaway This exercise introduces arrays for storing collections of data and shows how to access and manipulate array elements Advanced Exercises 7 Functions Problem Write a function that takes two numbers as input and returns their sum Call the function in the Main method and print the result Solution C using System class FunctionDemo static int CalculateSumint num1 int num2 return num1 num2 static void Mainstring args 6 int num1 10 int num2 20 int sum CalculateSumnum1 num2 ConsoleWriteLineSum sum Key takeaway This exercise emphasizes the importance of modularity by introducing functions for encapsulating reusable code blocks 8 Classes and Objects Problem Define a class called Employee with attributes like name salary and department Create an object of the Employee class and assign values to its attributes Print the employees information Solution C using System class Employee public string name public double salary public string department public void DisplayEmployeeInfo ConsoleWriteLineName name ConsoleWriteLineSalary salary ConsoleWriteLineDepartment department class ClassDemo static void Mainstring args 7 Employee emp new Employee empname Jane Doe empsalary 50000 empdepartment IT empDisplayEmployeeInfo Key takeaway This exercise introduces classes and objects the fundamental building blocks of objectoriented programming in C 9 Exception Handling Problem Write a program that prompts the user for a number and divides 100 by that number Handle the DivideByZeroException and print an appropriate message Solution C using System class ExceptionHandlingDemo static void Mainstring args try ConsoleWriteEnter a number int num intParseConsoleReadLine int result 100 num ConsoleWriteLineResult result catch DivideByZeroException ex ConsoleWriteLineError Cannot divide by zero exMessage 8 Key takeaway This exercise demonstrates how to handle exceptions gracefully ensuring that your program can recover from unexpected errors 10 File IO Problem Write a program that reads a text file counts the number of words and prints the count to the console Solution C using System using SystemIO class FileIODemo static void Mainstring args string filePath inputtxt Replace with your file path int wordCount 0 try using StreamReader reader new StreamReaderfilePath string line while line readerReadLine null string words lineSplit wordCount wordsLength ConsoleWriteLineNumber of words in the file wordCount catch Exception ex ConsoleWriteLineError exMessage 9 Key takeaway This exercise introduces file inputoutput operations in C allowing you to interact with files and manipulate their contents Conclusion By working through these exercises youll develop a strong foundation in C programming progressing from basic syntax to more complex concepts like objectoriented programming exception handling and file IO Remember consistency and a focus on understanding are key to mastering any programming language Keep practicing experiment with new ideas and dont be afraid to ask for help when you encounter challenges Happy coding