Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

C Programming

C is a general-purpose, statically typed, and imperative programming language which


was founded in 1972 by Dennis Ritchie at Bell’s Laboratories. It is one of the oldest
and finest programming language.

Uses of C

*Most parts of Windows, Linux, and other operating systems are written in C.

*C is used to write driver programs for devices like Tablets, Printers, (etc.).
Comments

Comments is some text that does not get executed while the program runs and used
for the explanation or description of the code. The compiler ignores the comments
when it runs the code.
There are two types of comments: Single-line and Multi-line Comments
// This is /* This is
// Single-Line Multi-line
// Comment Comment */

Escape Sequence

Escape Sequence is the character combination consisting of a backslash (\) followed


by a letter or digits that specifies actions within a line or string of text.
\n = newline
\t = horizontal tab // 1 2 3
\v = vertical tab
\’ = single quotation mark
\” = double quotation mark
\? = question mark
\\ = backslash

Variables

Variables are the small amount of memory whose value may change while the
program runs. We create a variable in two steps in C: Declaration and Initialization.

int myAge; // declaration


myAge = 15; // initialization

*Notes:

-Variable names are case-sensitive.


-Convention says that first word of variable name is lowercase, and any additional
words are capitalized. // myFirstVariable
Data Types

Data type is the type of data that can be stored by a variable in C.

short int = %d (-32,767 to +32,768)


unsigned short int = %d (0 to +65,535)
int = %d (-2,147,483,648 to +2,147,483,647)
unsigned int = %u (0 to +4,294,967,295)
long long int = %lld (-9 quintillion to +9 quintillion)
char = %c (for single character)
%s (for array of characters)
float = %f (up to 7 digits)
double = %lf (up to 15 digits)
long double = %Lf (…)
*Notes:
-‘unsigned’ makes the variable store only positive values.
-Format specifier formats and defines the type of data to be displayed.
**For extra study, prefer Bro_Code \ C_Tutorial \ Format_Specifier \

Boolean Data Type

It is the data type that stores either ‘true’ or ‘false’ value. It uses 1 Byte of memory
and works in binary; 1 for ‘true’, and 0 for ‘false’.
Ex. bool e = true;
printf(“%d”, e); // output will be 1.
*Notes:
-We must include <stdbool.h> to use this data type.
-The format specifier for it is %d.
Constants

Constants are the fixed values which can not be altered by the program during its
execution.
Ex. const double PI = 3.141592654;
*Notes:

-Convention says that constant name is written in uppercase, and the words are
separated by underscore (_). // MY_FAV_NUM

Arithmetic Operators

Arithmetic Operators are one of the elements in C that perform certain mathematical
calculation.
+ = for addition
- = for subtraction
* = for multiplication
/ = for division
% = for modular division
++ = for increment by
-- = for decrement by 1
*Notes:

-Pay attention to integer division in C.


Ex. int x = 7; int y = 2;
int z = x / y;
printf(“%d”, x / y); // the output will be 3 NOT 3.5.
To fix it, we can write: double z = x / (double) y;

Augmented Assignment Operators

Augmented Assignment Operators provide a short way to perform mathematical


calculation and assign the result to the same variable which was used as operand.
x += 2 , x -= 2, x*= 2, x /= 2, x %= 2
User Input

We can take the user input in C by using scanf function.


Ex. scanf(“%d”, &age);
We can take the full name of the user as an input using fgets function.
Ex. fgets(name, 25, stdin);
*Notes:

-fgets function accepts whitespaces along with the string.


-Always use an ampersand (&) sign before the variable in scanf function.
-In case of array of characters, use of ampersand (&) sign is not necessary.

Math Functions

Math Functions help us to perform certain mathematical operations like taking


square root, rounding off, (etc.). To use these functions, we have to include <math.h>
header file.
sqrt(number) = finds square root of any number
pow(base, index) = raises a number by n power
round(double) = rounds off a decimal number
ceil(double) = always rounds the number up
floor(double) = always rounds the number down
fabs(number) = finds absolute value of a number
log(number) = find the logarithm of a number
sin(angle value) = finds sine of an angle
cos(angle value) = finds cosine of an angle
tan(angle value) = finds tangent of an angle
If Statements

If statement helps us to check for a certain condition.


Syntax goes like this:

If ( statement ) {
1st condition;
} else if ( statement ) {
2nd condition;
} else {
Last condition;
}

*Notes:

- ‘=’ is an assignment operator, and ‘==’ is a relational operator.


- Other relational operators are ‘>’, ‘<’, ‘>=’, ‘<=’, ‘!=’.

Switch Statements

Switch statement helps us to check a value for equality against many conditions. It is
more efficient alternative to using many ‘else if’ statements.
Syntax of it goes like this:

switch ( value ) {
case value1:
statement(s);
break; // break; is mandatory
….

default:
statement(s);
}
AND Logical Operator

AND logical operator returns true value if all given two or more conditions are true.
‘&&’ represents AND operator in C.
It can be used as:

double height = 5.9;


bool male = true;
if ( height > 5.6 && height < 8 && male = true ) { // ..male = 1 OR
male
printf(“You can be an army !”);
} else {
printf(“Sorry, you can not be in army coaching.”);
} //output will be “You can be an army !”

OR Logical Operator

OR logical operator checks if at least one condition among all the given conditions is
true. ‘||’ represents OR operator in C.
It can be used as:

int math = 70
int science = 92
if ( math > 90 || science > 85 ) {
printf(“You can enroll my class.”);
} else {
printf(“Better luck next time:)”);
} // output will be “You can enroll my class”

NOT Logical Operator

NOT logical operator reverses the state of a condition. This means it returns false
value if the condition is true and vice-versa. ‘!’ represents NOT operator in C.
It can be used as:
bool sunny = false;
if ( !sunny ) {
printf(“It’s cloudy outside.”);
} else {
printf(“Wow! It’s sunny outside”);
} // output will be “It’s cloudy outside.”

Ternary Operator

Ternary operator is the shortcut to if/else statement while assigning or returning the
value. It can be used in functions while returning value.
Syntax of it goes like this:

( condition ) ? value if true : value if false ;

Ex.

char check ( int x ) {


return x % 2 = 0 ? “Even” : “Odd” ;
}
int main () {
char result [ ] = check ( 13 ) ;
printf(“%s”, result);
return 0;
} // output will be “Odd”
String Functions

String Functions are pre-defined functions included in <string.h> header file, that help
us to perform certain operation on a string.

strlwr(string) = converts a string into lowercase.


strupr(string) = converts a string into uppercase.
strcat(string, string) = appends (joins) second string to the first string.
strcpy(string, string) = copies the second string to the first string
strset(string, ‘character’) = sets all the characters of a string to a given character.
strrev(string) = reverses a string.
strlen(string) = counts the number of characters in a string
strcmp(string, string) = compares all the characters of two strings
strcmpi(string, string) = compares all the characters, but ignores the case.

strncat(string, string, no_of_characters) = catenates first n characters of second


string to the first string.
strncpy(string, string, no_of_characters ) = copies first n characters of second string
to the first string
strnset(string, ‘char’, no_of_character) = sets first n characters of a string to a
given character.
strncmp(string, string, no_of_characters) = compares n characters of two given
strings

For Loops

In programming, a loop is the repetition of a block of code until the certain condition
is satisfied. For loop is one of the looping statements in C.
Syntax of it goes like this:

for ( initialization ; condition ; increment/decrement ) {


// code to be executed.

} While Loops

While loop repeats a block of code until the given condition remains satisfied. In
some cases, while loop might not execute at all.
Syntax of it goes like this:

while ( condition ) {
// code to be executed.
}

Do While Loop

Do While loop always executes a block of code first, THEN checks for the condition.
Syntax of it goes like this.

do {
// code to be executed.
} while ( condition ) ;

Nested Loop

Nested loop is a loop inside another loop.


Ex.

for ( int i = 1 ; i <= 5 ; i++ ) { // ‘i’ stands for ‘index’,


for ( int j = 1 ; j <= i ; j++ ) { // conventionally, we write only i.
printf(“%d ”, j );
}
printf(“\n”);
}
Break and Continue

Break is used to exit out of the entire loop / switch. Continue is used to skip the
current iteration of the loop and moves to the next iteration of the loop.
They can be used as:

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


if ( i == 7 ) {
continue;
}
if ( i == 9 ) {
break;
}
printf(“%d ”, i);
} // the output will be: 1 2 3 4 5 6 8

Array
An array is the data structure that can hold many values of same data type in a single
variable.
Ex. int houseNumber [ ] = { 245 , 111 , 109 , 094 } ;
*Notes:
-To access the elements in an array, we need to use their indexes.
-The index of first element is 0, that of second is 1, an d so on.
-Ex. “ printf(“%d”, houseNumber [ 2 ] ); ” will print the value 109.

Loop + Array

double humanMasses [ ] = { 30.0 , 25.0 , 67.0 , 93.0 , 32.0 } ;


for ( int i = 0 ; i < sizeof( humanMasses ) / sizeof( humanMasses[0] ) ; i++ ) {
printf(“%.2lf kg \n”, humanMasses[i] );
}
Structs
Structure (also known as Struct) is the collection of related variables that can be of
different data types under a single name. A struct is defined / written outside the
main() function. typedef…..
Ex.

struct biodata {
char name [25];
int age;
double gpa;
}; // ; is mandatory
int main() {
struct biodata firstPerson;
strcpy( firstPerson.name, “Unik” );
}

Array of Structs

#include <stdio.h>

struct employeeName {
char name[25];
int age;
};

int main() {

struct employeeName employee1 = {"Funik", 14};


struct employeeName employee2 = {"Bunik", 10};
struct employeeName employee3 = {"Tunik", 15};
struct employeeName employee4 = {"Unik", 15};

struct employeeName employees[4] = {employee1, employee2, employee3,


employee4};

for(int i = 0; i < sizeof(employees) / sizeof(employees[0]); i++) {


printf("%-15s", employees[i].name);
printf("%d \n", employees[i].age);
}
return 0;
}
Bitwise Operators
Bitwise operators are the special operators used in bit level programming.
& = AND
| = OR
^ = XOR
<< = left shift // doubles the number.
>> = right shift // makes the number half.

You might also like