美文网首页c/c++
【算法笔记】C语言基础

【算法笔记】C语言基础

作者: 程序员Anthony | 来源:发表于2019-12-21 00:07 被阅读0次

最近开始学习算法和数据机构的相关书籍。需要用到C语言做算法描述,同时对比下Java语言。所以复习到大一学过的C语言。转眼已经8年时间。重学基础,重新规划兴趣和个人发展。一切不会太晚。

下面内容来自:https://www.learn-c.org/

hello world

#include <stdio.h>

int main() {
  printf("Hello, World!");
  return 0;
}

sum numbers

#include <stdio.h>

int main() {
  int a = 3;
  float b = 4.5;
  double c = 5.25;
  float sum;

  sum = a + b + c;

  printf("The sum of a, b, and c is %f.", sum);
  return 0;
}

defines an array

#include <stdio.h>

int main() {

  int grades[3];
  int average;

  grades[0] = 80;
  grades[1] = 85;
  grades[2] = 90;

  average = (grades[0] + grades[1] + grades[2]) / 3;
  printf("The average of the 3 grades is: %d", average);

  return 0;
}

Multidimensional Arrays

    #include <stdio.h>

    int main() {
        int grades[2][5];
        float average;
        int i;
        int j;

        grades[0][0] = 80;
        grades[0][1] = 70;
        grades[0][2] = 65;
        grades[0][3] = 89;
        grades[0][4] = 90;

        grades[1][0] = 85;
        grades[1][1] = 80;
        grades[1][2] = 80;
        grades[1][3] = 82;
        grades[1][4] = 87;

        for (i = 0; i < 2; i++) {
            average = 0;
            
            for (j = 0; j < 5; j++) {
                average += grades[i][j];
            }

            average /= 5.0;
            printf("The average marks obtained in subject %d is: %.2f\n", i, average);
        }

        return 0;
    }

Conditions

#include <stdio.h>

void guessNumber(int guess) {
    // TODO: write your code here
    if (guess < 555) {
        printf("Your guess is too low.\n");
    } else if (guess > 555) {
        printf("Your guess is too high.\n");
    } else {
        printf("Correct. You guessed it!\n");
    }
}

int main() {
    guessNumber(500);
    guessNumber(600);
    guessNumber(555);
}

Strings

#include <stdio.h>
#include <string.h>
int main() {
  char * first_name = "John";
  char last_name[] = "Doe";
  char name[100];

  last_name[0] = 'B';
  sprintf(name, "%s %s", first_name, last_name);
  if (strncmp(name, "John Boe", 100) == 0) {
      printf("Done!\n");
  }
  name[0]='\0';
  strncat(name,first_name,4);
  strncat(name,last_name,20);
  printf("%s\n",name);
  return 0;
}

for loop

#include <stdio.h>

int main() {
  int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  int factorial = 1;

  int i;

  for(i=0;i<10;i++){
    factorial *= array[i];
  }

  printf("10! is %d.\n", factorial);
}

while loop

#include <stdio.h>

int main() {
    int array[] = {1, 7, 4, 5, 9, 3, 5, 11, 6, 3, 4};
    int i = 0;

    while (i < 10) {
        if(array[i] < 5){
            i++;
            continue;
        }

        if(array[i] > 10){
            break;
        }

        printf("%d\n", array[i]);
        i++;
    }

    return 0;
}

function

#include <stdio.h>

/* function declaration */
void print_big(int number);

int main() {
  int array[] = { 1, 11, 2, 22, 3, 33 };
  int i;
  for (i = 0; i < 6; i++) {
    print_big(array[i]);
  }
  return 0;
}

void print_big(int number){
    if(number > 10){
        printf("%d is big\n",number);
    }
}

static

   #include <stdio.h>
   int sum (int num) {
       static int total = 0;
       total += num;
       return total;
   }

   int main() {
       printf("%d ",sum(55));
       printf("%d ",sum(45));
       printf("%d ",sum(50));
       return 0;
   }

pointers

Pointers are also variables and play a very important role in C programming language. They are used for several reasons, such as:
Strings
Dynamic memory allocation
Sending function arguments by reference
Building complicated data structures
Pointing to functions
Building special data structures (i.e. Tree, Tries, etc...)

#include <stdio.h>

int main() {
  int n = 10;

  int * pointer_to_n = &n;

  *pointer_to_n += 1;

  /* testing code */
  if (pointer_to_n != &n) return 1;
  if (*pointer_to_n != 11) return 1;

  printf("Done!\n");
  return 0;
}

Structures

C structures are special, large variables which contain several named variables inside. Structures are the basic foundation for objects and classes in C. Structures are used for:Serialization of data
Passing multiple arguments in and out of functions through a single argument
Data structures such as linked lists, binary trees, and more

Typedefs allow us to define types with a different name

#include <stdio.h>

typedef struct {
    char * name;
    int age;
} person;

int main() {
    person john;

    /* testing code */
    john.name = "John";
    john.age = 27;
    printf("%s is %d years old.", john.name, john.age);
}

Function arguments by reference

#include <stdio.h>

typedef struct {
  char * name;
  int age;
} person;



void birthday(person * p){
    (*p).age += 1;
}

int main() {
  person john;
  john.name = "John";
  john.age = 27;

  printf("%s is %d years old.\n", john.name, john.age);
  birthday(&john);
  printf("Happy birthday! %s is now %d years old.\n", john.name, john.age);

  return 0;
}

Dynamic allocation

Dynamic allocation of memory is a very important subject in C. It allows building complex data structures such as linked lists. Allocating memory dynamically helps us to store data without initially knowing the size of the data in the time we wrote the program.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
  int x;
  int y;
} point;

int main() {
  point * mypoint;

  mypoint = malloc(sizeof(point));

  mypoint->x = 10;
  mypoint->y =5 ;
  printf("mypoint coordinates: %d, %d\n", mypoint->x, mypoint->y);

  free(mypoint);
  return 0;
}

Arrays and Pointers

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i, j;
    /* TODO: define the 2D pointer variable here */
    int **pnumbers;

    /* TODO: Complete the following line to allocate memory for holding three rows */
    pnumbers = (int **) malloc(3  *sizeof(int *));

    /* TODO: Allocate memory for storing the individual elements in a row */
    pnumbers[0] = (int *) malloc(1 * sizeof(int));
    pnumbers[1] = (int *) malloc(2 * sizeof(int));
    pnumbers[2] = (int *) malloc(3 * sizeof(int));

    pnumbers[0][0] = 1;
    pnumbers[1][0] = 1;
    pnumbers[1][1] = 1;
    pnumbers[2][0] = 1;
    pnumbers[2][1] = 2;
    pnumbers[2][2] = 1;

    for (i = 0; i < 3; i++) {
        for (j = 0; j <= i; j++) {
            printf("%d", pnumbers[i][j]);
        }
        printf("\n");
    }

    for (i = 0; i < 3; i++) {
        free(pnumbers[i]);
    }

    free(pnumbers);

  return 0;
}

Recursion

#include <stdio.h>

int main() {
    /* testing code */
    printf("1! = %i\n", factorial(1));
    printf("3! = %i\n", factorial(3));
    printf("5! = %i\n", factorial(5));
}

int factorial(int number){
    int f = number;
    if(number > 1){
        f *= factorial(number-1);
    }
return f;
}

Linked lists

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int val;
    struct node * next;
} node_t;

void print_list(node_t * head) {
    node_t * current = head;

    while (current != NULL) {
        printf("%d\n", current->val);
        current = current->next;
    }
}

int pop(node_t ** head) {
    int retval = -1;
    node_t * next_node = NULL;

    if (*head == NULL) {
        return -1;
    }

    next_node = (*head)->next;
    retval = (*head)->val;
    free(*head);
    *head = next_node;

    return retval;
}

int remove_by_value(node_t ** head, int val) {
    node_t *previous, *current;

    if (*head == NULL) {
        return -1;
    }

    if ((*head)->val == val) {
        return pop(head);
    }

    previous = current = (*head)->next;
    while (current) {
        if (current->val == val) {
            previous->next = current->next;
            free(current);
            return val;
        }

        previous = current;
        current  = current->next;
    }
    return -1;
}

void delete_list(node_t *head) {
    node_t  *current = head, 
            *next = head;

    while (current) {
        next = current->next;
        free(current);
        current = next;
    }
}

int main(void) {
    node_t * test_list = malloc(sizeof(node_t));

    test_list->val = 1;
    test_list->next = malloc(sizeof(node_t));
    test_list->next->val = 2;
    test_list->next->next = malloc(sizeof(node_t));
    test_list->next->next->val = 3;
    test_list->next->next->next = malloc(sizeof(node_t));
    test_list->next->next->next->val = 4;
    test_list->next->next->next->next = NULL;

    remove_by_value(&test_list, 3);

    print_list(test_list);
    delete_list(test_list);

    return EXIT_SUCCESS;
}

Binary trees

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
  int val;
  struct node * left;
  struct node * right;
} node_t;

void insert(node_t * tree,int val);
void print_tree(node_t * current);
void printDFS(node_t * current);

int main()
{
  node_t * test_list = malloc(sizeof(node_t));
  /* set values explicitly, alternative would be calloc() */
  test_list->val = 0;
  test_list->left = NULL;
  test_list->right = NULL;

  insert(test_list,5);
  insert(test_list,8);
  insert(test_list,4);
  insert(test_list,3);

  printDFS(test_list);
  printf("\n");
}

void insert(node_t * tree, int val)
{
  if (tree->val == 0)
  {
    /* insert on current (empty) position */
    tree->val=val;
  }
  else
  {
    if (val < tree->val)
    {
      /* insert left */
      if (tree->left != NULL)
      {
        insert(tree->left, val);
      }
      else
      {
        tree->left = malloc(sizeof(node_t));
        /* set values explicitly, alternative would be calloc() */
        tree->left->val = val;
        tree->left->left = NULL;
        tree->left->right = NULL;
      }
    }
    else
    {
      if (val >= tree->val)
      {
        /* insert right */
        if (tree->right != NULL)
        {
          insert(tree->right,val);
        }
        else
        {
          tree->right=malloc(sizeof(node_t));
          /* set values explicitly, alternative would be calloc() */
          tree->right->val=val;
          tree->right->left = NULL;
          tree->right->right = NULL;
        }
      }
    }
  }
}

/* depth-first search */
void printDFS(node_t * current)
{
  /* change the code here */
  if (current == NULL)         return;   /* security measure */
  if (current != NULL)         printf("%d ", current->val);
  if (current->left != NULL)   printDFS(current->left);
  if (current->right != NULL)  printDFS(current->right);
}

Unions

    #include <stdio.h>
  
    union hiddenMessage {
        int  ints[6];
        char chars[21];
    };
  
    int main() {
        union hiddenMessage intCharacters = {{1853169737, 1936876900, 1684955508, 1768838432, 561213039, 0}};
    
        printf("[");
        // only go to 18 because 1 byte is for the terminating 0 and we don't print the last in the loop
        for(int i = 0; i < 19; ++i)
            printf("%c, ", intCharacters.chars[i]);
        printf("%c]\n", intCharacters.chars[19]);
        printf("%s\n", intCharacters.chars);
    }

Pointer Arithmetics

    #include <stdio.h>

    int main() {
        int intarray[5] = {10,20,30,40,50};
        //-----------------------^
        int *pointer = &intarray[2];

        int *parray[3];

        int i;
        for (i = 0; i < 3; i++) {
            parray[i] = pointer + i;
        }

        for (i = 0; i < 3; i++) {
            if (parray[i] == &pointer[i]) {
                printf("Matched!\n");
            } else {
                printf("Fail\n");
            }
        }

        return 0;
    }
  
  

Function Pointers

    #include <stdio.h>

    void f1(int var)
    {
            printf("this is f1 and var is: %d\n", var);
    }

    void f2(int var)
    {
            printf("this is f2 and var is: %d\n", var);
    }

    void f3(int var)
    {
            printf("this is f3 and var is: %d\n", var);
    }

    int main()
    {
        void (*pf[])(int) = {f1, f2, f3};

        int c = 0;
        while(c < 3)
        {
            pf[c](c);
            ++c;
        }

        return 0;
    }

相关文章

  • 【算法笔记】C语言基础

    最近开始学习算法和数据机构的相关书籍。需要用到C语言做算法描述,同时对比下Java语言。所以复习到大一学过的C语言...

  • C基础算法

    C语言的学习要从基础开始,这里是100个经典的算法-1C语言的学习要从基础开始,这里是100个经典的 算法 题目:...

  • 阶段02#大三·下

    A 书籍 C程序设计语言 Java学习指南 C++语言基础教程 数据结构与算法分析 算法设计与分析基础 计算机网络...

  • 100000571 - 《算法笔记》2.7小节——C/C++快速

    100000571 - 《算法笔记》2.7小节——C/C++快速入门->指针 问题 A: C语言10.1 [命题人...

  • 开工

    能力地图 基础技术能力 架构能力 项目管理能力 基础技术能力 基础技术,如数据结构、算法 编程语言,如c/c++/...

  • C语言程序设计教程(1)

    第一章是C语言程序设计基础,介绍了该语言是用来干嘛的,什么是算法和对算法的描述,C语言的来龙去脉,特点结构及上机步...

  • 如何学习数据结构与算法

    算法学习经验 推荐: 入门: 数据结构启蒙:《数据结构与算法分析——C 语言描述》 算法启蒙:《算法设计与分析基础...

  • 2018 阅读技术图书目录

    C语言从入门到精通(第2版) (软件开发视频大讲堂) 零基础学C++ 第2版 (零基础学编程) 算法精解:C语言描...

  • C语言基础教程之递归

    一文读懂C语言递归算法,C语言基础教程之递归 C语言递归 递归指的是在函数的定义中使用函数自身的方法。 从前有座山...

  • C语言基础-基本算法

    在之前的两篇文章中介绍了C语言的入门程序入门程序1,入门程序2,从这篇文章我们就开始介绍C语言基础。今天来给大家介...

网友评论

    本文标题:【算法笔记】C语言基础

    本文链接:https://www.haomeiwen.com/subject/ioyvnctx.html