C Video Tutorial 3

C Video Tutorial 3Welcome to part 3 of my C Video Tutorial!

In this tutorial I cover : exit(), switch, Arrays, Array Indexes, Problems with scanf(), Memory Overflow, strcpy(), fgets(), Array Interation, strcmp(), strcat(), strlen(), strlcpy(), Global Variables, Local Variables, Functions, and more…

The code below is heavily commented and will help you learn. Feel free to leave any questions you have.

If you like videos like this it helps to tell Google+ with a click here

Code From the Video

CTutorial3_1.c

#include <stdio.h>

// Needed for exit()
#include <stdlib.h> 

void main(){

	int whatToDo = 0;

	do{
	printf("\n");
	printf("1. What Time is It?\n");
	printf("2. What is Todays Date?\n");
	printf("3. What Day is It?\n");
	printf("4. Quit\n");
	
	scanf(" %d", &whatToDo);
	} while(whatToDo < 1 || whatToDo > 4);
	
	// How to handle the input with if
	
	if(whatToDo == 1){
	
		printf("Print the time\n");
	
	} else if(whatToDo == 2){
	
		printf("Print the date\n");
	
	} else if(whatToDo == 3){
	
		printf("Print the day\n");
	
	} else {
	
		printf("Bye Bye\n");
		
		// Exit the program with a non error state
		// Almost always better to use return
		
		exit(0);
	
	}
	
	printf("\n");
	
	// How to handle the input with switch
	// Switch checks the value provided and executes
	// accordingly. (Value must be char or int)
	// break is used to stop checking input against the
	// other options. Without break other options would 
	// be checked
	
	switch(whatToDo){
	
		case(1) : printf("Print the time\n");
					break;
					
		case(2) : printf("Print the date\n");
					break;
					
		case(3) : printf("Print the day\n");
					break;
					
		default : printf("Bye Bye\n");
					exit(0);
					break;
	
	}
	
}

CTutorial3_2.c

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

void main(){

printf("\n");
	
	// ARRAYS -------------
	
	// We have already taken a look at arrays when we stored
	// strings in a character array.
	// An int array is the same type of thing, and array
	// that stores ints.
	// An array can only store elements of the same data type
	
	char wholeName[12] = "Derek Banas";
	
	// You can also define an array one element at a time
	
	int primeNums[3] = {2, 3, 5,};
	
	// You don't need to define the size if you define
	// the values up front
	
	int morePrimes[] = {13, 17, 19, 23};
	
	// Like most other languages the first number in an 
	// array is put in the zero index
	
	printf("The first prime in the list is %d\n\n", 
		primeNums[0]);
		
	// A character array can be created the same way
	
	char city[7] = {'C', 'h', 'i', 'c', 'a', 'g', 'o'};
	
	// If I want to print the character array as a string
	// though I have to add \0 at the end
	
	char anotherCity[5] = {'E', 't', 'n', 'a', '\0'};
	
	printf("A City %s\n\n", anotherCity);
	
	// Creating the string like before is easier
	// No quotes and an automatic null at the end
	
	char thirdCity[] = "Paris";
	
	// Once an array is defined we can change the value with
	// strcpy() but make sure if you do that that the new 
	// array is of the same size, or less. Otherwise you will
	// overwrite other data in memory.
	// You have to make your arrays big enough to hold all
	// potential input, but don't over do it, or you'll consume
	// to much memory.
	
	char yourCity[30];
	
	printf("What city do you live in? ");
	
	// scanf() is kind of limited for adding a string to an array
	// 1. It will allow you to overwrite data past the end of
	//     the space allowed
	// 2. It won't allow you to enter spaces unless you define
	//     exactly how they will be entered
	// fgets() has neither of these problems and it also adds a
	// \0 at the end for you. The only negative is that you must
	// provide a size limit for the data being entered
	
	fgets(yourCity, 30, stdin);
	
	printf("Hello %s\n\n", yourCity);
	
	// fgets() Will read in everything up till the end of the array
	// is reached or until a \n is entered and then it will add
	// a \0 at the end. It leaves in the \n though which can be 
	// a bad thing.
	
	// Let's get rid of the '\n'
	// Use -std=c99 since we are initializing i below in the for
	
	for(int i = 0; i < 30; i++){
	
		if(yourCity[i] == '\n'){
		
			yourCity[i] = '\0';
			break;
		
		}
	
	}
	
	printf("Hello %s\n\n", yourCity);
	
	// Some string functions available
	
	// strcmp() takes 2 strings and returns a negative number 
	// if the first string is less then the second. It returns
	// a positive if the opposite occurs. It returns a 0 if
	// they are equal
	
	printf("Is your city Paris? %d\n\n",
		strcmp(yourCity, thirdCity));
		
	// strcat() adds the second string to the end of the first
	
	char yourState[] = ", Pennsylvania";
	
	strcat(yourCity, yourState);
	
	printf("You live in %s\n\n", yourCity);
	
	// strlen() returns the length of the string minus \0
	
	printf("Letters in Paris : %d\n\n", strlen(thirdCity));
	
	// As mentioned before strcpy() is bad for copying strings
	// because it can overwrite memory. 
	// That is were strlcpy() comes in.
	// It won't overwrite memory and it always adds a \0
	
	strlcpy(yourCity, 
		"El Pueblo del la Reina de Los Angeles", 
		sizeof(yourCity));
	
	printf("The new name is %s\n\n", yourCity);
	
}

CTutorial3_3.c

#include <stdio.h>

// Needed for exit(), rand()
#include <stdlib.h> 

// I'm a global variable. Every function can see me and change
// my value.

int globalVar = 0;

// Each function has a return type 
// (void if nothing is returned)
// Between the parentheses you can define the type and number
// of attributes passed to the function if any

int addTwoInts(int num1, int num2){

	// return the result to the function that called this one

	return num1 + num2;

}

void changeVariables(){

	// This variable is local and doesn't exist outside 
	// of this function even if it has the same name
	// as a variable outside of this function

	int age = 40;
	
	printf("age inside of function = %d\n\n", age);
	
	// Since globalVar is accessible in any function though 
	// can change it for all other functions
	
	globalVar = 100;
	
	printf("globalVar inside of function = %d\n\n", globalVar);

}

void main(){

	// FUNCTIONS ------------------
	
	// If you want to some day make a big program you will 
	// have to step out of main(). 
	// With a complex program you are going to want to write 
	// a function for each task required
	
	// How to call a function and pass data by value to it
	
	int total = addTwoInts(4,5);
	
	printf("The Sum is %d\n\n", total);
	
	// GLOBAL VS LOCAL VARIABLES ------
	
	// That brings us to the concept of local versus global
	// variables.
	
	// This age variable is local to main()
	
	int age = 10;
	
	// I changed the global variable globalVar here to 50
	
	globalVar = 50;
	
	printf("age before a call to the function = %d\n\n", age);
	
	printf("globalVar before a call to the function = %d\n\n", globalVar);
	
	changeVariables();
	
	printf("age after a call to the function = %d\n\n", age);
	
	printf("globalVar after a call to the function = %d\n\n", globalVar);

}

4 Responses to “C Video Tutorial 3”

  1. gaurav says:

    derek sir wanted to learn web development so could u plz guide me which of your tutorial I should take and their order.
    thanku

    • Derek Banas says:

      Check out this page I made Web Design Course. All my videos are on that one short page. Follow them in order, but feel free to skip XML and come back to it when you need it. You can also learn either javascript or php in either order. I hope that helps :)

  2. Oscar says:

    When I try the strlcpy function I get the error: undefined reference to strlcpy.
    I read that strlcpy is not standard c. do I need additional header files

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Google+