KEMBAR78
C Language Notes With Problems | PDF | C (Programming Language) | Data Type
0% found this document useful (0 votes)
46 views15 pages

C Language Notes With Problems

Uploaded by

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

C Language Notes With Problems

Uploaded by

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

C Language

Detailed Notes with Explanations

1. Introduction to C

C is a procedural programming language developed by Dennis Ritchie in 1972


at Bell Laboratories.
It is one of the most influential programming languages and has shaped many
modern languages like C++, Java, and Python.

Why use C?

 It is fast and efficient, suitable for system programming such as operating


systems and embedded systems.
 Provides low-level access to memory using pointers, which makes it powerful
for hardware-level manipulation.
 Highly portable across different platforms and devices.

2. Structure of a C Program

Every C program has a basic structure that must be followed for successful
compilation and execution.

#include <stdio.h> // Preprocessor directive to include standard input/output library

int main() { // Main function where program execution starts


printf("Hello, World!"); // Print the message to the screen
return 0; // Return statement indicates successful program termination
}

Explanation:

 #include <stdio.h> tells the compiler to include the Standard Input Output
library which contains functions like printf.
 int main() is the entry point of every C program; execution starts here.
 printf() prints text to the console.
 return 0; signals the program ended without errors.

1|P age
3. Basic Syntax

 Every statement in C ends with a semicolon (;). This tells the compiler where
one instruction ends and another begins.
 Curly braces {} group statements into blocks, like the body of functions or
loops.
 Comments help explain code and are ignored by the compiler:
o Single-line comments start with //.
o Multi-line comments are enclosed between /* and */.

4. Variables and Data Types

A variable is a named location in memory used to store data. Before using a


variable, you must declare it with a data type, which defines the kind of data it can
hold.

Example declaration:

int age = 20;

Common Data Types:

Type Description Size (bytes) Example


int Integer numbers (whole numbers) Usually 4 int age = 30;
float Floating point numbers (decimals) Usually 4 float price = 9.99;
char Single characters Usually 1 char grade = 'A';
double Double precision floating point Usually 8 double pi = 3.14;

Explanation:
Choosing the right data type is important because it affects the size of memory
allocated and the type of operations you can perform.

5. Input and Output

C provides built-in functions to interact with users.

Output with printf:

printf("Your age is %d", age);

 %d is a format specifier used to print an integer variable.

2|P age
Input with scanf:

scanf("%d", &age);

 %d tells scanf to expect an integer input.


 The & (address-of) operator gives the memory address of the variable where
the input will be stored.

Explanation:
Format specifiers must match the variable type for input/output functions to work
correctly.

6. Operators in C

Operators perform operations on variables and values.

Arithmetic Operators:

Operator Operation Example


+ Addition 5+3=8
- Subtraction 5-3=2
* Multiplication 5 * 3 = 15
/ Division 6/3=2
% Modulus (remainder) 5 % 2 = 1

Relational Operators:

Used to compare values and return true or false.

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater or equal
<= Less or equal

Logical Operators:

Used to combine multiple conditions.


3|P age
Operator Meaning
&& AND

! NOT

Assignment Operators:

Assign values to variables, sometimes combined with arithmetic.

Operator Meaning Example


= Assign x=5
+= Add and assign x += 3 (x = x + 3)
-= Subtract and assign x -= 2 (x = x - 2)

Increment and Decrement:

Operator Meaning
++ Increment by 1
-- Decrement by 1

Explanation:
Operators let you perform calculations, make decisions, and manipulate data.

7. Control Statements

Control the flow of the program.

if-else Statement

Executes code based on a condition.

if (age >= 18) {


printf("You are an adult.");
} else {
printf("You are a minor.");
}

Explanation:
If the condition is true, the first block runs; else the second block runs.

4|P age
switch Statement

Selects one of many blocks based on a variable's value.

switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
default: printf("Invalid day");
}

Loops

Used to repeat code multiple times.

for loop

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


printf("%d\n", i);
}

Explanation:
Starts from i=0, runs as long as i < 5, increments i each loop.

while loop

int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}

do-while loop

int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);

Difference: do-while runs at least once.

5|P age
8. Functions

Functions break a program into reusable pieces.

int add(int a, int b) {


return a + b;
}

 int is the return type (this function returns an integer).


 add is the function name.
 (int a, int b) are parameters the function receives.

Calling a function:

int result = add(5, 3);

Explanation:
Functions help keep code organized, reduce repetition, and improve readability.

9. Arrays

An array stores multiple values of the same data type in a contiguous block.

int numbers[5] = {1, 2, 3, 4, 5};

 numbers[0] accesses the first element.


 Arrays start at index 0.

Explanation:
Arrays allow handling lists of data efficiently.

10. Strings

Strings are arrays of characters ending with a special null character \0 to indicate
the end.

char name[] = "Alice";

String functions: (from string.h)

6|P age
 strlen(name) returns the length of the string.
 strcpy(dest, src) copies one string to another.
 strcmp(str1, str2) compares two strings.
 strcat(dest, src) concatenates (joins) two strings.

11. Pointers

Pointers store the memory address of another variable.

int x = 10;
int *p = &x;

 *p accesses the value stored at the address.


 &x gets the address of variable x.

Explanation:
Pointers provide powerful control over memory and are essential for dynamic
memory allocation and advanced data structures.

12. Structures

Structures group variables of different types under one name.

struct Student {
char name[20];
int age;
};

Using structures:

struct Student s1;


strcpy(s1.name, "Bob");
s1.age = 21;

Explanation:
Structures help model real-world entities with multiple attributes.

13. File Handling

Files allow programs to save data permanently.

7|P age
FILE *fp = fopen("file.txt", "w"); // Open file for writing
fprintf(fp, "Hello File"); // Write to file
fclose(fp); // Close file

File modes:

 "r" - read
 "w" - write (overwrite)
 "a" - append (add to end)

Explanation:
File handling lets you create, read, update, and delete files on disk.

14. Preprocessor Directives

Instructions executed before actual compilation.

 #include includes header files.


 #define defines constants or macros.
 Conditional compilation with #ifdef and #endif lets you compile code
selectively.

8|P age
Sample Programs for practice:
Problem 1: Print Hello World

Question:
Write a program to print Hello, World! on the screen.

Code:

#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
}

Explanation:
Use printf() to display text. \n adds a new line. The main() function starts the
program.

Problem 2: Add Two Numbers

Question:
Write a program that takes two integers and prints their sum.

Code:

#include <stdio.h>

int main() {
int a, b, sum;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
9|P age
Explanation:
Read inputs with scanf(), add them, print the result with printf().

Problem 3: Check Even or Odd

Question:
Write a program to check whether a number is even or odd.

Code:

#include <stdio.h>

int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);

if (num % 2 == 0)
printf("%d is even.\n", num);
else
printf("%d is odd.\n", num);

return 0;
}

Explanation:
Use % (modulo) operator to check remainder when dividing by 2.

Problem 4: Find Largest of Three Numbers

Question:
Find the largest number among three inputs.

Code:

#include <stdio.h>

int main() {

10 | P a g e
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);

if (a >= b && a >= c)


printf("%d is largest.\n", a);
else if (b >= a && b >= c)
printf("%d is largest.\n", b);
else
printf("%d is largest.\n", c);

return 0;
}

Explanation:
Compare all numbers using if-else and logical AND &&.

Problem 5: Calculate Factorial

Question:
Calculate factorial of a number using a loop.

Code:

#include <stdio.h>

int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);

if (n < 0)
printf("Factorial doesn't exist for negative numbers.\n");
else {
for (i = 1; i <= n; ++i)
fact *= i;
printf("Factorial of %d = %llu\n", n, fact);
}
return 0;
}

Explanation:
Multiply numbers from 1 to n in a loop to get factorial.
11 | P a g e
Problem 6: Print Multiplication Table

Question:
Print multiplication table of a given number.

Code:

#include <stdio.h>

int main() {
int n, i;
printf("Enter a number: ");
scanf("%d", &n);

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


printf("%d x %d = %d\n", n, i, n*i);
}
return 0;
}

Explanation:
Loop from 1 to 10, multiply and print each product.

Problem 7: Calculate Average of Three Numbers

Question:
Calculate average of three numbers.

Code:

#include <stdio.h>

int main() {
float a, b, c, avg;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
avg = (a + b + c) / 3;
printf("Average = %.2f\n", avg);
12 | P a g e
return 0;
}

Explanation:
Add three floats and divide by 3. Use %.2f to print two decimals.

Problem 8: Celsius to Fahrenheit Conversion

Question:
Convert Celsius temperature to Fahrenheit.

Code:

#include <stdio.h>

int main() {
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 9 / 5) + 32;
printf("Temperature in Fahrenheit = %.2f\n", fahrenheit);
return 0;
}

Explanation:
Use formula: F = (C × 9/5) + 32.

Problem 9: Check Prime Number

Question:
Check if a number is prime.

Code:

#include <stdio.h>

int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

if (n <= 1)
13 | P a g e
flag = 1;
else {
for(i = 2; i <= n/2; ++i) {
if (n % i == 0) {
flag = 1;
break;
}
}
}

if (flag == 0)
printf("%d is prime.\n", n);
else
printf("%d is not prime.\n", n);

return 0;
}

Explanation:
Check divisibility from 2 to n/2. If divisible, not prime.

Problem 10: Fibonacci Series

Question:
Print first n Fibonacci numbers.

Code:

#include <stdio.h>

int main() {
int n, i;
int t1 = 0, t2 = 1, nextTerm;
printf("Enter number of terms: ");
scanf("%d", &n);

printf("Fibonacci Series: ");

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


printf("%d ", t1);
14 | P a g e
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
printf("\n");
return 0;
}

Explanation:
Start with 0 and 1, then sum previous two terms repeatedly.

15 | P a g e

You might also like