28
In CodeBlocks, we need to invoke the compiler with the –std=c99 option for a lot of things like the ‘for’ loop to work. To do this go to ‘Settings’ ‘Compiler’ ‘Other Options’ and type ‘-std=c99’ in the window. Working with integers #include <stdio.h> #include <stdlib.h> int main() { int num1 = 5; int num2 = 7; int num3 = num1/num2 ; printf("%i \t", num3); return 0; }

C Programming Notes - Part 1

Embed Size (px)

DESCRIPTION

Basic C Programming

Citation preview

In CodeBlocks, we need to invoke the compiler with the std=c99 option for a lot of things like the for loop to work. To do this go to Settings Compiler Other Options and type -std=c99 in the window.

Working with integers#include #include

int main(){ int num1 = 5; int num2 = 7; int num3 = num1/num2 ; printf("%i \t", num3); return 0;}Working with floating numbers#include #include

float main(){ float num1 = 5; float num2 = 7; float num3 = num1/num2 ; printf("%.2f \t", num3); return 0;}Working with characters#include #include

char main(){ char char1 = 'A'; printf("%c \t", char1); return 0;}Getting input from the user#include #include

int main(){ int num1 = 0; printf("Please enter a number:\t"); scanf("%i", &num1); int num2 = 0; printf("Please enter a second number:\t"); scanf("%i", &num2); printf("%i", num1 + num2); return 0;}If loops#include #include

void main(){ printf("Please provide a character input:\t"); int char1; scanf("%c", &char1); if (char1 == 'a') { printf("Hello"); } else if (char1 == 'b') { printf("Great"); } else { printf("You have entered an invalid character.\n"); } return 0;}Building a calculator with the if loop#include #include

int main(){ printf("Please say what operation you want to perform:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n"); int char1; scanf("%c", &char1); printf("Please enter the first number:\t"); float num1; scanf("%f", &num1); printf("Please enter the second number:\t"); float num2; scanf("%f", &num2); if (char1 == 'A' || char1 == 'a') { printf("The sum is:\t%f", num1+num2); } else { printf("You have entered an invalid character.\n"); } return 0;}Switch cases#include #include

void main(){ printf("Please provide a character input:\t"); int char1; scanf("%c", &char1); switch (char1) { case 'A': printf("Hello"); break; case 'B': printf("Happy Birthday"); break; default: printf("You entered an invalid char"); break; } return 0;}While loop#include #include

void main(){ int i = 1; while(i