0% found this document useful (0 votes)
46 views

Programming Short Note 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Programming Short Note 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

C Basics Summary

______________________________________________________

1. Header Files
Header files are used to include predefined functions and libraries in your C
program.

Commonly used headers include <stdio.h> for input/output


Example
#include <stdio.h>

2. Input and Output:


printf() is used for output. It displays text and variable values on the screen.

scanf() is used for input. It reads data from the user or a file and stores it in
variables.
Example
#include <stdio.h>

int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You entered: %d\n", age);
return 0;
}

3. Variables:
Variables are used to store data. They must be declared with a data type before use
(e.g., int, float, char).

In C (Or in any programming language), variable names must adhere to certain


rules and conventions to ensure clarity and maintainability in your code.

● Variable names can consist of letters (both uppercase and lowercase),


digits, and underscores.
● They must begin with a letter or an underscore.
● Variable names should be meaningful and describe the purpose of the
variable. This makes your code more readable.
● Avoid Reserved Keywords: Don't use language-specific reserved
keywords (e.g., if, int, while) as variable names.
Example

/*Examples of good variable names in C (following CamelCase


convention):*/
int numberOfStudents;
float averageScore;
char userName;

/*Examples of good variable names in C (following underscore


separation convention):*/
int num_of_students;
float average_score;
char user_name;

4. Main Method:
Every C program must have a main method.

It's the entry point of the program where execution begins.

Example main method:


Example
int main()
{
int x = 5;
printf("Hello, world!\n");
printf("The value of x is: %d\n", x);
return 0; // Indicates successful program execution

}
C Loop Structures Summary
______________________________________________________

1. for Loop
It consists of three main parts: initialization, condition, and update.

Syntax
for (initialization; condition; update) {
// Loop body code
}

Initialization: Initializes a control variable.


Condition: Specifies the loop continuation condition.
Update: Modifies the control variable in each iteration.

Example
for (int i = 0; i < 5; i++) {
// Loop body code executed 5 times
}

2. while Loop
The loop continues as long as a specified condition is true.

Syntax
while (condition) {
// Loop body code
}

Condition: Specifies the loop continuation condition.

Example
int i = 0;
while (i < 5) {
// Loop body code executed while i < 5
i++;
}
3. do-while Loop
The do-while loop is similar to the while loop, but it always executes the loop body at
least once because the condition is checked after the first iteration.
The loop continues as long as a specified condition is true.

Syntax
do {
// Loop body code
} while (condition);

Condition: Specifies the loop continuation condition.

Example
int i = 0;
do {
// Loop body code executed at least once
i++;
} while (i < 5);

Loop Control Statements


In addition to the basic loop structures, C provides loop control statements:

break: Exits the loop prematurely.

The break statement is used within a loop to exit the loop prematurely. When
encountered, it immediately terminates the loop, and control passes to the statement
immediately following the loop.

Example
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
// Loop body code
}
In this example, when i becomes equal to 5, the break statement is executed, and the loop
is terminated, bypassing the remaining iterations.

continue: Skips the current iteration and continues with the next one.
The continue statement is used within a loop to skip the current iteration and continue
with the next one. When encountered, it immediately moves to the next iteration of the
loop, skipping any code below it for the current iteration.

Example
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
continue; // Skip even values of i
}
// Loop body code
}

In this example, when i is even (i.e., i % 2 == 0), the continue statement is executed, and
the loop proceeds to the next iteration without executing the code following it for that
iteration.
C conditional statements
______________________________________________________
1. if Statement
The if statement is used to execute a block of code only if a specified condition is true. If
the condition is false, the block of code is skipped.
Syntax
if (condition) {
// Code to execute if condition is true
}

Example
int age = 25;
if (age >= 18) {
printf("You are an adult.\n");
}

2. else Statement
The else statement is used in conjunction with if to specify a block of code to execute if
the if condition is false.

Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

Example
int age = 15;
if (age >= 18) {
printf("You are an adult.\n");
} else {
printf("You are a minor.\n");
}

3. else if Statement
The else if statement allows you to specify multiple conditions to test in sequence. It is
used when you have multiple possible outcomes.
Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if no conditions are true
}

Example
int score = 75;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}

4. Conditional Operator (? :)
The conditional operator, also known as the ternary operator, provides a compact way to
write simple if-else statements.

Syntax
(condition) ? expression_if_true : expression_if_false;

Example
int age = 20;
char* status = (age >= 18) ? "Adult" : "Minor";
printf("Status: %s\n", status);

5. Switch cases
In C, the switch statement provides a way to select one of many code blocks to be
executed based on the value of a given expression. It's often used when you have a
specific value or expression to compare against multiple possible cases.
Syntax
switch (expression) {
case constant1:
// Code to execute if expression matches constant1
break;
case constant2:
// Code to execute if expression matches constant2
break;
// Add more cases as needed
default:
// Code to execute if expression doesn't match any cases
}

● The switch statement evaluates the expression and then compares its value to each
case constant.
● If a match is found, the code block associated with that case is executed.
● The break statement is used to exit the switch block. Without break, execution
would continue into subsequent cases.
Example
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Weekend\n");
}
Discussion questions
______________________________________________________

1. Write a program in C to check a given number is even or odd.

#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");// Input
scanf("%d", &number);

// Check if the number is even or odd

if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}
return 0;
}

2. Write a C program that uses a while loop to print the numbers from 1 to 10 in ascending
order.

#include <stdio.h>
int main() {
int i = 1; // Initialize the loop variable

// Use a while loop to print numbers from 1 to 10


while (i <= 10) {
printf("%d ", i);
i++; // Increment the loop variable
}
printf("\n"); // Print a newline after the loop
return 0;
}

3. Write a C program that takes a numeric grade as input (e.g., 1, 2, 3, 4, 5) and converts it
into a corresponding letter grade (A, B, C, D, F) using a switch-case statement. The
grading scale is as follows:
a. Grade 1: A
b. Grade 2: B
c. Grade 3: C
d. Grade 4: D
e. Grade 5: F

Write a program that accepts the numeric grade as input and then outputs the
corresponding letter grade based on the provided scale using a switch-case statement.

#include <stdio.h>
int main() {
int numericGrade;
printf("Enter a numeric grade (1-5): ");// Input
scanf("%d", &numericGrade);

// Convert numeric grade to letter grade using switch-case


switch (numericGrade) {
case 1:
printf("Letter Grade: A\n");
break;
case 2:
printf("Letter Grade: B\n");
break;
case 3:
printf("Letter Grade: C\n");
break;
case 4:
printf("Letter Grade: D\n");
break;
case 5:
printf("Letter Grade: F\n");
break;
default:
printf("Invalid grade.Enter a grade between 1 and 5.\n");
break;
}

return 0;
}
4. Write a C program to read the age and citizenship status of a person and determine
whether they are eligible to run for public office. The eligibility criteria for running for
public office are as follows:

a. The person must be at least 25 years old.


b. The person must be a citizen of the country.

Write a C program that takes the person's age and citizenship status (1 for citizen, 0 for
non-citizen) as inputs and outputs whether the person is eligible to run for public office
based on these criteria.

Either we can use logical operators or we can use nested if else

USing Logical Operators


#include <stdio.h>

int main() {
int age, is_citizen;

printf("Enter your age: "); // Input


scanf("%d", &age);

printf("Are you a citizen? (1 for yes, 0 for no): ");


scanf("%d", &is_citizen);

// Check eligibility using logical operators


if (age >= 25 && is_citizen == 1) {
printf("You are eligible to run for public office.\n");
} else {
printf("Sorry, you do not meet the eligibility criteria\n");
}

return 0;
}
Nested if-else

#include <stdio.h>

int main() {
int age, is_citizen;

// Input
printf("Enter your age: ");
scanf("%d", &age);

printf("Are you a citizen? (1 for yes, 0 for no): ");


scanf("%d", &is_citizen);

// Nested if-else statements to check eligibility for running


for public office
if (age >= 25) {
if (is_citizen == 1) {
printf("Congratulations! You are eligible to run for
public office.\n");
} else {
printf("You must be a citizen to run for public
office.\n");
}
} else {
printf("You must be at least 25 years old to run for
public office.\n");
}

return 0;
}

5. Write a program in C to display the pattern like a right angle triangle using an asterisk.
Expected Output :
*
**
***
****

#include <stdio.h>
void main()
{
int i,j,rows;
printf("Input number of rows : ");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
printf("*");
printf("\n");
}
}

6. Write a C program to determine whether a person is eligible for a driver's license. The
eligibility criteria are as follows:

a. The person must be at least 18 years old.


b. The person must pass a vision test.
c. The person must pass a written exam.

Write a C program that takes the person's age, vision test result (1 for pass, 0 for fail), and
written exam result (1 for pass, 0 for fail) as inputs and outputs whether the person is
eligible for a driver's license using nested if-else statements.
#include <stdio.h>

int main() {
int age, vision_test, written_exam;

// Input
printf("Enter your age: ");
scanf("%d", &age);

printf("Did you pass the vision test? (1 for pass, 0 for


fail): ");
scanf("%d", &vision_test);

printf("Did you pass the written exam? (1 for pass, 0 for


fail): ");
scanf("%d", &written_exam);

// Nested if-else statements to check eligibility for a


driver's license
if (age >= 18) {
if (vision_test == 1) {
if (written_exam == 1) {
printf("Congratulations! You are eligible for a
driver's license.\n");
} else {
printf("You need to pass the written exam to be
eligible for a driver's license.\n");
}
} else {
printf("You need to pass the vision test to be
eligible for a driver's license.\n");
}
} else {
printf("You must be at least 18 years old to be eligible
for a driver's license.\n");
}

return 0;
}
7. Write a C program that calculates the average of an array of 10 integers. The program
should do the following:

a. Initialize an array of 10 integers with some values.


b. Calculate and display the average of these 10 integers.

#include <stdio.h>

int main() {
int numbers[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int sum = 0;
double average;

// Calculate the sum of the array elements


for (int i = 0; i < 10; i++) {
sum += numbers[i];
}

// Calculate the average


average = (double)sum / 10.0;

printf("The average of the array is: %.2lf\n", average);

return 0;
}

8. Write a C program that finds the largest and smallest elements in an array of integers. The
program should do the following:

a. Initialize an array of 10 integers with some values.


b. Find and display the largest and smallest elements in the array.
#include <stdio.h>

int main() {
int numbers[10] = {15, 3, 7, 42, 8, 56, 23, 11, 5, 38};
int smallest = numbers[0]; // Assume the first element is
the smallest
int largest = numbers[0]; // Assume the first element is
the largest

// Find the smallest and largest elements


for (int i = 1; i < 10; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
if (numbers[i] > largest) {
largest = numbers[i];
}
}

printf("The smallest element in the array is: %d\n",


smallest);
printf("The largest element in the array is: %d\n", largest);

return 0;
}

You might also like