Below we have presented the complete notes of c programming for the beginner’s.
Introduction To Programming
→ Programming Language
A programming language is a set of instructions that tells a computer what to do.
Some of the most popular programming languages include:
- Python: A general-purpose language that is easy to learn and use.
- Java: A general-purpose language that is object-oriented and platform-independent.
- JavaScript: A scripting language that is used to create interactive web pages.
- C/C++: Low-level languages that are used for system programming and game development.
- SQL: A database language that is used to query and manipulate data.
→ Programming Approach
There is mainly two types of programming approach i.e.
1.Top-Down Approach
2.Bottom-Up Approach
1.Top-Down Approach
Top-down programming tends to generate modules that are based on functionality, usually in the form of functions or procedures.
- In this approach, It starts from top to bottom of a program.
- Function is considered as the basic unit.
Eg: C, Fortan etc.
2.Bottom-Up Approach
The bottom-up approach in programming refers to a method of problem-solving where you start by solving smaller, individual components of a problem before combining them to build a larger solution.
- In this approach, It starts from bottom to top.
- Data, object and class are considered as the basic unit.
Eg: C++, Java etc.
→ Structured Programming
Structured programming is a programming paradigm that focuses on organizing code into clear, well-defined structures and control flow.
The advantages of structured programming is presented below:
- Readability: Structured programming emphasizes code organization and readability. By using structured control flow constructs, the code becomes easier to understand and follow.
- Reduced complexity: Structured programming can help to reduce the complexity of programs, which makes them easier to develop and debug.
- Improved reliability: Structured programs are more reliable than unstructured programs, because they are less likely to contain errors.
- Debugging: With a clear control flow and modular design, structured programs are often easier to debug. Errors are more localized and can be easily traced back to specific modules or functions.
Basic Terminologies
- Source Code: The code of the program written in high level language (HLL) is called source code. It is not directly understandable by the computer. Translator converts the HLL into Machine language.
- Object Code: It is the compiled executable file that is compatible with particular platform (windows, Linux, macOS, etc.).It has the extension “.o”.
- Translator (Language Processor): It is type of Computer software that translates program code into machine code (i.e. 0s & 1s).
Type of Translators
- Interpreter:
It translates source code into machine code line by line. Example: Perl, Python & MATLAB.
- Compiler:
It translates the entire source code into machine code in one pass. Example: C, C#, C++ & Java.
- Assembler:
It translates the assembly language program into machine code.
- Linker:
A linker is a program that combines multiple object files into a single executable file. Object files are created by a compiler or assembler, and they contain the machine code for a program. The linker resolves all symbol references between the object files, and it also assigns memory addresses to the code and data sections of the program.
Here is a diagram of the linking process:
Source code files -> Compiler -> Object files Linker -> Executable file Object files: - .o file - .obj file Linker: - Resolves symbol references - Assigns memory addresses - Links external libraries Executable file: - .exe file - .out file
Comment
A comment in programming is a programmer-readable explanation or annotation in the source code of a computer program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters.
There are two main types of comments in programming: single-line comments and multi-line comments.
- Single-line comments are started with a
//
symbol and end at the end of the line. - Multi-line comments are started with a
/*
symbol and end with a*/
symbol.
Introduction Of C Language
Origin & Definition Of C:
- It is a basic general purpose , mid-level , structured programming language
- It is the base of all the high level language.
- It was developed by Dennis Ritchie at the AT & T’s Bell Laboratory(USA) in 1972 AD.
- Basically, it w as developed to implement UNIX operating system.
Features Of C Language:
Fast and Efficient: Programs written in C are efficient and fast. This is due to its variety of data type and powerful operators.
Portable: C is highly portable. This means that programs once written can be run on another machines with little or no modification.
Function and Rich Libraries: C program is basically a collection of functions that are supported by C library. We can also create our own functions and add it to the C library.
Modularity: Modular programming is a software design technique that increases the extent to which software is composed of separate parts, called modules.
Easy to Extend: In C, New feature can be added at any time by programmer.
Case Sensitive: It is a case sensitive language, that it can differentiate the character is upper case or lower case.
Application Of C language:
- Developing Games
- Operating system
- Compilers
- Editors
- Database Systems
- Network Drivers
- Graphics Packages
- Interpreters
Basic Syntax Of C
- The basic syntax of a C programming is presented below:
stdio
- It stands for standard input output.
- It is a collection of predefined functions/methods.
- It is also called library of c.
include
- To include the header file into the program.
#
- It is called preprocessor.
- It includes the library of c into the program before the execution of program.
conio
- It stands for console input output.
- It is used to show the output on console window.
.h
- It stands for header and is extension of C header’s Library.
void()
- It is a keyword.
- It indicates that no one value is being returned by the function.
- If we use any other keyword like int, float, char, etc in place of void then we will use return keyword.
main()
- It is the function which is called the entry point of any program.
- The execution of any program starts from the main function.
- If in a program there is only one function then it should be main function.
clrscr();
- It stands for clear screen.
- It is a predefined function which is used to clear the output screen.
- It acts like a duster on output screen.
- It is defined in the conio.h header file.
printf();
- It is a predefined function which is use used to print information or data on to the output screen.
- It is defined in the stdio.h header file.
getch();
- It is a predefined function which is used to hold the output screen.
- It acts like a duster on output screen.
- It is defined in the conio.h header file.
Structure & Compilation Process In C language
- The basic structure of a C programming is presented below:
Documentation section Link Section Definition Section Global Declaration Section |
Main() Function Section { Declaration Part Executable Part } |
User Defined Section Function 1 {} Function 2 {} — Function n {} |
Go through the given example for better understanding of Structure of C.
//Documentation section
/* This is a program to demonstrate the structure of a C program */
/* Link Section */
#include<stdio.h>
/* Definition Section */
#define MAX_LENGTH 100
/* Global Declaration Section */
int global_variable;
/* Main() Function Section */
int main() {
/* Declaration Part */
int local_variable;
/* Executable Part */
printf("This is the main function\n");
global_variable = 10;
local_variable = 20;
printf("Value of global variable: %d\n", global_variable);
printf("Value of local variable: %d\n", local_variable);
return 0;
}
/* User Defined Section */
/* Function 1 */
int function1() {
printf("This is function 1\n");
return 0;
}
/* Function 2 */
int function2() {
printf("This is function 2\n");
return 0;
}
/* Function n */
int functionn() {
printf("This is function n\n");
return 0;
}
- C is a case sensitive language (All the letters of defined function must be in small alphabets).
- C Program consist of one or more functions.
- One function that must be present in every C program is main(). This is the 1st function called up when program execution begins.
Compiling Process:
→ The process of translating source code into machine code by a compiler is called Compilation.
- After compiling the source code, it creates the Executable File with extension “.exe” and Object File with Extension “.o” in the program saved location.
hello.c
#include <stdio.h>
int main()
{
printf("Hello javaTpoint");
return 0;
}
In the above flow diagram, the following steps are taken to execute a program:
- Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor converts the source code into expanded source code. The extension of the expanded source code would be hello.i.
- The expanded source code is passed to the compiler, and the compiler converts this expanded source code into assembly code. The extension of the assembly code would be hello.s.
- This assembly code is then sent to the assembler, which converts the assembly code into object code.
- After the creation of an object code, the linker creates the executable file. The loader will then load the executable file for the execution.
Variable in C
Definition
- It is name of storage space ( container to store values ) which is used to store data.
- It’s value is changeable.
- It always contains last value.
- It is always declared with data type.
- Suppose we declare variable of type integer then it can store only integer values.
- Variable is considered as one of the building block of C Programming which is also called as identifier.
- A Variable is a name given to the memory location where the actual data is stored.
Rules To Declare Variable
- First letter of a variable should be alphabet or underscore(_).
- First letter should not be digit.
- After first character it can be the combination of alphabets and digits.
- Blank Spaces are not allowed in variable name
- Variable name should not be a keyword.
Types of variable in C :
Local Variables
- Local Variable is Variable having Local Scope.
- Local Variable is accessible only from function or block in which it is declared.
- Local variable is given Higher Priority than the Global Variable.
Global Variables
- Global Variable is Variable that is Globally available.
- Scope of Global variable is throughout the program [ i.e in all functions including main() ]
- Global variable is also visible inside function , provided that it should not be re-declared with same name inside function because “High Priority is given to Local Variable than Global”
- Global variable can be accessed from any function.
Let’s have look in this code to understand better.
#include<stdio.h>
int group;// We have declared "group" as the global variable
/* Main() Function Section */
int main() {
int height;// We have declared "height" as the local variable
return 0;
}
Variable Declaration
//Syntax
// Data_type variable_name ;
#include<stdio.h>
/* Main() Function Section */
int main() {
int serial_number; //here we have declared variable of int data type
float height;//here we have declared variable of float data type
char group;//here we have declared variable of char data type
getch();
}
Note: We have discussed about the data types in c language below
In the above code, serial_number is variabe of int data type, height is variable of float data type and group is the variable of character data type
Variable Initialization
//Syntax
// Data_type variable_name = value ;
#include<stdio.h>
/* Main() Function Section */
int main() {
int serial_number = 123456; //here we have declared variable of int data type
float height= 5.11; //here we have declared variable of float data type
char group = 'A'; //here we have declared variable of char data type
getch();
}
Here, 123456 is the value of serial_number, 5.11 is the value of height and A is the value of group. In the above code , we have initialized the value to each variable as like we do in the math a= 2, y=5 ,etc.
Constant & Its Type
Definition
→ An element of program whose value cannot be changed at the time of execution of program is called constant
- It may be integer, float and character data type.
- Constants are declared using the
const
keyword.
Syntax Of Declaring Constant const data_type variable_name = value; #define data_type varibale_name = value;
Here are some examples of constants in C:
const int MAX_VALUE = 100;
const char* MESSAGE = "Hello, world!";
Types Of Constant
There are two main types of constants in programming:
- Primary constants: These are constants that are defined directly in the source code. They are also called literal constants.
- Secondary constants: These are constants that are defined indirectly, such as through a function or a macro.
Primary constants can be further classified into the following types:
- Integer constants: These are constants that represent whole numbers. They can be decimal, octal, or hexadecimal.
- Real constants: These are constants that represent real numbers. They can be decimal or scientific notation.
- Character constants: These are constants that represent a single character. They are enclosed in single quotes.
- String constants: These are constants that represent a sequence of characters. They are enclosed in double quotes.
Secondary constants are created by functions or macros. They are often used to represent complex values or to make code more readable.
Here is a table of the different types of constants:
Type | Description | Example |
---|---|---|
Integer constant | Represents a whole number | 100 , 0123 , 0x1234 |
Real constant | Represents a real number | 10.5 , 1.23e-4 , 3.14 |
Character constant | Represents a single character | 'a' , '\n' , '$' |
String constant | Represents a sequence of characters | “Hello, world!”, “This is a string” |
Rules For Constructing Constant In C
- Integer constants:
- Must have at least one digit.
- Cannot have a decimal point.
- Can be either positive or negative.
- No commas or blanks are allowed.
- If no sign precedes an integer constant, it is assumed to be positive.
- The allowable range for integer constants is -32768 to 32767.
- Real constants:
- Must have at least one digit.
- Must have a decimal point.
- Can be either positive or negative.
- No commas or blanks are allowed.
- If no sign precedes an real constant, it is assumed to be positive.
- The allowable range for real constants is -3.402823466e+38 to 3.402823466e+38.
- Character constants:
- Must be enclosed in single quotes.
- Can be any character from the ASCII character set.
- Escape sequences can be used to represent special characters.
- String constants:
- Must be enclosed in double quotes.
- Can be any sequence of characters from the ASCII character set.
- Escape sequences can be used to represent special characters
Keywords
Keywords are reserved words in the C programming language that have special meaning to the compiler. They cannot be used as identifiers, which are names that are used to identify variables, functions, and other entities in a program.
There are 32 keywords in C.
Keywords cannot be used as identifiers because they would be confusing to the compiler. For example, if the keyword int
were used as an identifier, the compiler would not know whether it was referring to the keyword int
or the type int
.
Keywords are an important part of the C programming language. They allow the compiler to understand the structure of a program and to generate efficient machine code.
Here is a table of the keywords in C, along with their meanings:
Keyword | Meaning |
---|---|
auto | Used to declare a variable that is automatically allocated on the stack |
break | Used to terminate a loop or switch statement |
case | Used to specify a case in a switch statement |
char | Used to declare a variable of type char |
const | Used to declare a constant |
continue | Used to continue the execution of a loop |
default | Used to specify a default case in a switch statement |
do | Used to start a do-while loop |
double | Used to declare a variable of type double |
else | Used to specify the else clause of an if statement |
enum | Used to declare an enumeration |
extern | Used to declare an external variable |
float | Used to declare a variable of type float |
for | Used to start a for loop |
goto | Used to unconditionally jump to a label |
if | Used to start an if statement |
inline | Used to declare an inline function |
int | Used to declare a variable of type int |
long | Used to declare a variable of type long |
register | Used to declare a register variable |
return | Used to return from a function |
short | Used to declare a variable of type short |
signed | Used to declare a signed variable |
sizeof | Used to determine the size of an object |
static | Used to declare a static variable |
struct | Used to declare a structure |
switch | Used to start a switch statement |
typedef | Used to define a type alias |
union | Used to declare a union |
unsigned | Used to declare an unsigned variable |
void | Used to declare a function that does not return a value |
while | Used to start a while loop |
Data Types In C
Definition
In the C programming language, a data type refers to the type of data that a variable can hold. Each data type specifies the size and format of the data that can be stored in a variable.
C is a statically-typed language, which means that the data type of a variable must be explicitly declared before it is used.
Types Of Data Type In C
Types | Description |
---|---|
Primitive Data Types | Primitive data types are the most basic data types that are used for representing simple values such as integers, float, characters, etc. |
User Defined Data Types | The user-defined data types are defined by the user himself. |
Derived Types | The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. |
Different data types also have different ranges up to which they can store numbers.
These ranges may vary from compiler to compiler. Below is a list of ranges along with the memory requirement and format specifiers on the 32-bit GCC compiler.
Data Type | Size (bytes) | Range | Format Specifier |
---|---|---|---|
short int | 2 | -32,768 to 32,767 | %hd |
unsigned short int | 2 | 0 to 65,535 | %hu |
unsigned int | 4 | 0 to 4,294,967,295 | %u |
int | 4 | -2,147,483,648 to 2,147,483,647 | %d |
long int | 4 | -2,147,483,648 to 2,147,483,647 | %ld |
unsigned long int | 4 | 0 to 4,294,967,295 | %lu |
long long int | 8 | -(2^63) to (2^63)-1 | %lld |
unsigned long long int | 8 | 0 to 18,446,744,073,709,551,615 | %llu |
signed char | 1 | -128 to 127 | %c |
unsigned char | 1 | 0 to 255 | %c |
float | 4 | 1.2E-38 to 3.4E+38 | %f |
double | 8 | 1.7E-308 to 1.7E+308 | %lf |
long double | 16 | 3.4E-4932 to 1.1E+4932 | %Lf |
Note: The long, short, signed and unsigned are datatype modifier that can be used with some primitive data types to change the size or length of the datatype.
Primitive Data Type
Integer Data Type
The integer datatype in C is used to store the whole numbers without decimal values. Octal values, hexadecimal values, and decimal values can be stored in int data type in C.
- Range: -2,147,483,648 to 2,147,483,647
- Size: 4 bytes
- Format Specifier: %d
Syntax of Integer
We use int keyword to declare the integer variable:
int var_name;
The integer data type can also be used as:
- unsigned int: Unsigned int data type in C is used to store the data values from zero to positive numbers but it can’t store negative values like signed int.
- short int: It is lesser in size than the int by 2 bytes so can only store values from –32,768 to 32,767.
- long int: Larger version of the int datatype so can store values greater than int.
- unsigned short int: Similar in relationship with short int as unsigned int with int.
Note: The size of an integer data type is compiler-dependent. We can use sizeof operator to check the actual size of any data type.
Example of Int
// C program to print Integer data types.
#include <stdio.h>
int main()
{
// Integer value with positive data.
int a = 9;
// integer value with negative data.
int b = -9;
// U or u is Used for Unsigned int in C.
int c = 89U;
// L or l is used for long int in C.
long int d = 99998L;
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n",
c);
printf("Integer value with an long int data: %ld", d);
return 0;
}
Output
Integer value with positive data: 9 Integer value with negative data: -9 Integer value with an unsigned int data: 89 Integer value with an long int data: 99998
Character Data Type
Character data type allows its variable to store only a single character.
The size of the character is 1 byte. It is the most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.
- Range: (-128 to 127) or (0 to 255)
- Size: 1 byte
- Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;
Example of char
// C program to print Integer data types.
#include <stdio.h>
int main()
{
char a = 'a';
char c;
printf("Value of a: %c\n", a);
a++;
printf("Value of a after increment is: %c\n", a);
// c is assigned ASCII values
// which corresponds to the
// character 'c'
// a-->97 b-->98 c-->99
// here c will be printed
c = 99;
printf("Value of c: %c", c);
return 0;
}
Output
Value of a: a Value of a after increment is: b Value of c: c
Float Data Type
In C programming, float data type is used to store floating-point values. Float in C is used to store decimal and exponential values. It is used to store decimal numbers (numbers with floating point values) with single precision.
- Range: 1.2E-38 to 3.4E+38
- Size: 4 bytes
- Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;
Example Of Float
// C Program to demonstrate use
// of Floating types
#include <stdio.h>
int main()
{
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);
return 0;
}
Output
9.000000 2.500000 0.000200
Double Data Type
A Double data type in C is used to store decimal numbers (numbers with floating point values) with double precision. It is used to define numeric values which hold numbers with decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding 64 bits of decimal numbers or floating points. Since double has more precision as compared to that float then it is much more obvious that it occupies twice the memory occupied by the floating-point type. It can easily accommodate about 16 to 17 digits after or before a decimal point.
- Range: 1.7E-308 to 1.7E+308
- Size: 8 bytes
- Format Specifier: %lf
Syntax of Double
The variable can be declared as double precision floating point using the double keyword:
double var_name;
Example of Double
// C Program to demonstrate
// use of double data type
#include <stdio.h>
int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c);
return 0;
}
Void Data Type
The void data type in C is used to specify that no value is present. It does not provide a result value to its caller. It has no values and no operations. It is used to represent nothing. Void is used in multiple ways as function return type, function arguments as void, and pointers to void.
Syntax:
// function return type void void exit(int check); // Function without any parameter can accept void. int print(void); // memory allocation function which // returns a pointer to void. void *malloc (size_t size);
Example of Void
// C program to demonstrate
// use of void pointers
#include <stdio.h>
int main()
{
int val = 30;
void* ptr = &val;
printf("%d", *(int*)ptr);
return 0;
}
//WE ARE STILL WORKING ON IT
100+ Programs of C programming
Basic C programs15+ programs
C program to print “Hello world“
#include<stdio.h>
int main()
{
printf("Hello world");
return 0;
}
C program to Add two variables
#include <stdio.h>
int main() {
int num1, num2, sum;
// Read two numbers from user input
printf("Enter two numbers:\n");
scanf("%d%d", &num1, &num2);
// Perform the addition
sum = num1 + num2;
// Display the result
printf("Sum: %d\n", sum);
return 0;
}
C program to Subtract two variables
#include <stdio.h>
int main() {
int num1, num2, difference;
// Read two numbers from user input
printf("Enter two numbers:\n");
scanf("%d%d", &num1, &num2);
// Perform the subtraction
difference = num1 - num2;
// Display the result
printf("Difference: %d\n", difference);
return 0;
}
C program to Multiply two variables
#include <stdio.h>
int main() {
int num1, num2, product;
// Read two numbers from user input
printf("Enter two numbers:\n");
scanf("%d%d", &num1, &num2);
// Perform the multiplication
product = num1 * num2;
// Display the result
printf("Product: %d\n", product);
return 0;
}
C program on Division of two variables
#include <stdio.h>
int main() {
int num1, num2;
float div;
// Read two numbers from user input
printf("Enter two numbers:\n");
scanf("%d%d", &num1, &num2);
// Perform the division
div = (float) num1 / num2;
// Display the result
printf("Quotient: %.2f\n", div);
return 0;
}
C program on Modulus
#include <stdio.h>
int main() {
int num1, num2, remainder;
// Read two numbers from user input
printf("Enter two numbers:\n");
scanf("%d%d", &num1, &num2);
// Perform the modulus operation
remainder = num1 % num2;
// Display the result
printf("Remainder: %d\n", remainder);
return 0;
}
C program on Mixed Arithmetic operation
#include <stdio.h>
int main() {
int num1, num2;
// Read two numbers from user input
printf("Enter two numbers:\n");
scanf("%d%d", &num1, &num2);
// Perform arithmetic operations
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
float quotient = (float) num1 / num2;
int remainder = num1 % num2;
// Display the results
printf("Sum: %d\n", sum);
printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %.2f\n", quotient);
printf("Remainder: %d\n", remainder);
return 0;
}
C program to calculate Area of circle
#include <stdio.h>
int main() {
float radius, area;
// Read the radius of the circle from user input
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
// Calculate the area of the circle
area = 3.14159 * radius * radius;
// Display the result
printf("The area of the circle with radius %.2f is %.2f\n", radius, area);
return 0;
}
C program to calculate Area of Triangle
#include <stdio.h>
int main() {
float base, height, area;
// Read the base and height of the triangle from user input
printf("Enter the base of the triangle: ");
scanf("%f", &base);
printf("Enter the height of the triangle: ");
scanf("%f", &height);
// Calculate the area of the triangle
area = 0.5 * base * height;
// Display the result
printf("The area of the triangle with base %.2f and height %.2f is %.2f\n", base, height, area);
return 0;
}
C program to calculate Area of Rectangle
#include <stdio.h>
int main() {
float length, width, area;
// Read the length and width of the rectangle from user input
printf("Enter the length of the rectangle: ");
scanf("%f", &length);
printf("Enter the width of the rectangle: ");
scanf("%f", &width);
// Calculate the area of the rectangle
area = length * width;
// Display the result
printf("The area of the rectangle with length %.2f and width %.2f is %.2f\n", length, width, area);
return 0;
}
C program on Swapping two variables
#include <stdio.h>
int main() {
int x = 10;
int y = 20;
printf("Before swapping, x = %d and y = %d\n", x, y);
// Swap the values of x and y
int temp = x;
x = y;
y = temp;
printf("After swapping, x = %d and y = %d\n", x, y);
return 0;
}
C program to calculate simple interest
#include <stdio.h>
int main() {
float principal, rate, time, si;
printf("Enter the principal: ");
scanf("%f", &principal);
printf("Enter the rate of interest: ");
scanf("%f", &rate);
printf("Enter the time period (in years): ");
scanf("%f", &time);
si = (principal * rate * time) / 100;
printf("The simple interest is %f\n", si);
return 0;
}
C programs on if-else15+ programs
C Program to Check Even or Odd
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
return 0;
}
C Program to Find the Sum of Even and Odd Numbers
#include <stdio.h>
int main() {
int n, evenSum = 0, oddSum = 0, number;
printf("Enter the number of terms: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
printf("Enter the %dth number: ", i);
scanf("%d", &number);
if (number % 2 == 0) {
evenSum += number;
} else {
oddSum += number;
}
}
printf("The sum of even numbers is %d\n", evenSum);
printf("The sum of odd numbers is %d\n", oddSum);
return 0;
}
C program to Check Positive or Negative
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0) {
printf("The number is positive.\n");
} else if (number < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}
return 0;
}
C program to Find the Largest Number Among Three Numbers
#include <stdio.h>
int main() {
int num1, num2, num3, largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
if (num1 > num2 && num1 > num3) {
printf("Num1 is Largest");
} else if (num2 > num1 && num2> num3) {
printf("Num2 is Largest");
}
else {
printf("Num3 is Largest");
}
return 0;
}
C Program to Check Prime Number
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d is a prime number.\n", n);
} else {
printf("%d is not a prime number.\n", n);
}
return 0;
}
C Program to Check Armstrong Number
#include <stdio.h>
int main() {
int n, temp, digit, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
temp = n;
while (temp > 0) {
digit = temp % 10;
sum = sum + digit * digit * digit;
temp = temp / 10;
}
if (n == sum) {
printf("%d is an Armstrong number.\n", n);
} else {
printf("%d is not an Armstrong number.\n", n);
}
return 0;
}
C Program to Check palindrome Number
#include <stdio.h>
int main() {
int n, temp, rev = 0, digit;
printf("Enter a number: ");
scanf("%d", &n);
temp = n;
while (temp > 0) {
digit = temp % 10;
rev = rev * 10 + digit;
temp = temp / 10;
}
if (n == rev) {
printf("%d is a palindrome number.\n", n);
} else {
printf("%d is not a palindrome number.\n", n);
}
return 0;
}
C Program to Reverse a Number
#include <stdio.h>
int main(void)
{
int num, reverse = 0, temp, remainder;
printf("Enter the number:\n");
scanf("%d", &num);
temp = num;
while (num > 0)
{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
printf("Given number = %d\n", temp);
printf("Reverse of a Number is %d\n", reverse);
}
C Program to Convert Days into Years, Months and Days
#include <stdio.h>
int main() {
int days, years, months, days_left;
printf("Enter the number of days: ");
scanf("%d", &days);
years = days / 365;
days_left = days % 365;
months = days_left / 30;
days = days_left % 30;
printf("%d days is equivalent to %d years, %d months and %d days\n", days, years, months, days);
return 0;
}
C program to Check Eligibility for Voting-(if else)
#include <stdio.h>
int main() {
int age;
// Read age from user input
printf("Enter your age: ");
scanf("%d", &age);
// Check eligibility for voting
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}
C program to Check alphabet is upper or lower-(if..else if)
#include <stdio.h>
int main() {
char ch;
// Read a character from user input
printf("Enter a character: ");
scanf("%c", &ch);
// Determine if the character is lowercase or uppercase alphabet
if (ch >= 'a' && ch <= 'z') {
printf("The character is a lowercase alphabet.\n");
} else if (ch >= 'A' && ch <= 'Z') {
printf("The character is an uppercase alphabet.\n");
} else {
printf("The character is not an alphabet.\n");
}
return 0;
}
C program to Check grades-(if..else if)
#include <stdio.h>
int main() {
int marks;
// Read marks from user input
printf("Enter marks: ");
scanf("%d", &marks);
// Nested if statements to check grade based on marks
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 80) {
printf("Grade: B\n");
} else if (marks >= 70) {
printf("Grade: C\n");
} else if (marks >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}
return 0;
}
C programs on switch5+ programs
C program to Print day of week
#include <stdio.h>
int main() {
int day;
// Read a number from user input
printf("Enter a number (1-7) to represent a day of the week: ");
scanf("%d", &day);
// Use switch statement to determine the day of the week
switch (day) {
case 1:
printf("Sunday\n");
break;
case 2:
printf("Monday\n");
break;
case 3:
printf("Tuesday\n");
break;
case 4:
printf("Wednesday\n");
break;
case 5:
printf("Thursday\n");
break;
case 6:
printf("Friday\n");
break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid input. Please enter a number between 1 and 7.\n");
}
return 0;
}
C program to Check alphabet is consonent or vowel
#include <stdio.h>
int main() {
char ch;
// Read a character from user input
printf("Enter an alphabet: ");
scanf(" %c", &ch);
// Convert the character to lowercase for easier comparison
ch = tolower(ch);
// Check if the character is a vowel or a consonant using switch statement
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("The character is a vowel.\n");
break;
default:
if ((ch >= 'a' && ch <= 'z')) {
printf("The character is a consonant.\n");
} else {
printf("Invalid input. Please enter an alphabet.\n");
}
}
return 0;
}
C program for Calculator program
#include <stdio.h>
int main() {
char operator;
int num1, num2, result;
// Read operator and two numbers from user input
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
// Perform calculations based on the operator using switch statement
switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %d\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %d\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %d\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %d\n", result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operator.\n");
}
return 0;
}
C program for ATM program
#include <stdio.h>
int main() {
int choice;
int balance = 1000; // Initial account balance (in cents)
// Display ATM menu and read user's choice
printf("Welcome to the ATM!\n");
printf("1. Check Balance\n");
printf("2. Deposit\n");
printf("3. Withdraw\n");
printf("4. Exit\n");
printf("Enter your choice (1/2/3/4): ");
scanf("%d", &choice);
// Perform the selected operation based on the switch statement
switch (choice) {
case 1:
printf("Your current balance: $%d.%02d\n", balance / 100, balance % 100);
break;
case 2:
int depositAmount;
printf("Enter the deposit amount: $");
scanf("%d", &depositAmount);
balance += depositAmount;
printf("Deposit successful. Your new balance: $%d.%02d\n", balance / 100, balance % 100);
break;
case 3:
int withdrawAmount;
printf("Enter the withdrawal amount: $");
scanf("%d", &withdrawAmount);
if (withdrawAmount <= balance) {
balance -= withdrawAmount;
printf("Withdrawal successful. Your new balance: $%d.%02d\n", balance / 100, balance % 100);
} else {
printf("Insufficient funds.\n");
}
break;
case 4:
printf("Thank you for using the ATM. Have a nice day!\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
C program for Nested Switch program
#include <stdio.h>
int main() {
int category, item;
// Display menu and read user's choice
printf("Menu:\n");
printf("1. Food\n");
printf("2. Clothing\n");
printf("3. Electronics\n");
printf("Enter a category (1/2/3): ");
scanf("%d", &category);
switch (category) {
case 1:
printf("Food Menu:\n");
printf("1. Pizza\n");
printf("2. Burger\n");
printf("3. Pasta\n");
printf("Enter an item (1/2/3): ");
scanf("%d", &item);
switch (item) {
case 1:
printf("You selected Pizza.\n");
break;
case 2:
printf("You selected Burger.\n");
break;
case 3:
printf("You selected Pasta.\n");
break;
default:
printf("Invalid item.\n");
}
break;
case 2:
printf("Clothing Menu:\n");
printf("1. T-shirt\n");
printf("2. Jeans\n");
printf("3. Dress\n");
printf("Enter an item (1/2/3): ");
scanf("%d", &item);
switch (item) {
case 1:
printf("You selected T-shirt.\n");
break;
case 2:
printf("You selected Jeans.\n");
break;
case 3:
printf("You selected Dress.\n");
break;
default:
printf("Invalid item.\n");
}
break;
case 3:
printf("Electronics Menu:\n");
printf("1. Smartphone\n");
printf("2. Laptop\n");
printf("3. Headphones\n");
printf("Enter an item (1/2/3): ");
scanf("%d", &item);
switch (item) {
case 1:
printf("You selected Smartphone.\n");
break;
case 2:
printf("You selected Laptop.\n");
break;
case 3:
printf("You selected Headphones.\n");
break;
default:
printf("Invalid item.\n");
}
break;
default:
printf("Invalid category.\n");
}
return 0;
}
C program for Traffic light simulator
#include <stdio.h>
int main() {
int light;
// Display menu and read user's choice
printf("Traffic Light Simulator:\n");
printf("1. Red\n");
printf("2. Green\n");
printf("3. Yellow\n");
printf("Enter the current light (1/2/3): ");
scanf("%d", &light);
switch (light) {
case 1:
printf("Stop! Red light.\n");
break;
case 2:
printf("Go! Green light.\n");
break;
case 3:
printf("Prepare to stop! Yellow light.\n");
break;
default:
printf("Invalid light signal.\n");
}
return 0;
}
C programs on Loops15+ programs
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
Accordion Title
for loop, while loop, do-while loop
print “Hello world” 5 times-(for loop)
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("Hello, World!\n");
}
return 0;
}
print natural numbers from 1-10-(for loop)
#include <stdio.h>
int main() {
printf("Natural numbers from 1 to 10:\n");
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
even numbers between 1 and 10-(for loop)
#include <stdio.h>
int main() {
printf("Even numbers between 1 and 10:\n");
for (int i = 2; i <= 10; i += 2) {
printf("%d\n", i);
}
return 0;
}
multiples of five between 10-50-(for loop)
#include <stdio.h>
int main() {
printf("Multiples of 5 between 10 and 50:\n");
for (int i = 10; i <= 50; i += 5) {
printf("%d\n", i);
}
return 0;
}
Patterns
#include <stdio.h>
int main() {
int n=5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}