C Programming Notes Unit-1&2
C Programming Notes Unit-1&2
C allows programmers to write code that runs fast, while also offering features like structured
programming and a rich set of functions. Even though it’s considered a low-level language, C provides a
solid foundation for learning other programming languages like C++, Java, and Python.
Simple and Efficient: C offers straightforward syntax and commands, making it easy to learn
and use while maintaining high performance.
Structured Programming: C language allows the breaking down of a program into
functions, making the code easier to understand and manage.
Low-level Access: C gives direct access to memory through pointers, allowing fine control over
hardware resources.
Portability: C programs can be run on different machines with minimal or no modification.
Rich Library Support: C language has a vast collection of built-in functions and libraries
for various tasks.
Modularity: C enables code reusability by allowing functions and modules to be reused
in different programs.
Dynamic Memory Allocation: C programming language provides functions to allocate memory
dynamically, giving control over memory management.
Fast Execution: Programs written in C are compiled, making them faster compared to interpreted
languages.
1. High Performance
C is known for its speed. The language allows for direct memory manipulation, which makes it ideal for
systems where performance is critical, like operating systems and embedded systems.
2. System-Level Programming
C is widely used in developing operating systems, drivers, and other low-level software. It gives
programmers close control over the hardware, which is essential for system-level tasks.
Many modern languages like C++, Java, and Python are either directly based on or influenced by C. Learning
C provides a solid foundation for learning other programming languages.
4. Portability
C programs can be easily adapted to different machines and operating systems with minimal changes, making
it a versatile choice for cross-platform development.
C is still the go-to language in industries like embedded systems, game development, and operating system
development. It is also heavily used in compilers and network programming.
With its long history, C has a vast community and a wealth of learning resources, libraries, and frameworks,
making it easier for beginners to find support.
Headers: These include necessary libraries using #include, such as #include <stdio.h>, which
allows input/output functions.
Main Function: Every C program must have a main() function, which is the entry point of
the program.
Statements: Inside main(), we write the program logic, typically as a series of function calls
and operations.
Semicolons and Braces: Semicolons (;) are used to end statements, and braces ({ }) define code
blocks, ensuring the program’s structure.
#include <stdio.h>
int main() {
printf("Hello, World!\n"); }
Output:
Hello, World!
Explanation:
Basics of C Language
Now that you know what is C programming and its key features & uses, let’s move to learn the basics of C:
1. Data Types
Basic Data Types int (for integers), float (for floating-point numbers), double (for precision floating-point),
char (for characters)
2. Variables
Variables in C store data and need to be declared with a specific data type.
For example, int a; declares an integer variable a. Variables must be declared before they are used.
3. Operators
Category Description
4. Control Structures
5. Functions
C programs are modular and reusable through functions. A function is defined with a return type, a name,
and parameters (optional).
For example:
Pointers are variables that store the memory address of another variable. They are an essential feature of C,
allowing for:
7. Arrays
Arrays in C are used to store multiple values of the same data type. They are defined by specifying the data
type, followed by square brackets:
Structures are user-defined data types that group different types of data together.
Example
struct student {
int id;
char name[50];
float marks;
};
C provides functions like malloc(), calloc(), realloc(), and free() to allocate and deallocate memory
dynamically. This gives programmers control over the system’s memory.
C allows reading from and writing to files using functions like fopen(), fclose(), fread(), fwrite(), and more
from the <stdio.h> library. File operations are important for saving data permanently.
C programs use preprocessor directives like #include and #define for including files and macros, which are
processed before compilation
13. Comments
Comments in C are ignored by the compiler and are used to make the code more readable:
Keywords in C
We will first go through the definition of keywords in C.
The keywords are reserved words that have predefined meanings and functions within the C language.
These words cannot be used as variable names, function names, or identifiers because they are integral to
the language's syntax.
For example, int, if, return, and for are commonly used C keywords. Each keyword has a specific purpose,
and knowing how to use them correctly is essential for writing functional C programs.
List of Keywords in C
The total number of keywords in C language is 32. The table below presents all 32 keywords:
Keyword Meaning
continue Skips the current iteration of a loop and proceeds to the next one.
register Declares a variable that should be stored in a register for quick access.
signed Declares a signed variable that can hold both positive and negative values.
static Declares variables with static lifetime or functions with limited visibility.
union Declares a union, a data type that can store different data types in the same memory location.
Data Types in C
Data types in C program help define the kind of data a variable can store, like numbers or letters. Each
data type tells the compiler how much memory to allocate and how to interpret the data.
For instance, numbers without decimal points use a type like int, while numbers with decimal points use
float or double. Characters, which store single letters or symbols, use the char type.
Data types are essential for organizing information efficiently and ensuring your program works as
expected by managing memory properly.
1. Basic Data Types: These include fundamental types like int (for integers), char (for characters), float
(for floating-point numbers), and double (for double-precision floating-point numbers).
2. Derived Data Types: These are derived from basic data types and include arrays,
pointers, and functions.
3. User-Defined Data Types: These are created by the programmer and include structures (struct),
unions (union), and enumerations (enum).
double typedef
void
The table below shows the data types in C and their size along with range:
The sizeof operator is used to determine the size (in bytes) of any data type or variable.
Example:
Variables in C
Variables in C language are like containers used to store data that a program needs to process. Imagine
you’re working with numbers or words while solving a problem. In the same way, a C program uses
variables to store values such as numbers, characters, or more complex types of data.
Each variable has a name, a type, and a value. The type defines what kind of data the variable can hold,
like an integer or a decimal number. The variable's name helps us refer to it later in the code, and its value
is the actual data stored in it.
data_type variable_name;
data_type: Specifies the type of data the variable will hold, such as int for integers, float
for floating-point numbers, or char for characters.
variable_name: The name you assign to the variable, which must follow the rules for
valid identifiers in C (e.g., must start with a letter or underscore, no spaces, etc.).
Example:
Multiple variables of the same type can also be declared in one line:
int x, y, z;
Types of Variables in C
C language variables can be classified into several types based on their scope, lifetime, and storage class:
1. Local Variables
Local variables in C are declared inside a function or a block of code and can only be accessed within that
specific function or block. Their scope is limited to the function they are declared in, and their lifetime
exists only as long as the function is executing.
Example:
void display() {
int x = 10; // Local variable
printf("%d", x); // Can be accessed only within this function
}
Scope: Limited to the function/block they are declared in.
Lifetime: Exists only while the function or block is executing.
2. Global Variables
Global variables in C are declared outside of all functions, usually at the beginning of the program. They
can be accessed by any function within the same program, making their scope the entire program.
Global variables retain their values throughout the program’s execution.
Example:
void function1() {
printf("%d", globalVar); // Accessible here
}
void function2() {
printf("%d", globalVar); // Accessible here too
}
Scope: Entire program (available to all functions).
Lifetime: Exists for the entire duration of the program.
3. Static Variables
Static variables in C can be either local or global, but their key feature is that they retain their value
between function calls. If declared inside a function, a static variable is initialized only once and
maintains its value across multiple calls to that function.
Example:
void increment() {
static int count = 0; // Static variable
count++;
printf("%d", count);
}
int main() {
increment(); // Output: 1
increment(); // Output: 2 (retains value from previous call)
return 0;
}
Scope: If declared globally, they have global scope. If declared locally, they are limited to
the function but retain their value across function calls.
Lifetime: Exists for the entire duration of the program.
4. Automatic Variables
By default, all local variables in C are automatic variables. These variables are created when a function is
called and destroyed when the function exits. The keyword auto can be used to explicitly declare automatic
variables, though it is rarely used as this is the default behavior.
Example:
void display() {
auto int x = 5; // Automatic variable (default behavior for local variables)
printf("%d", x);
}
Scope: Limited to the function/block they are declared in.
Lifetime: Exists only during the function’s execution.
External variables in C language are declared outside of all functions (like global variables) but can be
accessed across multiple files in a project using the extern keyword. They are defined in one file and can
be used in others by declaring them with extern.
Start with a Letter or Variable names must begin with a letter (a-z, int age;, float _salary;
Underscore A-Z) or an underscore (_), but not a number.
No Spaces Allowed Variable names cannot contain spaces. int user_age; (correct), int
user age; (incorrect)
Only Letters, Digits, and After the first character, variable names can char name1;, int
Underscores have letters, digits, and underscores (_). employee_id;
Case-Sensitive C is case-sensitive, so age, Age, and AGE are int Age;, int age; (distinct)
different variables.
No Reserved Keywords Variable names cannot be any of the C int return; (incorrect)
language’s reserved keywords (e.g., int, float).
No Special Characters Special characters like @, #, %, etc., are not int num@; (incorrect)
allowed.
Avoid Starting with Variable names cannot start with a digit. int 1number; (incorrect), int
Numbers number1; (correct)
Operators in C
Operators in C are symbols that instruct the compiler to perform specific operations on variables and data.
They are used to manipulate data, perform calculations, make decisions, and control the flow of a program.
Operators work with operands, which are the values or variables involved in the operation.
C programming provides various categories of operators, such as arithmetic, relational, logical, bitwise,
and more. Each type of operator serves a different purpose, from performing basic arithmetic operations
to advanced bit-level manipulations.
For instance:
Arithmetic Operators in C
Arithmetic operators in C language are used to perform basic mathematical operations on variables and
values. These include addition, subtraction, multiplication, division, and modulus operations.
Arithmetic operators work on numeric data types like int and float. They help perform simple and complex
calculations efficiently.
Name of the Operator Arithmetic Operation Syntax
Example:
// C program to demonstrate arithmetic operators
#include <stdio.h>
int main() {
int x = 15, y = 6;
int result;
// Addition
result = x + y;
printf("x + y = %d\n", result);
// Subtraction
result = x - y;
printf("x - y = %d\n", result);
// Multiplication
result = x * y;
printf("x * y = %d\n", result);
// Division
result = x / y;
printf("x / y = %d\n", result);
// Modulus
result = x % y;
printf("x %% y = %d\n", result); // Use %% to print '%'
return 0;
}
Output:
x = 15 and y = 6
x + y = 21
x-y=9
x*y=
90 x / y =
2 x%y
=3
Relational Operators in C
Relational operators in C language are used to compare two values. They evaluate the relationship between
the operands and return true (1) or false (0) based on the result.
These operators are generally used in conditional statements in C, such as if, while, and for, to control the
flow of the program.
== Equal to x == y
!= Not equal to x != y
Example:
int main() {
int a = 12, b = 8;
// Printing a and b
printf("a = %d and b = %d\n", a, b);
// Equal to
if (a == b) {
printf("a is equal to b\n");
} else {
printf("a is not equal to b\n");
}
// Not equal to
if (a != b) {
printf("a is not equal to b\n");
}
// Greater than
if (a > b) {
printf("a is greater than b\n");
}
// Less than
if (a < b) {
printf("a is less than b\n");
}
// Greater than or equal to
if (a >= b) {
printf("a is greater than or equal to b\n");
}
return 0;
}
Output:
a = 12 and b = 8
a is not equal to b
a is not equal to b
a is greater than b
a is greater than or equal to b
Logical Operators in C
Logical operators in C language are used to combine or invert conditions, returning true (1) or false (0)
based on the evaluation of the expressions. They are essential for decision-making in conditional
statements, such as if, while, and for.
Example:
int main() {
int x = 5, y = 10;
// AND operator
if (x > 0 && y > 0) {
printf("Both x and y are positive\n");
}
// OR operator
if (x > 0 || y < 0) {
printf("At least one condition is true\n");
}
// NOT operator
if (!(x == y)) {
printf("x is not equal to y\n");
}
return 0;
}
Output:
Bitwise Operators in C
Bitwise operators in C language allow operations directly on bits of integer values. These operators are
used for manipulating individual bits within an integer, making them essential for low-level programming,
cryptography, and hardware interactions. The operations are performed at the binary level.
Example:
// Bitwise AND
result = a & b;
printf("a & b = %d\n", result); // 1
// Bitwise OR
result = a | b;
printf("a | b = %d\n", result); // 7
// Bitwise XOR
result = a ^ b;
printf("a ^ b = %d\n", result); // 6
// Bitwise NOT
result = ~a;
printf("~a = %d\n", result); // -6
// Left shift
result = a << 1;
printf("a << 1 = %d\n", result); // 10
// Right shift
result = a >> 1;
printf("a >> 1 = %d\n", result); // 2
return 0;
}
Output:
a&b=
1a|b=
7 a^b=
6
~a = -6
a << 1 = 10
a >> 1 = 2
Assignment Operators in C
Assignment operators in C programming are used to assign values to variables. The basic assignment
operator is = which assigns the right-hand value to the left-hand variable. C also provides compound
assignment operators like +=, -=, *=, and /= for shorthand operations, combining arithmetic and
assignment.
= Assignment a=b
int main() {
int a = 10, b = 5;
// Basic assignment
a = b;
printf("a = %d\n", a); // a becomes 5
a *= 2; // equivalent to a = a * 2
printf("a *= 2 -> %d\n", a);
a -= 4; // equivalent to a = a - 4
printf("a -= 4 -> %d\n", a);
a /= 3; // equivalent to a = a / 3
printf("a /= 3 -> %d\n", a);
return 0;
}
Output:
a=5
a += 3 -> 8
a *= 2 -> 16
a -= 4 -> 12
a /= 3 -> 4
In prefix, the operation is performed before the value is used, while in postfix, the original value is used
first, and then the operation is performed.
Example:
int main() {
int x = 5;
// Postfix increment
printf("x++ = %d\n", x++); // Prints 5, then x becomes 6
// Prefix increment
printf("++x = %d\n", ++x); // Increments to 7, then prints 7
// Postfix decrement
printf("x-- = %d\n", x--); // Prints 7, then x becomes 6
// Prefix decrement
printf("--x = %d\n", --x); // Decrements to 5, then prints 5
return 0;
}
Output:
x++ = 5
++x = 7
x-- = 7 --x = 5
Conditional (Ternary) Operator in C
The conditional or ternary operator in C is a shorthand way of writing an if-else statement. It uses the
symbols ? and : and returns one of two values depending on the evaluation of a condition.
If the condition is true, the first expression is executed, otherwise, the second expression is executed.
Syntax:
int main() {
int a = 10, b = 20;
int max;
return 0;
}
Output:
sizeof Operator in C
The sizeof operator in C is used to determine the size, in bytes, of a data type or a variable. It returns the
memory size required to store the variable or type and is essential for dynamic memory allocation and
understanding memory usage in programs.
The sizeof operator is evaluated at compile-time, except in the case of dynamically allocated memory.
Example:
int main() {
int a = 10;
double b = 12.5;
return 0;
}
Output:
Operator Precedence in C
Operator precedence in C programming defines the priority of operators when evaluating an expression. It
decides which operator gets applied first when there are multiple operators.
For example, multiplication (*) has higher precedence than addition (+), so it is evaluated first unless
parentheses are used to change the order. Precedence ensures that expressions are evaluated correctly.
Imagine a to-do list where tasks are ranked by importance. High-priority tasks (like an urgent meeting) are
done first, even if other tasks (like checking emails) are listed before them.
Example:
So x becomes 3 + 8 = 11.
Think of a group of kids taking turns on a swing. If the rule is left-to-right, the kid on the left swings first.
If the rule is right-to-left, the kid on the right goes first.
Associativity helps to avoid confusion when there are multiple operators in an expression.
Types of Associativity:
Example:
11 ` ` Bitwise OR
13 ` `
Things to Remember:
1. The Precedence column indicates priority; higher numbers mean lower precedence.
2. Associativity decides the direction of operation when operators have the same precedence.
3. Use parentheses to explicitly set the order of operations and ensure clarity in complex expressions.
int x = 5 + 3 * 2;
Explanation:
Execution:
Result:
x = 11.
Example 2: Parentheses to Change Precedence
int x = (5 + 3) * 2;
Explanation:
Execution:
Result:
x = 16.
Example 3: Relational and Logical Operators
int a = 10, b = 5, c = 2;
int result = a > b && b > c;
Explanation:
Relational operators (>) are evaluated first because they have higher precedence than logical AND (&&).
Execution:
Result:
result = 1.
Example 4: Division and Modulus
int x = 20 / 4 % 3;
Explanation:
Division (/) and modulus (%) have the same precedence, so they are evaluated left to right.
Execution:
20 / 4 = 5.
5 % 3 = 2.
Result:
x = 2.
Example 5: Assignment with Arithmetic
int x = 5;
x = 10 + x * 2;
Explanation:
Multiplication (*) happens first because it has higher precedence than addition (+).
Execution:
x * 2 → 5 * 2 = 10.
10 + 10 = 20.
x = 20.
Result:
x = 20.
int x = 10 - 5 - 2;
Explanation:
Execution:
First, 10 - 5 = 5.
Then, 5 - 2 = 3.
Result:
x = 3.
Example 2: Right-to-Left Associativity (Assignment Operators)
int x, y, z;
x = y = z = 5;
Explanation:
Execution:
First, z = 5.
Result:
x = 5, y = 5, z = 5.
Example 3: Conditional Operator (?:)
int x = 10, y = 5;
int result = (x > y) ? (x - y) : (y - x);
Explanation:
Execution:
Result:
result = 5.
Example 4: Logical AND (&&) and OR (||)
int a = 1, b = 0, c = 1;
int result = a && b || c;
Explanation:
Execution:
First, evaluate a && b → 1 && 0 → 0.
Then, evaluate 0 || c → 0 || 1 → 1.
Result:
result = 1.
Example 5: Mixed Operators with Associativity
int x = 5 + 10 / 2 * 3;
Explanation:
Execution:
First, 10 / 2 = 5.
Then, 5 * 3 = 15.
Finally, 5 + 15 = 20.
Result:
x = 20.
If two or more operators have the same precedence, use their associativity (left-to-right or right-to-left) to
decide the order.
Perform the operations step by step, following operator precedence and associativity rules.
4. Use Parentheses to Override
Parentheses have the highest precedence and can be used to change the natural order of execution.
Constants in C
Constants in C programming are fixed values that do not change during the execution of a program. Unlike
variables, which can store different values throughout the program’s runtime, constants are used to
represent data that remains the same.
For example, if you need to use the value of pi (3.14159) or the number of days in a week (7), you can
define them as constants so they cannot be accidentally changed.
Constants help make your code more reliable and easier to understand by ensuring that important values
stay unchanged, making the program predictable and reducing errors.
Definition Constants are fixed values that cannot be Variables are data holders whose values can be
changed once defined. modified during program execution.
Value Cannot be changed after initialization. Can be changed throughout the program.
Modification
Declaration Declared using const keyword or #define Declared by specifying data type and variable
Syntax directive. name.
Memory Value is stored at a fixed memory Memory is allocated for storing data that can be
Allocation location that is protected. changed.
Use Cases Used for fixed values like pi, number of Used when data changes during program
days, etc. execution, like user input or calculation results.
Scope Scope can be local or global. Scope can be local or global, depending on where
it's declared.
1. Integer Constants
Integer constants in C represent whole numbers without any fractional or decimal components. These
constants can be positive or negative, and are written without any quotes.
Example:
2. Floating-Point Constants
Floating-point constants in C represent real numbers with a decimal point or in exponential notation. These
constants are used to represent fractional values.
Example:
3. Character Constants
A character constant in C represents a single character enclosed within single quotes (' '), such as a
letter, number, or special symbol. These constants are stored as integers in C, following the ASCII value
of the character.
Examples:
4. String Constants
String constants in C represent a sequence of characters enclosed within double quotes (" "). Strings are
treated as arrays of characters and always end with a null character (\0) to mark the end of the string.
Examples:
5. Enumeration Constants
Enumeration constants in C are user-defined constants that represent a set of integer values. They are
defined using the enum keyword. Each enumeration constant is assigned an integer value, starting from 0
by default, unless explicitly specified.
Examples:
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; // Enumeration constant for
days of the week
enum week today = Wednesday; // Assigns Wednesday (which equals 3) to the variable today
You can also specify custom values for enum members:
Example:
Arrays in C are collections of elements of the same type stored in contiguous memory locations. An array
constant can be thought of as a fixed set of values used to initialize an array at the time of declaration.
Example:
struct Point {
int x;
int y;
};
struct Point p = {10, 20}; // Structure constant
The #define directive is used to define constant values or macros at the start of a program. It instructs the
compiler to replace all occurrences of the defined constant with its value before the actual compilation
begins.
Syntax:
Example:
#define PI 3.14159
#define MAX_SIZE 100
#define MESSAGE "Hello, World!"
int main() {
printf("Value of PI: %f\n", PI); // Outputs: Value of PI: 3.14159
printf("Max size is: %d\n", MAX_SIZE); // Outputs: Max size is: 100
printf(MESSAGE); // Outputs: Hello, World!
return 0;
}
2. Using const Keyword
The const keyword in C allows you to declare a variable whose value cannot be changed after
initialization. It provides type safety, meaning the compiler knows the type of the constant and ensures no
modification is made during the program's execution.
Syntax:
int main() {
printf("Value of PI: %f\n", PI); // Outputs: Value of PI: 3.14159
printf("Max size is: %d\n", MAX_SIZE); // Outputs: Max size is: 100
return 0;
}
Input in C
Input in C programming means gathering data from the user or external sources for processing. The most
common way is through the console, where functions like scanf() are used for formatted input, and
getchar() reads a single character.
Additionally, data can be read from files using functions like fscanf() and fgets().
For example, scanf("%d", &num); takes an integer input from the user.
Output in C
Output in C programming means displaying results or information from a program on the console or
writing it to a file. Console output functions like printf() allow formatted data to be printed, while putchar()
is used for single characters. File output operations in C involve writing data to a file using functions like
fprintf() and fputs().
scanf() Input (Console) Reads formatted input (e.g., integers, floats, strings) from the
user.
gets() Input (Console) Reads a string from the user (deprecated due to safety
issues).
feof() File Operation Checks if the end of a file has been reached.
Input Functions in C
Below is a detailed explanation of common input functions in C programming:
1. scanf()
Reads formatted input from the user, such as integers, floats, and strings.
Example:
int num;
printf("Enter a number: ");
scanf("%d", &num); // Takes integer input
printf("You entered: %d\n", num);
2. getchar()
Example:
char ch;
printf("Enter a character: ");
ch = getchar(); // Reads one character
printf("You entered: %c\n", ch);
3. gets()
Reads a string from the user, including spaces (deprecated due to safety concerns).
Example:
char str[50];
printf("Enter a string: ");
gets(str); // Reads the entire string
printf("You entered: %s\n", str);
4. fscanf()
Example:
Output Functions in C
Below is the explanation of common output functions in C programming:
1. printf()
Example:
2. putchar()
Outputs a single character to the console.
Example:
char ch = 'A';
putchar(ch); // Outputs the character 'A'
printf("\n");
3. puts()
Example:
4. fprintf()
Example:
5. fputs()
Example:
Input functions like scanf() and fgets() are used to take data from the user or files.
Output functions like printf() and fprintf() are used to display or save data.
Always use fopen() and fclose() when working with files to ensure proper file handling.
Clear Presentation: It allows developers to align text, control decimal places, and format outputs
for better readability.
Accurate Input Handling: It ensures the program accepts data in the correct format
(e.g., integers, floats, or strings).
Custom Layouts: Developers can customize outputs, such as aligning columns of numbers or
formatting dates.
Example
#include <stdio.h>
int main() {
int age;
float height;
char name[50];
// Formatted input
printf("Enter your name: ");
scanf("%s", name); // Reads a single word
printf("Enter your age: ");
scanf("%d", &age); // Reads an integer
printf("Enter your height (in meters): ");
scanf("%f", &height); // Reads a float
// Formatted output
printf("\n--- User Details ---\n");
printf("Name: %s\n", name);
printf("Age: %d years\n", age);
printf("Height: %.2f meters\n", height); // Displays height with 2 decimal places
return 0;
}
Run Code
Output:
Input: The program uses scanf() to read the user’s name, age, and height in specific formats (%s,
%d, %f).
Output: The program uses printf() to display the details in a structured format. For
example, "Height: %.2f meters" ensures the height is shown with exactly two decimal
places.
printf() Formatted output Standard output Displays data on the console in a structured
(console) format.
scanf() Formatted input Standard input Reads data from the user in a specific
(keyboard) format.
fscanf() Formatted input from File or stream Reads formatted data from a file.
file
Key Points
Usage: Allows displaying text, variables, and other data types with custom formatting.
Syntax:
#include <stdio.h>
int main() {
int age = 25;
printf("Age: %d\n", age); // Displays the age with an integer format specifier
return 0;
}
Run Code
Output:
Age: 25
Purpose: Used for formatted input from the standard input (keyboard).
Usage: Reads data of specific types (integers, floats, strings, etc.) into variables.
Syntax:
#include <stdio.h>
int main()
{ int age;
printf("Enter your age: ");
scanf("%d", &age); // Reads an integer from the user
printf("You entered: %d\n", age);
return 0;
}
Run Code
Output:
Usage: Writes data to files with formatting, similar to printf() but for file streams.
Syntax:
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "w"); // Opens a file in write mode
if (file != NULL) {
int age = 25;
fprintf(file, "Age: %d\n", age); // Writes formatted data to the file
fclose(file);
} else {
printf("Error opening file.\n");
}
return 0;
}
Run Code
Output:
Age: 25
2. Usage: Reads data from a file into variables, similar to scanf() but for file streams.
Syntax:
#include <stdio.h>
int main() {
FILE *file = fopen("[Link]", "r"); // Opens a file in read mode
if (file != NULL) {
int age;
fscanf(file, "%d", &age); // Reads an integer from the file
printf("Age from file: %d\n", age);
fclose(file);
} else {
printf("Error opening file.\n");
}
return 0;
}
Run Code
Output:
Format Specifiers in C
Format specifiers in C are placeholders used in formatted input/output functions like printf() and scanf() to
indicate the type of data being handled. They help the compiler understand how to read input or display
output.
Think of control statements like traffic signals. A green light allows cars to move (execution), a red light
stops them (condition not met), and a yellow light prepares them for the next action (transition).
1. Decision-Making Statements: These statements allow the program to make decisions and execute
specific blocks of code based on conditions.
2. Loop Control Statements: These statements repeatedly execute a block of code as long as a specified
condition is true.
3. Jump Statements: These statements transfer the program's control from one part of the code to
another, either conditionally or unconditionally.
1. if Statement
The if statement in C executes a block of code only if the given condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
#include <stdio.h>
int main() {
int number = 10;
if (number > 0) {
printf("The number is positive.");
}
return 0;
}
When to Use: Use the if statement when you need to perform an action based on a single condition.
2. if-else Statement
The if-else statement in C executes one block of code if the condition is true and another block if it is false.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
#include <stdio.h>
int main() {
int number = -5;
if (number >= 0) {
printf("The number is non-negative.");
} else {
printf("The number is negative.");
}
return 0;
}
When to Use: Use if-else control statement in C programming when you need to perform one action for a
true condition and another for a false condition.
3. nested if Statement
Syntax:
if (condition1) {
if (condition2) {
// Code if both conditions are true
}
}
Example:
#include <stdio.h>
int main() {
int number = 5;
if (number > 0) {
if (number % 2 == 0) {
printf("The number is positive and even.");
} else {
printf("The number is positive and odd.");
}
}
return 0;
}
When to Use: Use nested if when you need to test multiple related conditions.
4. if-else-if Ladder
This conditional statement in C checks multiple conditions one by one until a true condition is found.
Syntax:
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Example:
#include <stdio.h>
int main() {
int marks = 85;
if (marks >= 90) {
printf("Grade: A");
} else if (marks >= 75) {
printf("Grade: B");
} else if (marks >= 50) {
printf("Grade: C");
} else {
printf("Grade: F");
}
return 0;
}
When to Use: Use the if-else-if ladder when you need to check multiple conditions in sequence.
The switch case in C tests a variable against multiple values (cases) and executes the matching block of
code.
Syntax:
switch (variable) {
case value1:
// Code for case 1
break;
case value2:
// Code for case 2
break;
default:
// Code if no case matches
}
Example:
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}
return 0;
}
When to Use: Use switch when you need to test a variable against a fixed set of values.
Imagine you are filling bottles with water. You continue filling bottles one by one until you run out of
empty bottles. Similarly, in programming, looping statements repeatedly perform tasks until a condition is
met.
1. for Loop
The for loop in C executes a block of code a specific number of times, controlled by an initialization,
condition, and increment/decrement.
Syntax:
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Number: %d\n", i);
}
return 0;
}
Output:
1
2
3
4
5
When to Use: Use the for loop when the number of iterations is known beforehand.
2. while Loop
The while loop in C executes a block of code repeatedly as long as the specified condition is true.
Syntax:
while (condition) {
// Code to execute while condition is true
}
Example:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("Number: %d\n", i);
i++;
}
return 0;
}
Output:
1
2
3
4
5
When to Use: Use the while loop when the number of iterations is not known and depends on a condition.
3. do-while Loop
The do-while loop in C executes a block of code at least once and then continues to execute as long as the
condition is true.
Syntax:
do {
// Code to execute
} while (condition);
Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("Number: %d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output:
1
2
3
4
5
When to Use: Use the do-while loop when you want the code to execute at least once, regardless of the
condition.
do-while After the first iteration Code must run at least once.
Condition At the beginning of each At the beginning of each After executing the loop
Evaluation iteration. iteration. body.
Execution Executes only if the condition is Executes only if the Executes the loop body at
Guarantee true. condition is true. least once.
Use Case When the number of iterations is When the number of When the loop body must run
known. iterations depends on a at least once.
condition.
Syntax Compact with initialization, Requires a separate Similar to while, but checks
condition, and increment in a initialization and increment condition last.
single line. statement.
Flexibility Best for counter-based loops. Best for condition-based Best for condition-based
loops. loops requiring at least one
execution.
Examples Iterating over arrays, printing Validating user input, Menu-driven programs, input
patterns. waiting for events. validation.
Jumping Control Statements in C
Jumping statements in C are used to transfer control of the program from one point to another. These
statements enable conditional or unconditional jumps, allowing flexibility in program flow.
Real-Life Example:
Jumping statements in C programming work similarly by moving control within the code.
1. break Statement
The break statement in C terminates the nearest enclosing loop or switch statement and transfers control to
the next statement after it.
Syntax:
break;
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
printf("Number: %d\n", i);
}
return 0;
}
When to Use: Use break to exit a loop or switch prematurely when a specific condition is met.
2. continue Statement
The continue statement in C skips the current iteration of the loop and moves to the next iteration.
Syntax:
continue;
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("Number: %d\n", i);
}
return 0;
}
When to Use: Use continue when you want to skip specific iterations of a loop without exiting it.
3. goto Statement
The goto statement in C transfers control to a labeled statement within the program.
Syntax:
goto label;
...
label:
// Code to execute
Example:
#include <stdio.h>
int main() {
int number = 3;
if (number < 5) {
goto small;
}
printf("Number is not small.\n");
return 0;
small:
printf("Number is small.\n");
}
When to Use: Use goto sparingly, typically in cases like error handling, where other approaches may
complicate the code.
4. return Statement
The return statement in C exits the current function and optionally returns a value to the calling function.
Syntax:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 5);
printf("Result: %d\n", result);
return 0;
}
When to Use: Use return to exit a function and optionally pass a value back to the calling function.
goto Jump to a labeled statement Rarely, for complex flow control or errors.
Scenario: A person needs to be at least 18 years old to apply for a driving license.
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0;
}
Output:
Enter a number: 12
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
#include <stdio.h>
int main() {
int start, end;
printf("Enter the start and end of the range: ");
scanf("%d %d", &start, &end);
for (int i = start; i <= end; i++) {
if (i % 2 != 0) {
printf("%d ", i);
}
}
return 0;
}
Output:
#include <stdio.h>
int main() {
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
*
**
***
****
*****
******
*******
#include <stdio.h>
int main() {
char operator;
double num1, num2;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch (operator) {
case '+':
printf("Result: %.2lf\n", num1 + num2);
break;
case '-':
printf("Result: %.2lf\n", num1 - num2);
break;
case '*':
printf("Result: %.2lf\n", num1 * num2);
break;
case '/':
if (num2 != 0) {
printf("Result: %.2lf\n", num1 / num2);
} else {
printf("Error: Division by zero.\n");
}
break;
default:
printf("Invalid operator.\n");
}
return 0;
}
Output:
1 2 3 4 6 7 8 9 10
Scenario: Check if a user enters the correct username and password within three attempts.
#include <stdio.h>
#include <string.h>
int main() {
char username[20], password[20];
char correctUser[] = "admin";
char correctPass[] = "1234";
Handle Default Cases: Always include a default case in switch statements to handle unexpected
inputs.
Unit-2
Arrays and Strings
An array in C is a collection of multiple values of the same data type stored together under a single variable
name. Instead of creating separate variables for each value, you can use an array to store and manage them
efficiently using index numbers.
These index numbers start from 0, allowing easy access to each element. Arrays are especially useful when you
need to work with lists, such as marks of students, temperatures, or items in a menu.
Syntax of Array in C
The basic syntax for declaring an array in C is:
data_type array_name[array_size];
data_type: Type of data (e.g., int, float, char)
array_name: Any valid identifier
array_size: Number of elements (must be a constant or macro)
Example:
1. One-Dimensional Array
A one-dimensional array in C is the simplest form of an array. It stores a list of elements of the same data type
in a single row (linear structure), accessed using a single index.
Declaration:
int numbers[5];
Initialization:
#include <stdio.h>
int main() {
int marks[3] = {85, 90, 95};
for (int i = 0; i < 3; i++) {
printf("marks[%d] = %d\n", i, marks[i]);
}
return 0;
}
2. Two-Dimensional Array
A two-dimensional array in C stores data in a table-like structure using rows and columns. It’s often used
to represent matrices.
Declaration:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Accessing Elements:
#include <stdio.h>
int main() {
int matrix[2][2] = {{10, 20}, {30, 40}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);
}
}
return 0;
}
3. Multi-Dimensional Array
A multi-dimensional array in C contains more than two dimensions (like 3D or 4D arrays). These are
rarely used but helpful in special cases like 3D games or image processing.
Declaration:
int cube[2][2][2];
Initialization:
int cube[2][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
Accessing Elements:
1. Compile-Time Initialization
Example:
The compiler automatically determines the size based on the number of elements.
Example:
3. Partial Initialization
Only the first few elements are initialized, rest are automatically set to 0.
Example:
4. Zero Initialization
Example:
You can assign values to each element using a loop, especially when taking input from the user.
Example:
int n[3];
for (int i = 0; i < 3; i++) {
scanf("%d", &n[i]);
}
Examples of Arrays in C Language
1. Program to Print Elements of an Array
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
Explanation:
#include <stdio.h>
int main() {
int arr[5], sum = 0;
printf("Enter 5 numbers:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Sum = %d", sum);
return 0;
}
Explanation:
Takes user input into an array and calculates the total sum.
#include <stdio.h>
int main() {
int arr[5] = {11, 25, 9, 43, 31};
int max = arr[0];
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("Reversed array: ");
for (int i = 4; i >= 0; i--) {
printf("%d ", arr[i]);
}
return 0;
}
Explanation:
#include <stdio.h>
int main() {
int original[5] = {3, 6, 9, 12, 15};
int copy[5];
return 0;
}
Explanation:
Method 1: Using Character List: Must include \0 at the end to make it a valid string. Size must be 1
more than the number of characters to accommodate the null terminator.
#include <stdio.h>
int main() {
char city[] = "Delhi";
printf("City: %s", city); // Output: City: Delhi
return 0;
}
Reading Strings from User
char name[20];
scanf("%s", name);
Using fgets() (Reads full line including spaces)
Advantages of Arrays in C
Efficient Data Storage: Arrays allow storing multiple values of the same data type using a
single variable name.
Indexed Access: Elements can be easily accessed, modified, or iterated using index numbers (0-
based indexing).
Reduced Code Complexity: You don’t need to declare multiple variables — one array can hold
hundreds of values.
Easy Looping and Traversal: Arrays can be easily processed using loops (for, while),
making operations like printing, summing, or searching simpler.
Improved Memory Management: Arrays use contiguous memory, which helps in faster
data access and better memory locality.
Useful in Algorithms: Arrays are widely used in sorting, searching, matrix operations, and many
algorithms.
Foundation for Advanced Structures: Arrays form the basis of more advanced data
structures like strings, matrices, stacks, queues, and linked lists.
Cleaner and Organized Code: Helps organize related data under a single name,
improving readability and maintainability.
Disadvantages of Arrays in C
Fixed Size: Once declared, the size of an array cannot be changed during program execution.
Static Memory Allocation: Memory is allocated at compile time, which may lead to
inefficient memory usage if the size is too large or too small.
No Bound Checking: C does not check whether an index is within array limits, which can
cause unexpected behavior or segmentation faults.
Only Homogeneous Data Types: Arrays can store elements of the same data type only (e.g., all
int or all char).
No Built-in Dynamic Resizing: You cannot grow or shrink an array at runtime without
using dynamic memory (malloc, realloc, etc.).
No Built-in Insertion or Deletion: Inserting or deleting elements requires manual shifting
of elements, unlike in higher-level data structures like lists.
Wastage of Memory: If the allocated size is larger than needed, the unused memory is wasted.
2D Array in C Language
A two dimensional array in C is like a collection of data stored in rows and columns, similar to a table or grid.
It allows you to organize related information in a structured format, making it easier to access specific
elements using their row and column numbers.
For example, storing numbers in a 2D array means each number can be identified clearly by its position, such
as "third row, second column."
Imagine a cinema hall with rows and seats. To find your seat easily, you simply check your ticket, which
indicates your exact row number and seat number—just like locating elements in a 2D array.
data_type array_name[rows][columns];
data_type: Specifies the type of elements the array will store (like int, float, or char).
array_name: The name given to the array.
[rows] and [columns]: Define the size of the array, specifying how many rows and columns
it contains.
Example:
int matrix[3][4];
This example declares a two-dimensional array named matrix of type int with 3 rows and 4 columns. In total,
this array can hold 3 x 4 = 12 integer values.
1. Initialization at Declaration:
You can initialize a 2D array at the time you declare it using braces {}.
Syntax:
data_type array_name[rows][columns] = {
{val1, val2, val3},
{val4, val5, val6}
};
Example:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
2. Initialization Using Loops:
Example:
int matrix[2][3];
int value = 1;
array_name[row_index][column_index];
row_index: Specifies the row position of the element.
column_index: Specifies the column position of the element.
Example:
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
To access specific elements:
matrix[0][1] accesses the element in the first row, second column (20).
matrix[1][2] accesses the element in the second row, third column (60).
Practical Example:
#include <stdio.h>
int main() {
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
return 0;
}
Output:
Element at [0][1]: 20
Element at [1][2]: 60
Input and Output with 2D Arrays in C
Below is how you can handle input and output with two dimensional arrays in C:
To accept input into a 2D array from the user, use nested loops:
Example:
#include <stdio.h>
int main() {
int rows = 2, columns = 3;
int matrix[2][3];
return 0;
}
Displaying Output of a 2D Array
123
456
The following is a complete example showing passing and printing a 2D array using a function:
#include <stdio.h>
int main() {
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
Matrix elements:
10 20 30
40 50 60
Examples of 2D Arrays in C
1: Addition of Two Matrices
#include <stdio.h>
int main() {
int rows = 2, columns = 2;
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2];
// Adding matrices
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
Sum of matrices:
68
10 12
2. Transpose of a Matrix
#include <stdio.h>
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
int transpose[3][2];
// Calculating transpose
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
transpose[j][i] = matrix[i][j];
}
}
return 0;
}
Output:
Transpose of matrix:
14
25
36
#include <stdio.h>
int main() {
int matrix[3][3] = {
{12, 25, 6},
{8, 15, 20},
{3, 50, 10}
};
int max = matrix[0][0];
Output:
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int product[2][2] = {0};
// Multiplying matrices
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
product[i][j] += a[i][k] * b[k][j];
}
}
}
return 0;
}
Output:
Product of matrices:
19 22
43 50
5. Sum of Rows and Columns of a Matrix
#include <stdio.h>
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
int rowSum, colSum;
// Sum of rows
for(int i = 0; i < 2; i++) {
rowSum = 0;
for(int j = 0; j < 3; j++) {
rowSum += matrix[i][j];
}
printf("Sum of elements in row %d: %d\n", i + 1, rowSum);
}
// Sum of columns
for(int j = 0; j < 3; j++) {
colSum = 0;
for(int i = 0; i < 2; i++) {
colSum += matrix[i][j];
}
printf("Sum of elements in column %d: %d\n", j + 1, colSum);
}
return 0;
}
Output:
Advantages of 2D Arrays in C
Easy Data Representation: Ideal for representing matrices, tables, and grids clearly.
Efficient Access: Quick element access using row and column indices.
Contiguous Memory Allocation: Elements are stored contiguously in memory, enabling faster
processing.
Easy Manipulation: Simplifies operations such as matrix addition, multiplication,
and transposition.
Code Readability: Improves readability and clarity, especially in handling structured data.
Limitations of 2D Arrays in C
Fixed Size: Array dimensions must be specified during declaration and cannot be
resized afterward.
Memory Wastage: Possible memory wastage if the array is not fully utilized.
No Built-in Boundary Check: Accessing elements outside array bounds leads to undefined
behavior.
Complex Dynamic Allocation: Dynamic allocation and memory management for 2D arrays
can become complex, especially for beginners.
Rigid Structure: Limited flexibility; unsuitable for datasets that frequently change size or
structure.
String in C
String in C programming language is a sequence of characters stored in a character array, ending with a special
null character \0 that marks the end of the string. It can include letters, numbers, symbols, or spaces—just
like a sentence.
Since C doesn’t have a built-in string type like some other languages, strings are managed using arrays and
standard library functions.
Think of a string in C like a train, where each character is a coach, and the last coach is always empty (null
character \0) to signal that the train has ended.
char str[size];
Example of string declaration in C:
char name[10];
Explanation:
Here, name is a character array that can hold up to 9 characters plus one null character \0. This is just a
declaration—no specific string is stored yet. It's like reserving space without filling it.
In both examples, a string "Hello" is stored in the array. The null character \0 is automatically added when
you use double quotes. This tells the compiler where the string ends. This process is called initializing
strings in C and is essential for proper string handling.
So, this defines a string "Delhi" and stores it in a character array named city.
Reading Strings in C
Reading strings in C language from the user means taking input that contains multiple characters, including
spaces (if needed). There are multiple ways to read strings in C, each with its pros and cons.
char name[50];
scanf("%s", name);
Note: This reads only a single word. It stops reading when it encounters a space.
Example:
John Doe
Only John will be stored in the string.
char name[50];
gets(name);
Note: This can read an entire line, including spaces. But it is unsafe and deprecated because it doesn’t
prevent buffer overflow.
char name[50];
fgets(name, sizeof(name), stdin);
What it does:
Displaying Strings in C
After reading or defining a C language string, you’ll want to display the string to the user. In C, you can
print strings using a couple of standard functions:
Using printf()
Output:
Alice
Using puts()
Output:
Alice
#include <string.h>
int len = strlen("Hello");
printf("%d", len); // Output: 5
#include <string.h>
char src[] = "World";
char dest[20];
strcpy(dest, src);
printf("%s", dest); // Output: World
#include <string.h>
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2);
printf("%s", str1); // Output: Hello World
#include <string.h>
int result = strcmp("abc", "abc"); // Output: 0 (equal)
int result2 = strcmp("abc", "xyz"); // Output: negative (less than)
#include <string.h>
char str[] = "Hello";
strrev(str);
printf("%s", str); // Output: olleH
Note: In GCC or modern compilers, you’ll need to write your own strrev() function.
#include <string.h>
char *ptr = strchr("Hello", 'l');
printf("%s", ptr); // Output: llo
#include <string.h>
char *ptr = strstr("Hello World", "World");
printf("%s", ptr); // Output: World
These string functions in C help perform basic and advanced string operations with ease. Always include
#include <string.h> at the top of your program when using these functions.
Purpose Used to store multiple characters (not always Specifically used to represent textual data
a string)
String Functions Not fully compatible unless null-terminated Fully compatible with standard string
Compatibility functions
Examples of Strings in C
Program to Find the Length of a String
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Length = %lu", strlen(str));
return 0;
}
Program to Copy One String to Another
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter a string: ");
gets(str1);
strcpy(str2, str1);
printf("Copied String: %s", str2);
return 0;
}
Program to Reverse a String
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
strrev(str); // Note: Available in Turbo C. For GCC, use a custom function.
printf("Reversed String: %s", str);
return 0;
}
Program to Check if a String is Palindrome
#include <stdio.h>
#include <string.h>
int main() {
char str[100], temp[100];
printf("Enter a string: ");
gets(str);
strcpy(temp, str);
strrev(temp);
if(strcmp(str, temp) == 0)
printf("Palindrome");
else
printf("Not a Palindrome");
return 0;
}
Program to Count Vowels and Consonants in a String
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
gets(str);
for(int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if(isalpha(ch)) {
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
}
printf("Vowels: %d\nConsonants: %d", vowels, consonants);
return 0;
}