Skip to main content

Introduction

Focuses on the c11 standard

Hello World

// hello.c
#include <stdio.h>
int main() {
printf("HelloWorld\n");
return 0;
}

Compilation

can use g++ as c program is also a c++ program

g++ hello.c -o hello
gcc hello.c -o hello

Standard Output

Conversion Specifics

we have to include conversion specifics if we want to print a variable

variable typeconversion specific
int%d
float/ double%f
char%c
string%s
remove trailing zero for float/double%g

Example:

#include <stdio.h>
int a = 5;

int main() {
printf("I have %d apples\n", a); // print "I have 5 apples" through standard I/O
}

Output Formating

place number before the character in conversion specifics, e.g., "%8s"

// alloc 8 space and print apple (right-justified)
printf("I have %8d apples\n", a) // ___apple

String

string in C is an array of char

#include <stdio.h>
string fruit[] = "Apple"; // ['A', 'P', 'P', 'L', 'E', '\0']
int main() {
printf("I like %s", fruit);
}

Standard Input

use scanf in stdio

scanf(conversion specifics, address of first input, address of second input)

#include <stdio.h>
int a;
float b;
int main() {
scanf("%d%f", &a, &b) // takes in a int and float and store them to a/ b respectively
return 0;
}

Reading String

#include <stdio.h>
char name[100];
int main() {
// name is a pointer that points to first position of the char arr - name
scanf("%s", name)
return 0;
}