C Programming Notesss
C Programming Notesss
Key Features of C:
1. Simple and Efficient: The basic syntax style of implementing C language is very simple and
easy to learn. This makes the language easily comprehensible and enables a programmer to
redesign or create a new application.
2. Mid-level programming language: C is considered as a middle-level language because it
supports the feature of both low-level and high-level languages. C language program is
converted into assembly code, it supports pointer arithmetic (low-level), but it is machine
independent (a feature of high-level).
3. Structured Programming Lang: C is a structured programming language in the sense that we
can break the program into parts using functions. So, it is easy to understand and modify.
4. System programming language: A system programming language is used to create system
software. C language is a system programming language because it can be used to do low-
level programming (for example driver and kernel). It is generally used to create hardware
devices, OS, drivers, kernels, etc. For example, Linux kernel is written in C.
5. Portability: Code written in C can run on various machines with little or no modification.
{ // Starting brace
} // Closing Braces
You have seen a basic structure of C program, so it will be easy to understand other basic building
blocks of the C programming language.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a
string literal, or a symbol. For example, the following C statement consists of five tokens:
printf("Hello, World! \n");
The individual tokens are:
printf
(
"Hello, World! \n"
)
;
Page |1
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
Semicolons ;
In C program, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.
For example, following are two different statements:
printf("Hello, World! \n");
return 0;
Explanation:
• #include <stdio.h> : Includes the Standard Input Output library.
• int main(): Entry point of the program. int denotes the return type.
• printf("Hello, World!\n"); : Prints the string to the console.
• return 0; : Indicates that the program ended successfully.
Writing comments is a way to provide additional information and describe the logic, purpose, and
functionality of your code.
Comments provide a way to document your code and make it more readable and understandable for
anyone who will read and work with it.
• Single-line comments
• Multi-line comments
Single-line comments start with two forward slashes, //
Example:-
// I am a single-line comment
Multi-line comments start with a forward slash, /, followed by an asterisk, *, and end with an asterisk,
followed by a forward slash.
Page |2
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
They offer a way to write slightly longer explanations or notes within your code and explain in more detail
how it works.
Example:-
/*
This is
a multi-line
comment
*/
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An
identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters,
underscores, and digits 0 to 9.
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in C.
Here are some examples of acceptable identifiers:
Mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constant or variable or any other identifier names.
auto else long switch unsigned
break return char float short
const for void sizeof if while
do int double……………….
Surround the text you want to display in double quotation marks, "", and make sure it is inside the
parentheses() of the printf() function.
The semicolon ; , terminates the statement. All statements need to end with a semicolon in C, as it
identifies the end of the statement.
Another escape sequence is \t. The \t represrents a tab character, and will insert a space within a string.
Page |4
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
In the example above, I declared a variable named age that will hold integer values.
Lastly, variable names are case-sensitive. For example, age is different from Age.
#include <stdio.h>
int main(void) {
// the variable age with its original value
int age = 29;
// changing the value of age
// the new value will be 30
age = 30;
}
Page |5
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
Here is an example:-
#include <stdio.h>
int main(void) {
char initial = 'D';
}
• Notice how I used single quotation marks around the single character.
• This is because you can't use double quotes when working with chars.
• Double quotes are used for strings.
Here is how you create a variable that will hold an int value:
#include <stdio.h>
int main(void) {
int age = 29;
}
#include <stdio.h>
int main(void) {
float temperature = 68.5;
}
#include <stdio.h>
int main(void) {
double number = 3.14159;
}
Page |6
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
Format Codes in C
Format codes are used in input and output functions, such as scanf() and printf(), respectively.
The syntax for format codes is the % character and the format specifier for the data type of the variable.
#include<stdio.h>
int main(void)
{
int age = 29;
printf("My age is %i\n", age); // My age is 29
}
In the program's output, %i is replaced with the value of age, which is 29.
You can create a constant in a similar way to how you create variables.
The differences between constants and variables is that with constants you have to use
the const keyword before mentioning the data type.
The constant's name, LUCKY_NUM, is in uppercase letters, as this is a best practice and distinguishes
constants from variables.
Chapter 3: Operators
In C programming language, an operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
• Arithmetic operators: They perform math operations like addition (+), subtraction (-),
multiplication (*), division (/), and modulus (%), which gives the remainder of a division.
For. Eg:-
#include <stdio.h>
int main(void) {
int a = 5;
int b = 3;
int sum = a + b;
printf("Sum: %i\n", sum); // Output: Sum: 8
}
• Relational operators: These compare values. For example, == checks if two values are equal,
!= checks if they're not equal,
> checks if one value is greater than another, and so on.
For. Eg:-
#include <stdio.h>
int main(void) {
int a = 5;
int b = 5;
int result = (a == b);
printf("Result: %i\n", result); // Output: Result: 1
}
In the above example, the result is 1 (true), because a and b are equal.
• Logical operators: These work with boolean values (true or false). && means "and", || means
"or", and ! means "not".
Page |8
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
Example :
#include <stdio.h>
int main() {
// Define boolean variables (0 for false, non-zero for true)
int a = 1; // true
int b = 0; // false
// Logical AND
int result_and = a && b;
printf("a AND b is: %d\n", result_and); // Output: 0 (false)
// Logical OR
int result_or = a || b;
printf("a OR b is: %d\n", result_or); // Output: 1 (true)
// Logical NOT
int result_not = !a;
printf("NOT a is: %d\n", result_not); // Output: 0 (false)
return 0;
}
• Assignment operators: They assign values to variableS. For instance, = assigns a value to a
variable, += Adds b to a and assigns the result to a (equivalent to a = a + b). For Eg :-
#include <stdio.h>
int main(void) {
In the example above, the value 10 is assigned to the variable num using the assignment operator.
• Increment and decrement operators: They increase or decrease the value of a variable by 1. ++
adds 1, -- subtracts 1.
For Eg;-
#include <stdio.h>
int main(void) {
Page |9
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
printf("Num: %i\n", num); // Num: 11
• Bitwise operators: These work on individual bits of values. For example, & performs a bitwise
AND operation, | performs a bitwise OR operation, ^ performs a bitwise XOR operation, and ~
performs a bitwise NOT operation.
• This operator performs a logical AND operation on each bit of the operands. The result is 1 if both
corresponding bits are 1, otherwise, it is 0.
Bitwise OR (|)
• This operator performs a logical OR operation on each bit of the operands. The result is 1 if at least
one of the corresponding bits is 1, otherwise, it is 0.
• This operator performs a logical XOR operation on each bit of the operands. The result is 1 if the
corresponding bits are different, otherwise, it is 0.
• This operator inverts each bit of the operand. The result is the one's complement of the operand.
1. This operator shifts the bits of the first operand to the left by the number of positions specified by
the second operand. Each shift to the left effectively multiplies the number by 2.
• This operator shifts the bits of the first operand to the right by the number of positions specified by
the second operand. Each shift to the right effectively divides the number by 2.
#include <stdio.h>
int main() {
int a = 5; // 0101 in binary
int b = 3; // 0013 in binary
int result = a | b; // 0111 in binary (7 in decimal)
P a g e | 10
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
• In this chapter, you will learn how to make decisions and control the flow of a program.
• You get to set the rules on what happens next in your programs by setting conditions using
conditional statements.
The primary conditional statements in C are :- if, if-else, else if, and switch.
1. if Statement
❖ It makes a decision based on a condition.
❖ If the given condition evaluates to true only then is the code inside the if block executed.
❖ If the given condition evaluates to false, the code inside the if block is ignored and skipped.
Syntax:
if (condition) {
// code to be executed if condition is true
}
Example:
#include <stdio.h>
int main() {
int num = 10;
if (num > 5) {
printf("Number is greater than 5.\n");
}
return 0;
}
2. if-else Statement
The if-else statement allows you to execute one block of code if the condition is true and another
block of code if the condition is false.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example: 1
P a g e | 11
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
#include <stdio.h>
int main() {
int num = 3;
if (num > 5) {
printf("Number is greater than 5.\n");
} else {
printf("Number is not greater than 5.\n");
}
return 0;
}
Example: 2
#include <stdio.h>
int main(void) {
int age;
printf("Please enter your age: ");
scanf("%i", &age);
if (age < 18) {
printf("You need to be over 18 years old to continue\n");
} else {
printf("You are over 18 so you can continue \n");
}
}
3. if-else if Statement
The if-else if statement allows you to check multiple conditions. Once a condition is found to
be true, the corresponding block of code is executed and the rest are skipped.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Example:1
#include <stdio.h>
int main() {
int num = 8;
if (num > 10) {
P a g e | 12
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
printf("Number is greater than 10.\n");
} else if (num > 5) {
printf("Number is greater than 5 but less than or equal to 10.\n");
} else {
printf("Number is 5 or less.\n");
}
return 0;
Example: 2
#include <stdio.h>
int main(void) {
int age;
printf("Please enter your age: ");
scanf("%i", &age);
if (age < 18) {
printf("You need to be over 18 years old to continue\n");
} else if (age < 21) {
printf("You need to be over 21\n");
} else {
printf("You are over 18 and older than 21 so you can continue \n");
}
}
4. switch Statement
The switch statement is used to perform different actions based on different values of a single variable. It
provides a way to check a variable against a list of values and execute corresponding blocks of code.
Syntax:
switch (variable) {
case value1:
// code to be executed if variable equals value1
break;
case value2:
// code to be executed if variable equals value2
break;
// you can have any number of case statements
default:
// code to be executed if variable doesn't match any case
}
Example:
#include <stdio.h>
int main() {
int num = 2;
P a g e | 13
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
switch (num) {
case 1:
printf("Number is 1.\n");
break;
case 2:
printf("Number is 2.\n");
break;
case 3:
printf("Number is 3.\n");
break;
default:
printf("Number is not 1, 2, or 3.\n");
}
return 0;
}
Chapter 5: Loops
In C programming, loops are used to execute a block of code repeatedly as long as a specified condition is
true.
There are three primary types of loops in C: for, while, and do-while.
1. for Loop
The for loop is typically used when you know in advance how many times you want to execute a
statement or a block of statements. It consists of three parts: initialization, condition, and
increment/decrement.
Syntax:
Example:
#include <stdio.h>
int main() {
int i;
return 0;
}
P a g e | 14
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
2. while Loop
The while loop executes a block of code as long as the specified condition is true. It checks the
condition before executing the block of code.
Syntax:
while (condition) {
// code to be executed
}
Example:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("Value of i: %d\n", i);
i++;
}
return 0;
}
3. do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the block of code will be
executed at least once, as the condition is checked after the execution of the block.
Syntax:
do {
// code to be executed
} while (condition);
Example:
#include <stdio.h>
int main() {
int i = 0;
do {
printf("Value of i: %d\n", i);
i++;
} while (i < 5);
return 0;
}
Chapter 6: Arrays
In C programming, an array is a collection of variables that are of the same data type. Arrays are used to
store multiple values in a single variable, instead of declaring separate variables for each value.
P a g e | 15
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
Declaration:
data_type array_name[array_size];
Initialization:
Example:
#include <stdio.h>
int main() {
// Declaration and initialization
int numbers[5] = {1, 2, 3, 4, 5};
return 0;
}
Chapter 7: Strings
Strings are everywhere in programming. They are used to represent names, messages, passwords, and
more.
A string is a sequence of characters, like letters, numbers, or symbols, that are used to represent text.
Make sure to include the null terminator, \0, as the last character to signify the end of the string.
To print the string, you use the printf() function, the %s format code and the name of the array:
#include <stdio.h>
int main() {
char phrase[] = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0'};
printf("%s\n", phrase);
int main() {
char word[] = "Hello";
}
P a g e | 16
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
int main() {
char phrase[] = "Hello";
}
-----------------------------------------------------
Output:
String length: 5
---------------------------------------------------
Chapter 8: Pointer
In C programming, a pointer is a variable that stores the memory address of another variable. Pointers
provide a powerful and flexible way to manipulate data and memory in a program.
Syntax of C Pointers
datatype * ptr;
Note: we can get the memory address of a variable with the reference
operator &:
we can get the value of the pointer variable with the dereference
operator * .
Example :
#include <stdio.h>
int main() {
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge
P a g e | 17
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
printf("%p\n", ptr);
Syntax of struct
struct structureName {
dataType member1;
dataType member2;
...
};
For example,
struct Person {
char name[50];
int citNo;
float salary;
};
#include <stdio.h>
P a g e | 18
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
};
int main() {
// Declare a variable of type struct Student
struct Student student;
return 0;
}
Notes
• The fgets function is used to reads a limited number of characters from a given file stream source
into an array of characters.
• The scanf function is used to read the roll number and marks.
• The printf function is used to display the student's details.
• The %. 2f format specifier is used to format the floating-point value with two decimal places
This simple program demonstrates the basic usage of structures in C, including defining a structure,
declaring a structure variable, reading input into the structure, and displaying the structure's data.
P a g e | 19
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
Example 1: Basic Input and Output
#include <stdio.h>
int main() {
int age;
float height;
char name[50];
// Output a message
printf("Enter your name: ");
// Input a string
scanf("%s", name);
return 0;
}
******************************************************************
Some C Programs
1. C Program to Print “Hello World”
#include <stdio.h>
int main()
{
printf("\n Hello World");
return 0;
}
------------------------------------------------
Output
Hello World
-------------------------------------------------
P a g e | 20
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
int main()
{
printf("Name : GeeksforGeeks");
return 0;
}
------------------------------
Output
Name : GeeksforGeeks
-------------------------------
2. Using scanf()
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
// user input will be taken here
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
------------------------------
Output:
Enter name: Mukul
Your name is Mukul.
------------------------------
// Printing values
printf("Printing Integer value %d", x);
return 0;
}
---------------------------------
Output
Printing Integer value 5
---------------------------------
4. C Program to Add Two Numbers
#include <stdio.h>
int main()
{
int number1, number2, sum;
P a g e | 21
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
P a g e | 22
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);
// Calculating product
product = a * b;
// %.2lf displays number up to 2 decimal point
printf("Product = %.2lf", product);
return 0;
}
return 0;
}
9. Program to calculate the power of double data value using the pow() function
#include <stdio.h>
#include <math.h>
int main ()
{
// declare base and exp variable
int base, exp;
int result; // store the result
printf (" Enter the base value from the user: ");
scanf (" %d", &base); // get base from user
printf (" Enter the power value for raising the power of base: ");
scanf (" %d", &exp); // get exponent from user
// use pow() function to pass the base and the exp value as arguments
result = pow ( base, exp);
printf (" %d to the power of %d is = %d ", base, exp, result);
return 0;
}
----------------------------------------------------------------
Output :
Enter the base value from the user: 7
Enter the power value for raising the power of base: 5
7 to the power of 5 is = 16807
P a g e | 23
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
------------------------------------------------------
int main() {
int i, number, factorial = 1;
P a g e | 24
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
// %d displays the integer value of a character
// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}
--------------------------------------------------
Output :
Enter a character: A
ASCII value of A = 65
---------------------------------------------------
int main() {
float num1, num2, average;
return 0;
}
int main() {
int number;
int absoluteValue;
// Input a number
printf("Enter an integer: ");
scanf("%d", &number);
P a g e | 25
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
// Display the result
printf("The absolute value of %d is %d\n", number, absoluteValue);
return 0;
}
int main() {
float principal, rate, time, simple_interest;
return 0;
}
int main() {
double principal, rate, time, compoundInterest;
printf("Enter the principal amount: ");
scanf("%lf", &principal);
printf("Enter the annual interest rate (in percentage): ");
scanf("%lf", &rate);
printf("Enter the time (in years): ");
scanf("%lf", &time);
compoundInterest = principal * (pow((1 + rate / 100), time) - 1);
printf("The compound interest after %.2lf years is: %.2lf\n", time,
compoundInterest);
return 0;
P a g e | 26
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
}
16. C program to find the cube of a number:
#include <stdio.h>
int main() {
int number, cube;
printf("Enter a number: ");
scanf("%d", &number);
cube = number * number * number;
printf("The cube of %d is %d\n", number, cube);
return 0;
}
17. C Program to print a value using biwise OR operator and scanf.
#include <stdio.h>
int main() {
int a, b;
// Perform bitwise OR
int result = a | b;
return 0;
}
--------------------------------------------------------
Output:
Enter the first integer (a): 6
Enter the second integer (b): 5
a = 6, b = 5
a | b = 7
--------------------------------------------------------
18. C Program to Swap Numbers Using Temporary Variable
#include<stdio.h>
int main() {
int first, second, temp;
printf("Enter first number: ");
scanf("%d", &first);
printf("Enter second number: ");
P a g e | 27
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
scanf("%d", &second);
int main() {
int number;
return 0;
}
20. C Program to Check Whether a Number is Positive or Negative Using Nested if...else
#include <stdio.h>
int main() {
P a g e | 28
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
double num;
printf("Enter a number: ");
scanf("%lf", &num);
if (num <= 0.0) {
if (num == 0.0)
printf("You entered 0.");
else
printf("You entered a negative number.");
}
else
printf("You entered a positive number.");
return 0;
}
----------------------------------------------------------
Output :
Enter a number: 2
You entered a positive number.
Enter a number: -2
You entered a negative number.
Enter a number: 0
You entered 0.
------------------------------------------------------------
21. C Program to Check Whether a Number is Positive or Negative Using if...else if.
#include <stdio.h>
int main() {
double num;
printf("Enter a number: ");
scanf("%lf", &num);
if (num < 0) {
P a g e | 29
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
22. C Program to Print Even Numbers from 1 to N using For Loop and If.
#include <stdio.h>
int main()
{
int N, i;
// Prompt the user to enter the value of N
printf("Enter the value of N: ");
scanf("%d", &N);
// Print even numbers from 1 to N
printf("Even numbers from 1 to %d are:\n", N);
for (i = 1; i <= N; i++)
{
if (i % 2 == 0)
{
printf("%d ", i);
}
}
printf("\n");
return 0;
}
Output :
------------------------------------------------
Enter the value of N: 10
Even numbers from 1 to 10 are:
2 4 6 8 10
------------------------------------------------
23. C Program to Find Largest of Two Numbers using If-Else If Statement.
#include <stdio.h>
int main()
{
int num1, num2;
// Prompt the user to enter two integers
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
// Determine the larger number
if (num1 > num2)
{
printf("The larger number is: %d\n", num1);
}
else if (num2 > num1)
{
printf("The larger number is: %d\n", num2);
}
else
{
printf("Both numbers are equal.\n");
P a g e | 30
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
}
return 0;
}
----------------------------------------------
Output :
Enter two integers: 50 100
The larger number is: 100
---------------------------------------------
24. Program to print large number Using if statement.
#include<stdio.h>
main()
{
int a, b;
printf("enter a:");
scanf("%d",&a);
printf("enter b:");
scanf("%d",&b);
if(a>b)
{
printf("a is large");
}
}
----------------------------------------------
Output
• enter a:14 enter b: 12 a is large
• enter a:19 enter b: 25
---------------------------------------------
P a g e | 31
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
}
-----------------------------------------------------------------------------
Output
Enter your marks? 31 Sorry You FAILED
Enter your marks? 478 You are placed in THIRD CLASS
Enter your marks? 545 You are placed in SECOND CLASS
Enter your marks? 726 Congrats ! you are place in the FIRST CLASS
-------------------------------------------------------------------------------
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
printf("%c is an alphabet.", c);
else
printf("%c is not an alphabet.", c);
return 0;
}
------------------------------------------------------
Output :
Enter a character: *
* is not an alphabet.
Enter a character: G
G is an alphabet.
------------------------------------------------------
28. C Program to Calculate the Sum of Natural Numbers
#include <stdio.h>
P a g e | 32
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
int main() {
int n, i, sum = 0;
P a g e | 33
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
-----------------------------------------------------
31. C Program for Simple Calculator
#include <stdio.h>
int main() {
int num1, num2;
char operator;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter second number: ");
scanf("%d", &num2);
switch (operator)
{
case '+':
printf("Result: %d\n", num1 + num2);
break;
case '-':
printf("Result: %d\n", num1 - num2);
break;
case '*':
printf("Result: %d\n", num1 * num2);
break;
case '/':
if (num2 != 0)
printf("Result: %d\n", num1 / num2);
else
printf("Error: Division by zero\n");
break;
default:
printf("Invalid operator\n");
}
return 0;
}
--------------------------------------------------
Output :
Enter first number: 9
Enter an operator (+, -, *, /): *
Enter second number: 10
Result: 90
-----------------------------------------------------
**************Best Of Luck****************
P a g e | 34