Skip to main content

c-in-21-days

Learnings from the book "Sams teach yoursels C in 21 days"

DaysTopics
Day 1Getting Started
Day 2Components of C Program
Day 3Variables and Constants
Day 4Statements,Operators,Expressions
Day 5Function
Day 6Arrays, Program control(for, while, do...while)
Day 7Display - printf
Day 8Numeric Arrays
Day 9Pointers
Day 10Characters, Strings
Day 11Structures,Unions, Typedefs
Day 12Variable Scopes
Day 13Advanced Program control(break,continue,switch,exit())
Day 14Input and Output
Day 15Pointers-advanced
Day 16Using Disc files
Day 17Manipulating strings
Day 18Functions-advanced
Day 19C function Library
Day 20Working with memory
Day 21Advanced compiler use

Getting Started

Compiling a program using GCC compiler

gcc helloworld.c

First Program

#include<stdio.h>

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

Components of C Program

Consider the following Program

1: /* Program to calculate the product of two numbers. */
2: #include <stdio.h>
3:
4: int val1, val2, val3;
5:
6: int product(int x, int y);
7:
8: int main( void )
9: {
10: /* Get the first number */
11: printf(“Enter a number between 1 and 100: “);
12: scanf(“%d”, &val1);
13:
14: /* Get the second number */
15: printf(“Enter another number between 1 and 100: “);
16: scanf(“%d”, &val2);
17:
18: /* Calculate and display the product */
19: val3 = product(val1, val2);
20: printf (“%d times %d = %d\n”, val1, val2, val3);
21:
22: return 0;
23: }
24:
25: /* Function returns the product of the two values provided */
26: int product(int x, int y)
27: {
28: return (x * y);
29: }

Components:

  1. main() Function - 8 to 23
  2. #include directive - 2
  3. variable definition - 4
  4. Function Prototype - 6
  5. Program statements - 11,12,15,16...
  6. Function Definition - 26 to 29

Variables and Constants

byte is the fundamental unit of computer data storage

C'x numeric datatypes

CharacterKeywordBytes RequiredRange
Characterchar1-128 to 127
Short Integershort2-32767 to 32767
Integerint4-2,147,438,647 to 2,147,438,647
Long Integerlong4-2,147,438,647 to 2,147,438,647
Long Long Integerlong long8-9,223,372,036,854,775,807 to 9,223,372,036,854,775,807

More on page 45

Typedef and initializing variables

Typedef creates a new name for a existing datatype, can rename int to integer

typedef int integer;

intializing variables

int count;
count = 0;

Statements,Operators,Expressions

Statement

Statement is a complete instruction to carry out a task

x = 2+3; #assignment statement

# compound statement is also called a block
{
printf(“Hello, “);
printf(“world!”);
}

Operators

A symbol that instructs C to perform some operation

x=y # assignment operator

a = 10;

# unary mathematical operators
b = ++a; # increment operator
c = --a; # decrement operator

# relational operators (if and while statements)
if (expression)
{
statement;
}

# logical operators
# AND OR NOT -> Page 81

Expressions

Function

Function is named, is independent, performs a specific task, can return value to the calling program

/* Demonstrates a simple function */
#include <stdio.h>
long cube(long x);
long input, answer;
int main( void )
{
printf(“Enter an integer value: “);
scanf(“%d”, &input);
answer = cube(input);
/* Note: %ld is the conversion specifier for */
/* a long integer */
printf(“\nThe cube of %ld is %ld.\n”, input, answer);

return 0;
}

/* Function: cube() - Calculates the cubed value of a variable */
long cube(long x)
{
long x_cubed;

x_cubed = x * x * x;
return x_cubed;
}

Arrays, Program control(for, while, do...while)

An array is an indexed group of data storage locations

int data[1000];
int index;
index = 100;
data[index] = 12; /* The same as data[100] = 12 */

Program control

for, while, do statements

Display - printf

printf function , used to display data on screen

more examples

Numeric Arrays

  • Single Dimensional Arrays
float expenses[100];
int a[10];
/* additional statements go here */
expenses[i] = 100; // i is an integer variable
expenses[2 + 3] = 100; // equivalent to expenses[5]
expenses[a[2]] = 100; // a[] is an integer array
  • Multi Dimensional Arrays

For example: two dimensional array

int checker[8][8];

Alternate way of anming and declaring arrays

#define MONTHS 12
int array[MONTHS];
is equivalent to this statement:
int array[12];

const int MONTHS = 12;
int array[MONTHS]; /* Wrong! */

Pointers

Pointer is a variable that contains the address if another variable

Declaring Pointers

typename *ptrname;

char *ch1, *ch2; /* ch1 and ch2 both are pointers to type char */

float *value, percent; /* value is a pointer to type float, and /* percent is an ordinary float variable */

Initializing Pointers

pointer = &variable;

p_rate = &rate; /* assign the address of rate to p_rate */

Using Pointers

printf(“%d”, rate);
or you could write this statement:
printf(“%d”, *p_rate);

Pointer Arithmetic

Characters, Strings

char datatype

Array of characters

char string[10] = { ‘A’, ‘l’, ‘a’, ‘b’, ‘a’, ‘m’, ‘a’, ‘\0’ };

malloc() Function

Memory allocation function in C

Example 1
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
/* allocate memory for a 100-character string */
char *str;
str = (char *) malloc(100);
if (str == NULL)
{
printf( “Not enough memory to allocate buffer\n”);
exit(1);
}
printf( “String was allocated!\n” );
return 0;
}
Example 2
/* allocate memory for an array of 50 integers */
int *numbers;
numbers = (int *) malloc(50 * sizeof(int));
Example 3
/* allocate memory for an array of 10 float values */
float *numbers;
numbers = (float *) malloc(10 * sizeof(float));

Structures,Unions, Typedefs

A structure is a collection of one or more variables grouped under a single name for easy manipulation.

struct coord {
int x;
int y;
};
  • Using a simple structure
/* simple.c - Demonstrates the use of a simple structures*/

#include <stdio.h>

int length, width;
long area;

struct coord{
int x;
int y;
} myPoint;

int main( void )
{
/* set values into the coordinates */
myPoint.x = 12;
myPoint.y = 14;

printf(“\nThe coordinates are: (%d, %d).”,
myPoint.x, myPoint.y);

return 0;
}
  • Complex Structures
  • Initializing structures
  • Structures and pointers
  • Unions

Variable Scopes

The scope of a variable refers to the extent to which different parts of a program have access to the variable—in other words, where the variable is visible

  • External variables
  • local Variables

Advanced Program control(break,continue,switch,exit())

  • Ending loops early with break
  • goto statement
  • Infinite loops
  • Exiting the program
  • Executing OS commands in a program

Input and Output

Pointers-advanced

  • Declaring Pointers to pointers
  • Pointers and Multidimensional Arrays
  • Working with Arrays of Pointers
  • Working with Pointers to Functions

Using Disc files

Manipulating strings

Functions-advanced

  • Passing Pointers to Functions
  • Functions That Return a Pointer

C function Library

  • Math functions
  • Dealing with time
  • Error handling
  • Searching and sorting

Working with memory

  • Type conversions

numerical data types

char short int long long long float double long double

  • Allocating memory storage space
  • Manipulating Memory Blocks

Advanced compiler use

  • Modular Programming techniques