0% found this document useful (0 votes)
18 views34 pages

C Programming Notesss

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views34 pages

C Programming Notesss

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari

Chapter 1: Introduction to C Programming


C is a powerful general-purpose programming language developed in the early 1970s by Dennis Ritchie at
Bell Labs. It is widely used for system programming, developing operating systems, and embedded systems
due to its efficiency and control over hardware.

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.

Basic Structure of a C Program


#include <stdio.h> // Preprocessor directive or Calling header files

int main() // Main function where execution begins

{ // Starting brace

printf("Hello, World!\n"); // Print statement

return 0; // Return statement

} // 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.

What Are Header Files in C?


• The #include part of #include <stdio.h> is a preprocessor command that tells the C compiler to
include a file.
• Specifically, it tells the compiler to include the stdio.h header file. The stdio.h header file stands for
standard input-output.
• If you don't include the stdio.h file at the top of your code, the compiler will not understand what
the printf() function is.

What is the main() function in C?


• Next, int main(void) {} is the main function and starting point of every C program.
• It is the first thing that is called when the program is executed.
• Every C program must include a main() function.
• The int keyword in int main(void) {} indicates the return value of the main() function.
• And the void keyword inside the main() function indicates that the function receives no arguments.
• Anything inside the curly braces, {}, is considered the body of the function

What Are Comments in C?


In C programming, comments are lines of text that get ignored by the compiler.

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.

There are two types of comments in C:

• 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……………….

What is the printf() function in C?


The printf() function is used for output. It prints the given statement to the console, defined in
stdio.h (header file).
Syntax :
printf("format string", argument_list);
Inside the function's body, the line printf("Hello World!\n"); prints the text Hello, World! to the
console (this text is also known as a string).

Whenever you want to display something, use the printf() function.

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.

What is the scanf() function in C?


• The scanf() function is used for input ,defined in stdio.h (header file). It reads the
input data from the console.
Syntax:
scanf("format string", &argument_list);
Page |3
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
• The format string can be
%d for integer,
%f for floating point number,
%c for single character,
%s for a string etc.

What Are Escape Sequences in C?


Did you notice the \n at the end of printf("Hello, World!\n");?
It's called an escape sequence, which means that it is a character that creates a newline and tells the cursor
to move to the next line when it sees it.

Another escape sequence is \t. The \t represrents a tab character, and will insert a space within a string.

Chapter 2: Variables and Data Types


In this chapter, you will learn the basics of variables and data types
By the end of this chapter, you will know how to declare and initialize variables.
You will also have learned about various data types available in C, such as integers, floating-point numbers,
and characters.
What Is a Variable in C?
• A variable is a name of the memory location. It is used to store data. Its value can be changed, and it
can be reused many times.
• It is a way to represent represent memory location location through symbol so that it can be easily
identified.
• Let's see the syntax to declare a variable:
data_type variable_list;

Rules for defining variables


• A variable can have alphabets, digits, and underscore.
• A variable name must start with an alphabet, and underscore only. It can't start with a digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or keyword, e.g. int, float, etc.
• Valid variable names:
int a; int _ab; int a30;
• Invalid variable names:
int 2; int a b; int long;

How to Declare Variables in C


Before you can use a variable, you need to declare it – this step lets the compiler know that it should
allocate some memory for it.

The general syntax for declaring variables


data_type variable_name;

Let's take the following example:


#include <stdio.h>
int main(void)
{
int age;
}

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.

How to Initialize Variables in C


Once you've declared a variable, it is a good practice to intialize it, which involves assigning an initial value
to the variable.
The general syntax for initialzing a variable
data_type variable_name = value;
The assignment operator, =, is used to assign the value to the variable_name.

Let's take the previous example and assign age a value:


#include <stdio.h>
int main(void)
{
int age;
age = 29;
}
I initialized the variable age by assigning it an integer value of 29.

How to Update Variable Values in C


• The values of variables can change.
• For example, you can change the value of age without having to specify its type again.
• Here is how you would change its value from 29 to 30:

#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;
}

What Is a Basic Data Types in C?


Data types specify the type of form that information can have in C programs. And they determine what kind
of operations can be performed on that information.
There are various built-in data types in C such as char, int, and float.
Each of the data types requires different allocation of memory.

char Data Type


• The most basic data type in C is char.
• It stands for "character" and it is one of the simplest and most fundamental data types in the C
programming language.
• You use it to store a single individual character such as an uppercase and lowercase letter
• Some examples of chars are 'a' and 'Z'.

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.

int Data Type


• An int is an integer, which is also known as a whole number.
• It can hold a positive or negative value or 0, but it can't hold numbers that contain decimal points
(like 3.5).
• Some examples of integers are 0, -3,and 9.

Here is how you create a variable that will hold an int value:
#include <stdio.h>
int main(void) {
int age = 29;
}

float Data Type


• The float data type is used to hold numbers with a decimal value (which are also known as real
numbers).
• It holds 4 bytes (or 32 bits) of memory and it is a single-precision floating-point type.
• Here is how you create a variable that will hold a float value:

#include <stdio.h>
int main(void) {
float temperature = 68.5;
}

Double Data Type


• A double is a floating point value and is the most commonly used floating-point data type in C.
• It holds 8 bytes (or 64 bits) of memory, and it is a double-precision floating-point type.
• Here is how you create a variable that will hold a double value:

#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.

Let's take the following example:

#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.

FORMAT SPECIFIER DATA TYPE


%c char
%c unsigned char
%i, &d Int
%u unsigned int
%f float
%lf double
%Lf long double
……………. ……………..
…………….. …………..

What are Constants in C?


In C, a constant is a variable with a value that cannot be changed after declaration and during the program's
execution.

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 general syntax for declaring constants


const data_type constant_name = value;

Example of how to create a constant in C:-


#include <stdio.h>
int main(void) {
const int LUCKY_NUM = 7;
Page |7
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari

printf("My lucky number is: %i\n", LUCKY_NUM);


}
In this example, LUCKY_NUM is defined as a constant with a value of 7.

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".

Here are the logical operators used in C:


OPERATOR NAME OF OPERATOR
&& Logical AND
|| Logical OR
! Logical 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) {

// declare an integer variable named num


int num;

// assign the value 10 to num


num = 10;
printf("num: %i\n", num); // Output: num: 10
}

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) {

int num = 10;


num++;

Page |9
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
printf("Num: %i\n", num); // Num: 11

The initial value of the variable num is 10.

By using the -- increment operator, the value of num is now set to 9.


This is like perfoming num = num - 1.

• 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.

Bitwise AND (&)

• 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.

Bitwise XOR (^)

• 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.

Bitwise NOT (~)

• This operator inverts each bit of the operand. The result is the one's complement of the operand.

Left Shift (<<)

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.

Right Shift (>>)

• 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.

For Eg;- bitwise OR operator

#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

printf("a = %d, b = %d\n", a, b);


printf("a | b = %d\n", result); // Output: 7
return 0;
}
Chapter 4: Conditional Statements

• 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:

for (initialization; condition; increment/decrement)


{
// code to be executed
}

Example:

#include <stdio.h>

int main() {
int i;

for (i = 0; i < 5; i++) {


printf("Value of i: %d\n", 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

Declaring and Initializing Arrays

Declaration:

data_type array_name[array_size];

Initialization:

data_type array_name[array_size] = {value1, value2, ..., valueN};

Example:
#include <stdio.h>

int main() {
// Declaration and initialization
int numbers[5] = {1, 2, 3, 4, 5};

// Accessing array elements


for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, numbers[i]);
}

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);

Another way to create a string in C is to use a string literal.


In this case, you create an array of characters and then assign the string by enclosing it in double quotes:
#include <stdio.h>

int main() {
char word[] = "Hello";
}

P a g e | 16
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari

To calculate the length of a string, use the strlen() function:


#include <stdio.h>
#include <string.h>

int main() {
char phrase[] = "Hello";

int length = strlen(phrase);

printf("String length: %i\n", length);

}
-----------------------------------------------------
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

// Output the value of myAge


printf("%d\n", myAge);

// Output the memory address of myAge


printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer

P a g e | 17
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari

printf("%p\n", ptr);

// Output the value of myAge with the pointer


printf("%d\n", *ptr);
return 0;
}
-----------------------------------------------------
Output:
43
0x7ffe5367e044
0x7ffe5367e044
43
------------------------------------------------

Chapter 9: C Structures (structs)


In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single
name.. Each variable in the structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, float, char, etc.).

Syntax of struct
struct structureName {
dataType member1;
dataType member2;
...
};

For example,
struct Person {
char name[50];
int citNo;
float salary;
};

Simple C Program Using Structures


This program defines a structure to store information about a student, takes input from the user to
populate the structure, and then displays the student's details.

#include <stdio.h>

// Define a structure to hold student details


struct Student {
char name[50];
int rollNumber;
float marks;

P a g e | 18
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari
};

int main() {
// Declare a variable of type struct Student
struct Student student;

// Input student details


printf("Enter student name: ");
fgets(student.name, sizeof(student.name), stdin); // Read a line of
text
printf("Enter roll number: ");
scanf("%d", &student.rollNumber);
printf("Enter marks: ");
scanf("%f", &student.marks);

// Display student details


printf("\nStudent Details:\n");
printf("Name: %s", student.name); // No need for '\n' because fgets
includes the newline character
printf("Roll Number: %d\n", student.rollNumber);
printf("Marks: %.2f\n", student.marks);

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.

Chapter 10: Input/Output


In C programming, input and output operations are essential for interacting with the user. The standard
input/output library in C is stdio.h, which provides functions like printf, scanf, gets, puts, fgets,
etc., for handling input and output.
Basic Input and Output Functions

1. printf - Used to print formatted output to the screen.


2. scanf - Used to read formatted input from the keyboard.
3. gets - Used to read a string from the keyboard (not recommended due to safety issues, use fgets
instead).
4. puts - Used to write a string to the screen.
5. fgets - Used to read a string from the keyboard safely.

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);

printf("Enter your age: ");


// Input an integer
scanf("%d", &age);

printf("Enter your height (in meters): ");


// Input a float
scanf("%f", &height);

// Output the inputted values


printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Height: %.2f meters\n", height);

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
-------------------------------------------------

2. C Program To Print Your Own Name


Here, we can use the 2 different approaches to print the name:
1. Using printf()
#include <stdio.h>

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.
------------------------------

3. C program to print the integer value:


#include <stdio.h>
// Driver code
int main()
{
// Declaring integer
int x = 5;

// 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

printf(" Enter two integer values \n ");


scanf("%d %d", &number1, &number2);

sum = number1 + number2;

printf(" Sum of the two integer values is %d", sum);


return 0;
}

5. Program to print cube of given number


#include<stdio.h>
main()
{
int number, cube;
printf("enter a number:");
scanf("%d",&number);
cube=number*number*number;
printf(“ cube of number is:%d “ cube,);
}
-------------------------------------------------------------
Output :
enter a number:5
cube of number is:125
----------------------------------------------------------------
6. Program to print sum of 2 integer numbers
#include<stdio.h>
main()
{
int x=0,y=0,result;
printf("enter first number:");
scanf("%d",&x);
printf("enter second number:");
scanf("%d",&y);
result=x+y;
printf("sum of 2 numbers:%d ",result);
}
------------------------------------------------------------
Output
enter first number:19
enter second number:11
sum of 2 numbers:30
-------------------------------------------------------------
7. Program to Multiply Two Numbers
#include <stdio.h>
int main() {
double a, b, product;

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;
}

8. Program to Multiply Two floating point Numbers.


#include <stdio.h>
int main() {
double a, b, product;
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;
}
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
------------------------------------------------------

10. C Program to Display Factors of a Number


#include <stdio.h>
int main() {
int num, i;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Factors of %d are: ", num);
for (i = 1; i <= num; ++i) {
if (num % i == 0) {
printf("%d ", i);
}
}
return 0;
}
------------------------------------------------------
Output :
Enter a positive integer: 60
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60
------------------------------------------------------

C program to find the factorial of a number using for Loop.


#include<stdio.h>

int main() {
int i, number, factorial = 1;

printf("Enter a number: ");


scanf("%d",&number);

for(i=1; i<=number; i++) {


factorial = factorial * i;
}

printf("Factorial of %d is: %d",number, factorial);


return 0;
}
--------------------------------------------------
Output :
Enter a number: 60
Factorial of 60 is: 0
---------------------------------------------------

11. C Program to Print ASCII Value


#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);

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
---------------------------------------------------

12. C Program to Find Average of Two Numbers


#include <stdio.h>

int main() {
float num1, num2, average;

// Input two numbers


printf("Enter first number: ");
scanf("%f", &num1);

printf("Enter second number: ");


scanf("%f", &num2);

// Calculate the average


average = (num1 + num2) / 2;

// Display the result


printf("The average of %.2f and %.2f is %.2f\n", num1, num2, average);

return 0;
}

13. C program to find the absolute value of a number:


#include <stdio.h>
#include <stdlib.h> // Include this header for the abs() function

int main() {
int number;
int absoluteValue;

// Input a number
printf("Enter an integer: ");
scanf("%d", &number);

// Calculate the absolute value


absoluteValue = abs(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;
}

14. C program to calculates the simple interest


#include <stdio.h>

int main() {
float principal, rate, time, simple_interest;

// Input principal amount


printf("Enter the principal amount: ");
scanf("%f", &principal);

// Input annual interest rate


printf("Enter the annual interest rate (percent): ");
scanf("%f", &rate);

// Input time period in years


printf("Enter the time period (in years): ");
scanf("%f", &time);

// Calculate simple interest


simple_interest = (principal * rate * time) / 100.0;

// Output the calculated simple interest


printf("Simple Interest = %.2f\n", simple_interest);

return 0;
}

15. C Program to Calculate Compound Interest


#include <stdio.h>
#include <math.h>

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;

// Prompt the user for input


printf("Enter the first integer (a): ");
scanf("%d", &a);

printf("Enter the second integer (b): ");


scanf("%d", &b);

// Perform bitwise OR
int result = a | b;

// Output the result


printf("a = %d, b = %d\n", a, b);
printf("a | b = %d\n", result);

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);

// value of first is assigned to temp


temp = first;

// value of second is assigned to first


first = second;

// value of temp (initial value of first) is assigned to second


second = temp;

// %.2lf displays number up to 2 decimal points


printf("\nAfter swapping, first number = %d\n", first);
printf("After swapping, second number = %d", second);
return 0;
}
--------------------------------------------------------
Output:
Enter first number: 66
Enter second number: 33

After swapping, first number = 33


After swapping, second number = 66
--------------------------------------------------------

19. C Program to Check Number is Odd or Even


#include <stdio.h>

int main() {
int number;

// Prompt the user to enter a number


printf("Enter a number: ");
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;
}

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) {

printf("You entered a negative number.");


}
else if (num>0)
printf("You entered a positive number.");
else if (num==0)

printf("You entered 0.");


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.
------------------------------------------------------------

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
---------------------------------------------

25. Program to print large number Using if-else 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");
}
else
{
printf("b is large");
}
}
-----------------------------------------------------
Output :
enter a:14 enter b: 12 a is large
enter a:19 enter b: 25 b is large
------------------------------------------------------

P a g e | 31
HOPE COMPUTER INSTITUTE, Rajbiraj-5, Saptari

26. Program to prepare the result of the student Using if-else-if.


#include <stdio.h>
main()
{ int marks;
printf("Enter your marks?"); scanf("%d",&marks);
if(marks >=600)
{ printf("Congrats ! you are place in the FIRST CLASS"); }
else if (marks >=500)
{ printf("You are placed in the SECOND CLASS"); }
else if (marks >= 400
)
{ printf("You are placed in the THIRD CLASS"); }
else

{ printf("Sorry you FAILED"); }

}
-----------------------------------------------------------------------------
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
-------------------------------------------------------------------------------

27. C Program to Check Whether a Character is an Alphabet or not.


#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);

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;

printf("Enter a positive integer: ");


scanf("%d", &n);

for (i = 1; i <= n; ++i) {


sum += i;
}

printf("Sum = %d", sum);


return 0;
}
----------------------------------------------------
Output :
Enter a positive integer: 10
Sum = 55
----------------------------------------------------
29.C Program to Generate Multiplication Table
#include <stdio.h>
int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);

for (int i = 1; i <= 5; ++i) {


printf("%d * %d = %d \n", n, i, n * i);
}
return 0;
}
------------------------------------------
Output :
Enter an integer: 2
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
--------------------------------------------

30. C Program to Display Characters from A to Z Using Loop


#include <stdio.h>
int main() {
char c;
for (c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
return 0;
}
----------------------------------------------------
Output :

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

You might also like