0% found this document useful (0 votes)
4 views9 pages

C Language Notes

This document serves as a beginner's guide to the C programming language, focusing on arrays, loops, and strings. It explains fundamental concepts with simple examples, including how to declare and initialize arrays, use different types of loops, and manage strings. Additionally, it provides practical use cases and example programs to illustrate the application of these concepts.

Uploaded by

Dev Kali
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)
4 views9 pages

C Language Notes

This document serves as a beginner's guide to the C programming language, focusing on arrays, loops, and strings. It explains fundamental concepts with simple examples, including how to declare and initialize arrays, use different types of loops, and manage strings. Additionally, it provides practical use cases and example programs to illustrate the application of these concepts.

Uploaded by

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

C Language

Beginner's Notes
Arrays • Loops • Strings & Characters

👋 Written for absolute beginners. No prior knowledge needed. Every concept is explained simply
with real examples and working programs.

1. Arrays
What is an Array?
Think of an array like a row of boxes, each holding one value. Instead of creating 5 separate variables
like num1, num2, num3, num4, num5, you create ONE array that holds all 5 values.

💡 Real-world analogy: An array is like an egg carton — one container with numbered slots (0, 1,
2...), each holding one egg.

How to Declare an Array


// Syntax:
datatype arrayName[size];

// Examples:
int marks[5]; // holds 5 integers
float prices[10]; // holds 10 decimal numbers
char name[20]; // holds 20 characters (a string)

How to Initialize (Fill) an Array


int marks[5] = {90, 85, 78, 92, 88};

// Access individual elements using index (starts at 0):


printf("%d", marks[0]); // prints 90 (first element)
printf("%d", marks[4]); // prints 88 (last element)
⚠️ IMPORTANT: Array index starts at 0, NOT 1. So for an array of size 5, valid indexes are 0, 1, 2, 3,
4.

Use Cases
Store marks Save marks of 30 students in one array instead of 30 variables
Store temperatures Daily temperatures for a month — float temp[31]
Store names List of names using char arrays
Process data Find average, maximum, minimum from a list of numbers

Benefits
Less code One array replaces many variables
Easy to loop Use a for loop to process all elements at once
Organized Data is stored in order, easy to access by index
Flexible size Can handle 5 or 500 items with the same code structure

Simple Example Program — Find Average Marks


#include <stdio.h>

int main() {
int marks[5] = {80, 90, 75, 95, 85};
int sum = 0;
float average;

// Add all marks


sum = marks[0] + marks[1] + marks[2] + marks[3] + marks[4];

// Calculate average
average = sum / 5.0;

printf("Sum: %d\n", sum);


printf("Average: %.2f\n", average);

return 0;
}

// Output:
// Sum: 425
// Average: 85.00
2. Loops
What is a Loop?
A loop lets you repeat a block of code multiple times without writing it again and again. Imagine you
want to print numbers 1 to 100 — without a loop you'd write 100 print statements. With a loop, just 3
lines!

💡 Real-world analogy: A loop is like a washing machine cycle — it repeats the same steps (wash,
rinse, spin) until the job is done.

Type 1: for Loop (when you know how many times)


Syntax
for (start; condition; step) {
// code to repeat
}

Example
#include <stdio.h>

int main() {
// Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}

// Output: 1 2 3 4 5

How it works: i=1 starts at 1. i<=5 runs as long as i is 5 or less. i++ adds 1 after each round.

Type 2: while Loop (when you don't know how many times)
Syntax
while (condition) {
// code to repeat
}

Example
#include <stdio.h>

int main() {
int n = 1;
while (n <= 5) {
printf("%d\n", n);
n++; // don't forget this or it loops forever!
}
return 0;
}

// Output: 1 2 3 4 5

Type 3: do-while Loop (always runs at least once)


Syntax
do {
// code to repeat
} while (condition);

Example
#include <stdio.h>

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

// Output: 1 2 3 4 5

When to use which loop?


for loop You know how many times to repeat (e.g. loop 10 times)
while loop You repeat until a condition is false (e.g. keep asking until correct input)
do-while You want the code to run at least once no matter what

Use Cases
Print tables Print multiplication table of any number
Sum numbers Add 1+2+3+...+100 using a loop
Process arrays Go through each element of an array
Menu programs Keep showing a menu until user chooses Exit
Count digits Count how many digits are in a number
Simple Example Program — Multiplication Table
#include <stdio.h>

int main() {
int num = 5;

printf("Table of %d:\n", num);

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


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

return 0;
}

// Output:
// 5 x 1 = 5
// 5 x 2 = 10
// ...up to...
// 5 x 10 = 50

⚠️ Common mistake: Forgetting to update the loop variable (i++) causes an infinite loop. Always
make sure the loop condition will eventually become false.

3. Strings & Characters


What is a Character (char)?
A char stores a single character like 'A', 'z', '5', or '!'. It uses single quotes. In memory it's stored as a
number (ASCII code).
char grade = 'A';
char symbol = '#';
char digit = '7';

printf("%c", grade); // prints: A


printf("%d", grade); // prints: 65 (ASCII code of 'A')

💡 Every character has an ASCII number. 'A'=65, 'a'=97, '0'=48. You can do math: 'A'+1 gives 'B'.

What is a String?
A string is a sequence of characters. In C, strings are stored as a char array ending with a special \0
character (null terminator) that marks the end.
char name[10] = "Rahul";
// Stored as: R a h u l \0 _ _ _ _
// Index: 0 1 2 3 4 5

printf("%s", name); // prints: Rahul

Reading Strings from User


char city[50];

// Method 1: scanf (stops at space)


scanf("%s", city);

// Method 2: fgets (reads full line with spaces)


fgets(city, 50, stdin);

Useful String Functions (from <string.h>)


strlen(s) Returns the length (number of chars) of string s
strcpy(dest, src) Copies src string into dest
strcat(dest, src) Joins/appends src to end of dest
strcmp(s1, s2) Compares two strings. Returns 0 if equal
strupr(s) Converts string to UPPERCASE (not in all compilers)
strlwr(s) Converts string to lowercase (not in all compilers)

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

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

printf("Length: %lu\n", strlen(name)); // 5

char greeting[20];
strcpy(greeting, "Hi ");
strcat(greeting, "World");
printf("%s\n", greeting); // Hi World

// Compare two strings


if (strcmp("apple", "apple") == 0) {
printf("Strings are equal!\n");
}
return 0;
}

Use Cases
char Store grade, gender, menu choice, single digit input
String Store name, address, password, sentence, file path
strcmp Login password checking, sorting names alphabetically
strlen Validate if name is too long or too short
strcat Build a full sentence from parts

Simple Example Program — Reverse a String


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

int main() {
char word[50];
printf("Enter a word: ");
scanf("%s", word);

int len = strlen(word);

printf("Reversed: ");
for (int i = len - 1; i >= 0; i--) {
printf("%c", word[i]);
}
printf("\n");

return 0;
}

// Input: hello
// Output: olleh

⚠️ Always make your char array big enough. If you declare char name[10] but store 20 characters, it
causes a buffer overflow — a serious bug.

4. Putting It All Together


Arrays + Loops + Strings — One Combined Program
This program stores 3 student names and their marks, then prints them neatly. It uses all three
concepts together.

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

int main() {
// Array of strings (names)
char names[3][20] = {"Arjun", "Priya", "Rohit"};

// Array of integers (marks)


int marks[3] = {88, 95, 76};

int sum = 0;

printf("--- Student Report ---\n");

// Loop through all students


for (int i = 0; i < 3; i++) {
printf("Name: %-10s Marks: %d\n", names[i], marks[i]);
sum += marks[i];
}

printf("----------------------\n");
printf("Class Average: %.1f\n", sum / 3.0);

return 0;
}

// Output:
// --- Student Report ---
// Name: Arjun Marks: 88
// Name: Priya Marks: 95
// Name: Rohit Marks: 76
// ----------------------
// Class Average: 86.3

5. Quick Reference Cheat Sheet


Concept Syntax / Example Purpose

Array declare int a[5]; Create array of 5 ints


Array access a[0], a[1]... Get element by index

Array init int a[]={1,2,3}; Fill array at start


for loop for(i=0;i<5;i++) Repeat known times

while loop while(x<10){...} Repeat until false


do-while do{...}while(c); Run at least once

char variable char c = 'A'; Single character


string declare char s[20]; Array of chars

strlen strlen(str) Length of string

strcpy strcpy(a, b); Copy string b to a

strcat strcat(a, b); Append b to end of a


strcmp strcmp(a,b)==0 Compare two strings

🚀 You now know 3 of the most important building blocks of C! Practice by modifying the example
programs — change numbers, add more students, try different words. The best way to learn coding is
by doing.

You might also like